1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// \brief This file implements semantic analysis for OpenMP directives and
13 //===----------------------------------------------------------------------===//
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclOpenMP.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtOpenMP.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeOrdering.h"
26 #include "clang/Basic/OpenMPKinds.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/Initialization.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/Scope.h"
32 #include "clang/Sema/ScopeInfo.h"
33 #include "clang/Sema/SemaInternal.h"
34 using namespace clang;
36 //===----------------------------------------------------------------------===//
37 // Stack of data-sharing attributes for variables
38 //===----------------------------------------------------------------------===//
41 /// \brief Default data sharing attributes, which can be applied to directive.
42 enum DefaultDataSharingAttributes {
43 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
48 /// \brief Stack for tracking declarations used in OpenMP directives and
49 /// clauses and their data-sharing attributes.
50 class DSAStackTy final {
52 struct DSAVarData final {
53 OpenMPDirectiveKind DKind = OMPD_unknown;
54 OpenMPClauseKind CKind = OMPC_unknown;
55 Expr *RefExpr = nullptr;
56 DeclRefExpr *PrivateCopy = nullptr;
57 SourceLocation ImplicitDSALoc;
60 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
64 struct DSAInfo final {
65 OpenMPClauseKind Attributes = OMPC_unknown;
66 /// Pointer to a reference expression and a flag which shows that the
67 /// variable is marked as lastprivate(true) or not (false).
68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
69 DeclRefExpr *PrivateCopy = nullptr;
71 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
73 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
75 /// Struct that associates a component with the clause kind where they are
77 struct MappedExprComponentTy {
78 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
79 OpenMPClauseKind Kind = OMPC_unknown;
81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
82 MappedExprComponentsTy;
83 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
85 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
88 struct SharingMapTy final {
89 DeclSAMapTy SharingMap;
90 AlignedMapTy AlignedMap;
91 MappedExprComponentsTy MappedExprComponents;
92 LoopControlVariablesMapTy LCVMap;
93 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
94 SourceLocation DefaultAttrLoc;
95 OpenMPDirectiveKind Directive = OMPD_unknown;
96 DeclarationNameInfo DirectiveName;
97 Scope *CurScope = nullptr;
98 SourceLocation ConstructLoc;
99 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
100 /// get the data (loop counters etc.) about enclosing loop-based construct.
101 /// This data is required during codegen.
102 DoacrossDependMapTy DoacrossDepends;
103 /// \brief first argument (Expr *) contains optional argument of the
104 /// 'ordered' clause, the second one is true if the regions has 'ordered'
105 /// clause, false otherwise.
106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
107 bool NowaitRegion = false;
108 bool CancelRegion = false;
109 unsigned AssociatedLoops = 1;
110 SourceLocation InnerTeamsRegionLoc;
111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
112 Scope *CurScope, SourceLocation Loc)
113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
118 typedef SmallVector<SharingMapTy, 4> StackTy;
120 /// \brief Stack of used declaration and their data-sharing attributes.
122 /// \brief true, if check for DSA must be from parent directive, false, if
123 /// from current directive.
124 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
126 bool ForceCapturing = false;
127 CriticalsWithHintsTy Criticals;
129 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
131 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
133 /// \brief Checks if the variable is a local for OpenMP region.
134 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
137 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
139 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
140 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
142 bool isForceVarCapturing() const { return ForceCapturing; }
143 void setForceVarCapturing(bool V) { ForceCapturing = V; }
145 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
146 Scope *CurScope, SourceLocation Loc) {
147 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
148 Stack.back().DefaultAttrLoc = Loc;
152 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
156 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
157 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
159 const std::pair<OMPCriticalDirective *, llvm::APSInt>
160 getCriticalWithHint(const DeclarationNameInfo &Name) const {
161 auto I = Criticals.find(Name.getAsString());
162 if (I != Criticals.end())
164 return std::make_pair(nullptr, llvm::APSInt());
166 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
167 /// add it and return NULL; otherwise return previous occurrence's expression
169 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
171 /// \brief Register specified variable as loop control variable.
172 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
173 /// \brief Check if the specified variable is a loop control variable for
175 /// \return The index of the loop control variable in the list of associated
176 /// for-loops (from outer to inner).
177 LCDeclInfo isLoopControlVariable(ValueDecl *D);
178 /// \brief Check if the specified variable is a loop control variable for
180 /// \return The index of the loop control variable in the list of associated
181 /// for-loops (from outer to inner).
182 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
183 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
184 /// parent directive.
185 ValueDecl *getParentLoopControlVariable(unsigned I);
187 /// \brief Adds explicit data sharing attribute to the specified declaration.
188 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
189 DeclRefExpr *PrivateCopy = nullptr);
191 /// \brief Returns data sharing attributes from top of the stack for the
192 /// specified declaration.
193 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
194 /// \brief Returns data-sharing attributes for the specified declaration.
195 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
196 /// \brief Checks if the specified variables has data-sharing attributes which
197 /// match specified \a CPred predicate in any directive which matches \a DPred
199 DSAVarData hasDSA(ValueDecl *D,
200 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
201 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
203 /// \brief Checks if the specified variables has data-sharing attributes which
204 /// match specified \a CPred predicate in any innermost directive which
205 /// matches \a DPred predicate.
207 hasInnermostDSA(ValueDecl *D,
208 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
209 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
211 /// \brief Checks if the specified variables has explicit data-sharing
212 /// attributes which match specified \a CPred predicate at the specified
214 bool hasExplicitDSA(ValueDecl *D,
215 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
216 unsigned Level, bool NotLastprivate = false);
218 /// \brief Returns true if the directive at level \Level matches in the
219 /// specified \a DPred predicate.
220 bool hasExplicitDirective(
221 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
224 /// \brief Finds a directive which matches specified \a DPred predicate.
225 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
226 const DeclarationNameInfo &,
227 SourceLocation)> &DPred,
230 /// \brief Returns currently analyzed directive.
231 OpenMPDirectiveKind getCurrentDirective() const {
232 return Stack.back().Directive;
234 /// \brief Returns parent directive.
235 OpenMPDirectiveKind getParentDirective() const {
236 if (Stack.size() > 2)
237 return Stack[Stack.size() - 2].Directive;
241 /// \brief Set default data sharing attribute to none.
242 void setDefaultDSANone(SourceLocation Loc) {
243 Stack.back().DefaultAttr = DSA_none;
244 Stack.back().DefaultAttrLoc = Loc;
246 /// \brief Set default data sharing attribute to shared.
247 void setDefaultDSAShared(SourceLocation Loc) {
248 Stack.back().DefaultAttr = DSA_shared;
249 Stack.back().DefaultAttrLoc = Loc;
252 DefaultDataSharingAttributes getDefaultDSA() const {
253 return Stack.back().DefaultAttr;
255 SourceLocation getDefaultDSALocation() const {
256 return Stack.back().DefaultAttrLoc;
259 /// \brief Checks if the specified variable is a threadprivate.
260 bool isThreadPrivate(VarDecl *D) {
261 DSAVarData DVar = getTopDSA(D, false);
262 return isOpenMPThreadPrivate(DVar.CKind);
265 /// \brief Marks current region as ordered (it has an 'ordered' clause).
266 void setOrderedRegion(bool IsOrdered, Expr *Param) {
267 Stack.back().OrderedRegion.setInt(IsOrdered);
268 Stack.back().OrderedRegion.setPointer(Param);
270 /// \brief Returns true, if parent region is ordered (has associated
271 /// 'ordered' clause), false - otherwise.
272 bool isParentOrderedRegion() const {
273 if (Stack.size() > 2)
274 return Stack[Stack.size() - 2].OrderedRegion.getInt();
277 /// \brief Returns optional parameter for the ordered region.
278 Expr *getParentOrderedRegionParam() const {
279 if (Stack.size() > 2)
280 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
283 /// \brief Marks current region as nowait (it has a 'nowait' clause).
284 void setNowaitRegion(bool IsNowait = true) {
285 Stack.back().NowaitRegion = IsNowait;
287 /// \brief Returns true, if parent region is nowait (has associated
288 /// 'nowait' clause), false - otherwise.
289 bool isParentNowaitRegion() const {
290 if (Stack.size() > 2)
291 return Stack[Stack.size() - 2].NowaitRegion;
294 /// \brief Marks parent region as cancel region.
295 void setParentCancelRegion(bool Cancel = true) {
296 if (Stack.size() > 2)
297 Stack[Stack.size() - 2].CancelRegion =
298 Stack[Stack.size() - 2].CancelRegion || Cancel;
300 /// \brief Return true if current region has inner cancel construct.
301 bool isCancelRegion() const { return Stack.back().CancelRegion; }
303 /// \brief Set collapse value for the region.
304 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
305 /// \brief Return collapse value for region.
306 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
308 /// \brief Marks current target region as one with closely nested teams
310 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
311 if (Stack.size() > 2)
312 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
314 /// \brief Returns true, if current region has closely nested teams region.
315 bool hasInnerTeamsRegion() const {
316 return getInnerTeamsRegionLoc().isValid();
318 /// \brief Returns location of the nested teams region (if any).
319 SourceLocation getInnerTeamsRegionLoc() const {
320 if (Stack.size() > 1)
321 return Stack.back().InnerTeamsRegionLoc;
322 return SourceLocation();
325 Scope *getCurScope() const { return Stack.back().CurScope; }
326 Scope *getCurScope() { return Stack.back().CurScope; }
327 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
329 /// Do the check specified in \a Check to all component lists and return true
330 /// if any issue is found.
331 bool checkMappableExprComponentListsForDecl(
332 ValueDecl *VD, bool CurrentRegionOnly,
333 const llvm::function_ref<
334 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
335 OpenMPClauseKind)> &Check) {
336 auto SI = Stack.rbegin();
337 auto SE = Stack.rend();
342 if (CurrentRegionOnly) {
348 for (; SI != SE; ++SI) {
349 auto MI = SI->MappedExprComponents.find(VD);
350 if (MI != SI->MappedExprComponents.end())
351 for (auto &L : MI->second.Components)
352 if (Check(L, MI->second.Kind))
358 /// Create a new mappable expression component list associated with a given
359 /// declaration and initialize it with the provided list of components.
360 void addMappableExpressionComponents(
362 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
363 OpenMPClauseKind WhereFoundClauseKind) {
364 assert(Stack.size() > 1 &&
365 "Not expecting to retrieve components from a empty stack!");
366 auto &MEC = Stack.back().MappedExprComponents[VD];
367 // Create new entry and append the new components there.
368 MEC.Components.resize(MEC.Components.size() + 1);
369 MEC.Components.back().append(Components.begin(), Components.end());
370 MEC.Kind = WhereFoundClauseKind;
373 unsigned getNestingLevel() const {
374 assert(Stack.size() > 1);
375 return Stack.size() - 2;
377 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
378 assert(Stack.size() > 2);
379 assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive));
380 Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs});
382 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
383 getDoacrossDependClauses() const {
384 assert(Stack.size() > 1);
385 if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) {
386 auto &Ref = Stack[Stack.size() - 1].DoacrossDepends;
387 return llvm::make_range(Ref.begin(), Ref.end());
389 return llvm::make_range(Stack[0].DoacrossDepends.end(),
390 Stack[0].DoacrossDepends.end());
393 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
394 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
395 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
399 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
400 auto *VD = dyn_cast<VarDecl>(D);
401 auto *FD = dyn_cast<FieldDecl>(D);
403 VD = VD->getCanonicalDecl();
407 FD = FD->getCanonicalDecl();
413 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
415 D = getCanonicalDecl(D);
416 auto *VD = dyn_cast<VarDecl>(D);
417 auto *FD = dyn_cast<FieldDecl>(D);
419 if (Iter == std::prev(Stack.rend())) {
420 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
421 // in a region but not in construct]
422 // File-scope or namespace-scope variables referenced in called routines
423 // in the region are shared unless they appear in a threadprivate
425 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
426 DVar.CKind = OMPC_shared;
428 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
429 // in a region but not in construct]
430 // Variables with static storage duration that are declared in called
431 // routines in the region are shared.
432 if (VD && VD->hasGlobalStorage())
433 DVar.CKind = OMPC_shared;
435 // Non-static data members are shared by default.
437 DVar.CKind = OMPC_shared;
442 DVar.DKind = Iter->Directive;
443 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
444 // in a Construct, C/C++, predetermined, p.1]
445 // Variables with automatic storage duration that are declared in a scope
446 // inside the construct are private.
447 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
448 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
449 DVar.CKind = OMPC_private;
453 // Explicitly specified attributes and local variables with predetermined
455 if (Iter->SharingMap.count(D)) {
456 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
457 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
458 DVar.CKind = Iter->SharingMap[D].Attributes;
459 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
463 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
464 // in a Construct, C/C++, implicitly determined, p.1]
465 // In a parallel or task construct, the data-sharing attributes of these
466 // variables are determined by the default clause, if present.
467 switch (Iter->DefaultAttr) {
469 DVar.CKind = OMPC_shared;
470 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
474 case DSA_unspecified:
475 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
476 // in a Construct, implicitly determined, p.2]
477 // In a parallel construct, if no default clause is present, these
478 // variables are shared.
479 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
480 if (isOpenMPParallelDirective(DVar.DKind) ||
481 isOpenMPTeamsDirective(DVar.DKind)) {
482 DVar.CKind = OMPC_shared;
486 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
487 // in a Construct, implicitly determined, p.4]
488 // In a task construct, if no default clause is present, a variable that in
489 // the enclosing context is determined to be shared by all implicit tasks
490 // bound to the current team is shared.
491 if (isOpenMPTaskingDirective(DVar.DKind)) {
493 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
495 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
496 // Referenced in a Construct, implicitly determined, p.6]
497 // In a task construct, if no default clause is present, a variable
498 // whose data-sharing attribute is not determined by the rules above is
500 DVarTemp = getDSA(I, D);
501 if (DVarTemp.CKind != OMPC_shared) {
502 DVar.RefExpr = nullptr;
503 DVar.CKind = OMPC_firstprivate;
506 if (isParallelOrTaskRegion(I->Directive))
510 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
514 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
515 // in a Construct, implicitly determined, p.3]
516 // For constructs other than task, if no default clause is present, these
517 // variables inherit their data-sharing attributes from the enclosing
519 return getDSA(++Iter, D);
522 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
523 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
524 D = getCanonicalDecl(D);
525 auto It = Stack.back().AlignedMap.find(D);
526 if (It == Stack.back().AlignedMap.end()) {
527 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
528 Stack.back().AlignedMap[D] = NewDE;
531 assert(It->second && "Unexpected nullptr expr in the aligned map");
537 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
538 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
539 D = getCanonicalDecl(D);
540 Stack.back().LCVMap.insert(
541 std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
544 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
545 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
546 D = getCanonicalDecl(D);
547 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
548 : LCDeclInfo(0, nullptr);
551 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
552 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
553 D = getCanonicalDecl(D);
554 return Stack[Stack.size() - 2].LCVMap.count(D) > 0
555 ? Stack[Stack.size() - 2].LCVMap[D]
556 : LCDeclInfo(0, nullptr);
559 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
560 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
561 if (Stack[Stack.size() - 2].LCVMap.size() < I)
563 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
564 if (Pair.second.first == I)
570 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
571 DeclRefExpr *PrivateCopy) {
572 D = getCanonicalDecl(D);
573 if (A == OMPC_threadprivate) {
574 auto &Data = Stack[0].SharingMap[D];
576 Data.RefExpr.setPointer(E);
577 Data.PrivateCopy = nullptr;
579 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
580 auto &Data = Stack.back().SharingMap[D];
581 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
582 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
583 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
584 (isLoopControlVariable(D).first && A == OMPC_private));
585 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
586 Data.RefExpr.setInt(/*IntVal=*/true);
589 const bool IsLastprivate =
590 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
592 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
593 Data.PrivateCopy = PrivateCopy;
595 auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()];
597 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
598 Data.PrivateCopy = nullptr;
603 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
604 D = D->getCanonicalDecl();
605 if (Stack.size() > 2) {
606 reverse_iterator I = Iter, E = std::prev(Stack.rend());
607 Scope *TopScope = nullptr;
608 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
613 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
614 Scope *CurScope = getCurScope();
615 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
616 CurScope = CurScope->getParent();
618 return CurScope != TopScope;
623 /// \brief Build a variable declaration for OpenMP loop iteration variable.
624 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
625 StringRef Name, const AttrVec *Attrs = nullptr) {
626 DeclContext *DC = SemaRef.CurContext;
627 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
628 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
630 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
632 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
640 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
642 bool RefersToCapture = false) {
644 D->markUsed(S.Context);
645 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
646 SourceLocation(), D, RefersToCapture, Loc, Ty,
650 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
651 D = getCanonicalDecl(D);
654 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
655 // in a Construct, C/C++, predetermined, p.1]
656 // Variables appearing in threadprivate directives are threadprivate.
657 auto *VD = dyn_cast<VarDecl>(D);
658 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
659 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
660 SemaRef.getLangOpts().OpenMPUseTLS &&
661 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
662 (VD && VD->getStorageClass() == SC_Register &&
663 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
664 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
668 if (Stack[0].SharingMap.count(D)) {
669 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer();
670 DVar.CKind = OMPC_threadprivate;
674 if (Stack.size() == 1) {
675 // Not in OpenMP execution region and top scope was already checked.
679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
680 // in a Construct, C/C++, predetermined, p.4]
681 // Static data members are shared.
682 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
683 // in a Construct, C/C++, predetermined, p.7]
684 // Variables with static storage duration that are declared in a scope
685 // inside the construct are shared.
686 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
687 if (VD && VD->isStaticDataMember()) {
688 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
689 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
692 DVar.CKind = OMPC_shared;
696 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
697 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
698 Type = SemaRef.getASTContext().getBaseElementType(Type);
699 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
700 // in a Construct, C/C++, predetermined, p.6]
701 // Variables with const qualified type having no mutable member are
704 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
705 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
706 if (auto *CTD = CTSD->getSpecializedTemplate())
707 RD = CTD->getTemplatedDecl();
709 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
710 RD->hasMutableFields())) {
711 // Variables with const-qualified type having no mutable member may be
712 // listed in a firstprivate clause, even if they are static data members.
713 DSAVarData DVarTemp = hasDSA(
714 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
715 MatchesAlways, FromParent);
716 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
719 DVar.CKind = OMPC_shared;
723 // Explicitly specified attributes and local variables with predetermined
725 auto StartI = std::next(Stack.rbegin());
726 auto EndI = std::prev(Stack.rend());
727 if (FromParent && StartI != EndI) {
728 StartI = std::next(StartI);
730 auto I = std::prev(StartI);
731 if (I->SharingMap.count(D)) {
732 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
733 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
734 DVar.CKind = I->SharingMap[D].Attributes;
735 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
741 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
743 D = getCanonicalDecl(D);
744 auto StartI = Stack.rbegin();
745 auto EndI = std::prev(Stack.rend());
746 if (FromParent && StartI != EndI) {
747 StartI = std::next(StartI);
749 return getDSA(StartI, D);
752 DSAStackTy::DSAVarData
753 DSAStackTy::hasDSA(ValueDecl *D,
754 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
755 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
757 D = getCanonicalDecl(D);
758 auto StartI = std::next(Stack.rbegin());
759 auto EndI = Stack.rend();
760 if (FromParent && StartI != EndI) {
761 StartI = std::next(StartI);
763 for (auto I = StartI, EE = EndI; I != EE; ++I) {
764 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
766 DSAVarData DVar = getDSA(I, D);
767 if (CPred(DVar.CKind))
773 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
774 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
775 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
777 D = getCanonicalDecl(D);
778 auto StartI = std::next(Stack.rbegin());
779 auto EndI = Stack.rend();
780 if (FromParent && StartI != EndI)
781 StartI = std::next(StartI);
782 if (StartI == EndI || !DPred(StartI->Directive))
784 DSAVarData DVar = getDSA(StartI, D);
785 return CPred(DVar.CKind) ? DVar : DSAVarData();
788 bool DSAStackTy::hasExplicitDSA(
789 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
790 unsigned Level, bool NotLastprivate) {
791 if (CPred(ClauseKindMode))
793 D = getCanonicalDecl(D);
794 auto StartI = std::next(Stack.begin());
795 auto EndI = Stack.end();
796 if (std::distance(StartI, EndI) <= (int)Level)
798 std::advance(StartI, Level);
799 return (StartI->SharingMap.count(D) > 0) &&
800 StartI->SharingMap[D].RefExpr.getPointer() &&
801 CPred(StartI->SharingMap[D].Attributes) &&
802 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
805 bool DSAStackTy::hasExplicitDirective(
806 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
808 auto StartI = std::next(Stack.begin());
809 auto EndI = Stack.end();
810 if (std::distance(StartI, EndI) <= (int)Level)
812 std::advance(StartI, Level);
813 return DPred(StartI->Directive);
816 bool DSAStackTy::hasDirective(
817 const llvm::function_ref<bool(OpenMPDirectiveKind,
818 const DeclarationNameInfo &, SourceLocation)>
821 // We look only in the enclosing region.
822 if (Stack.size() < 2)
824 auto StartI = std::next(Stack.rbegin());
825 auto EndI = std::prev(Stack.rend());
826 if (FromParent && StartI != EndI) {
827 StartI = std::next(StartI);
829 for (auto I = StartI, EE = EndI; I != EE; ++I) {
830 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
836 void Sema::InitDataSharingAttributesStack() {
837 VarDataSharingAttributesStack = new DSAStackTy(*this);
840 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
842 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
843 assert(LangOpts.OpenMP && "OpenMP is not allowed");
845 auto &Ctx = getASTContext();
848 // Find the directive that is associated with the provided scope.
849 auto Ty = D->getType();
851 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
852 // This table summarizes how a given variable should be passed to the device
853 // given its type and the clauses where it appears. This table is based on
854 // the description in OpenMP 4.5 [2.10.4, target Construct] and
855 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
857 // =========================================================================
858 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
859 // | |(tofrom:scalar)| | pvt | | | |
860 // =========================================================================
861 // | scl | | | | - | | bycopy|
862 // | scl | | - | x | - | - | bycopy|
863 // | scl | | x | - | - | - | null |
864 // | scl | x | | | - | | byref |
865 // | scl | x | - | x | - | - | bycopy|
866 // | scl | x | x | - | - | - | null |
867 // | scl | | - | - | - | x | byref |
868 // | scl | x | - | - | - | x | byref |
870 // | agg | n.a. | | | - | | byref |
871 // | agg | n.a. | - | x | - | - | byref |
872 // | agg | n.a. | x | - | - | - | null |
873 // | agg | n.a. | - | - | - | x | byref |
874 // | agg | n.a. | - | - | - | x[] | byref |
876 // | ptr | n.a. | | | - | | bycopy|
877 // | ptr | n.a. | - | x | - | - | bycopy|
878 // | ptr | n.a. | x | - | - | - | null |
879 // | ptr | n.a. | - | - | - | x | byref |
880 // | ptr | n.a. | - | - | - | x[] | bycopy|
881 // | ptr | n.a. | - | - | x | | bycopy|
882 // | ptr | n.a. | - | - | x | x | bycopy|
883 // | ptr | n.a. | - | - | x | x[] | bycopy|
884 // =========================================================================
890 // - - invalid in this combination
891 // [] - mapped with an array section
892 // byref - should be mapped by reference
893 // byval - should be mapped by value
894 // null - initialize a local variable to null on the device
897 // - All scalar declarations that show up in a map clause have to be passed
898 // by reference, because they may have been mapped in the enclosing data
900 // - If the scalar value does not fit the size of uintptr, it has to be
901 // passed by reference, regardless the result in the table above.
902 // - For pointers mapped by value that have either an implicit map or an
903 // array section, the runtime library may pass the NULL value to the
904 // device instead of the value passed to it by the compiler.
906 if (Ty->isReferenceType())
907 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
909 // Locate map clauses and see if the variable being captured is referred to
910 // in any of those clauses. Here we only care about variables, not fields,
911 // because fields are part of aggregates.
912 bool IsVariableUsedInMapClause = false;
913 bool IsVariableAssociatedWithSection = false;
915 DSAStack->checkMappableExprComponentListsForDecl(
916 D, /*CurrentRegionOnly=*/true,
917 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
919 OpenMPClauseKind WhereFoundClauseKind) {
920 // Only the map clause information influences how a variable is
921 // captured. E.g. is_device_ptr does not require changing the default
923 if (WhereFoundClauseKind != OMPC_map)
926 auto EI = MapExprComponents.rbegin();
927 auto EE = MapExprComponents.rend();
929 assert(EI != EE && "Invalid map expression!");
931 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
932 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
938 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
939 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
940 isa<MemberExpr>(EI->getAssociatedExpression())) {
941 IsVariableAssociatedWithSection = true;
942 // There is nothing more we need to know about this variable.
946 // Keep looking for more map info.
950 if (IsVariableUsedInMapClause) {
951 // If variable is identified in a map clause it is always captured by
952 // reference except if it is a pointer that is dereferenced somehow.
953 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
955 // By default, all the data that has a scalar type is mapped by copy.
956 IsByRef = !Ty->isScalarType();
960 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
961 IsByRef = !DSAStack->hasExplicitDSA(
962 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
963 Level, /*NotLastprivate=*/true);
966 // When passing data by copy, we need to make sure it fits the uintptr size
967 // and alignment, because the runtime library only deals with uintptr types.
968 // If it does not fit the uintptr size, we need to pass the data by reference
971 (Ctx.getTypeSizeInChars(Ty) >
972 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
973 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
980 unsigned Sema::getOpenMPNestingLevel() const {
981 assert(getLangOpts().OpenMP);
982 return DSAStack->getNestingLevel();
985 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
986 assert(LangOpts.OpenMP && "OpenMP is not allowed");
987 D = getCanonicalDecl(D);
989 // If we are attempting to capture a global variable in a directive with
990 // 'target' we return true so that this global is also mapped to the device.
992 // FIXME: If the declaration is enclosed in a 'declare target' directive,
993 // then it should not be captured. Therefore, an extra check has to be
994 // inserted here once support for 'declare target' is added.
996 auto *VD = dyn_cast<VarDecl>(D);
997 if (VD && !VD->hasLocalStorage()) {
998 if (DSAStack->getCurrentDirective() == OMPD_target &&
999 !DSAStack->isClauseParsingMode())
1001 if (DSAStack->hasDirective(
1002 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1003 SourceLocation) -> bool {
1004 return isOpenMPTargetExecutionDirective(K);
1010 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1011 (!DSAStack->isClauseParsingMode() ||
1012 DSAStack->getParentDirective() != OMPD_unknown)) {
1013 auto &&Info = DSAStack->isLoopControlVariable(D);
1015 (VD && VD->hasLocalStorage() &&
1016 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
1017 (VD && DSAStack->isForceVarCapturing()))
1018 return VD ? VD : Info.second;
1019 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
1020 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
1021 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1022 DVarPrivate = DSAStack->hasDSA(
1023 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1024 DSAStack->isClauseParsingMode());
1025 if (DVarPrivate.CKind != OMPC_unknown)
1026 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1031 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
1032 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1033 return DSAStack->hasExplicitDSA(
1034 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
1037 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
1038 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1039 // Return true if the current level is no longer enclosed in a target region.
1041 auto *VD = dyn_cast<VarDecl>(D);
1042 return VD && !VD->hasLocalStorage() &&
1043 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1047 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
1049 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1050 const DeclarationNameInfo &DirName,
1051 Scope *CurScope, SourceLocation Loc) {
1052 DSAStack->push(DKind, DirName, CurScope, Loc);
1053 PushExpressionEvaluationContext(PotentiallyEvaluated);
1056 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1057 DSAStack->setClauseParsingMode(K);
1060 void Sema::EndOpenMPClause() {
1061 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1064 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1065 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1066 // A variable of class type (or array thereof) that appears in a lastprivate
1067 // clause requires an accessible, unambiguous default constructor for the
1068 // class type, unless the list item is also specified in a firstprivate
1070 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1071 for (auto *C : D->clauses()) {
1072 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1073 SmallVector<Expr *, 8> PrivateCopies;
1074 for (auto *DE : Clause->varlists()) {
1075 if (DE->isValueDependent() || DE->isTypeDependent()) {
1076 PrivateCopies.push_back(nullptr);
1079 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1080 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1081 QualType Type = VD->getType().getNonReferenceType();
1082 auto DVar = DSAStack->getTopDSA(VD, false);
1083 if (DVar.CKind == OMPC_lastprivate) {
1084 // Generate helper private variable and initialize it with the
1085 // default value. The address of the original variable is replaced
1086 // by the address of the new private variable in CodeGen. This new
1087 // variable is not added to IdResolver, so the code in the OpenMP
1088 // region uses original variable for proper diagnostics.
1089 auto *VDPrivate = buildVarDecl(
1090 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1091 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
1092 ActOnUninitializedDecl(VDPrivate);
1093 if (VDPrivate->isInvalidDecl())
1095 PrivateCopies.push_back(buildDeclRefExpr(
1096 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1098 // The variable is also a firstprivate, so initialization sequence
1099 // for private copy is generated already.
1100 PrivateCopies.push_back(nullptr);
1103 // Set initializers to private copies if no errors were found.
1104 if (PrivateCopies.size() == Clause->varlist_size())
1105 Clause->setPrivateCopies(PrivateCopies);
1111 DiscardCleanupsInEvaluationContext();
1112 PopExpressionEvaluationContext();
1115 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1116 Expr *NumIterations, Sema &SemaRef,
1117 Scope *S, DSAStackTy *Stack);
1121 class VarDeclFilterCCC : public CorrectionCandidateCallback {
1126 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1127 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1128 NamedDecl *ND = Candidate.getCorrectionDecl();
1129 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1130 return VD->hasGlobalStorage() &&
1131 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1132 SemaRef.getCurScope());
1138 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1143 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1144 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1145 NamedDecl *ND = Candidate.getCorrectionDecl();
1146 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1147 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1148 SemaRef.getCurScope());
1156 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1157 CXXScopeSpec &ScopeSpec,
1158 const DeclarationNameInfo &Id) {
1159 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1160 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1162 if (Lookup.isAmbiguous())
1166 if (!Lookup.isSingleResult()) {
1167 if (TypoCorrection Corrected = CorrectTypo(
1168 Id, LookupOrdinaryName, CurScope, nullptr,
1169 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1170 diagnoseTypo(Corrected,
1171 PDiag(Lookup.empty()
1172 ? diag::err_undeclared_var_use_suggest
1173 : diag::err_omp_expected_var_arg_suggest)
1175 VD = Corrected.getCorrectionDeclAs<VarDecl>();
1177 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1178 : diag::err_omp_expected_var_arg)
1183 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1184 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1185 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1189 Lookup.suppressDiagnostics();
1191 // OpenMP [2.9.2, Syntax, C/C++]
1192 // Variables must be file-scope, namespace-scope, or static block-scope.
1193 if (!VD->hasGlobalStorage()) {
1194 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1195 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1197 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1198 Diag(VD->getLocation(),
1199 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1204 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1205 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
1206 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1207 // A threadprivate directive for file-scope variables must appear outside
1208 // any definition or declaration.
1209 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1210 !getCurLexicalContext()->isTranslationUnit()) {
1211 Diag(Id.getLoc(), diag::err_omp_var_scope)
1212 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1214 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1215 Diag(VD->getLocation(),
1216 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1220 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1221 // A threadprivate directive for static class member variables must appear
1222 // in the class definition, in the same scope in which the member
1223 // variables are declared.
1224 if (CanonicalVD->isStaticDataMember() &&
1225 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1226 Diag(Id.getLoc(), diag::err_omp_var_scope)
1227 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1229 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1230 Diag(VD->getLocation(),
1231 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1235 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1236 // A threadprivate directive for namespace-scope variables must appear
1237 // outside any definition or declaration other than the namespace
1238 // definition itself.
1239 if (CanonicalVD->getDeclContext()->isNamespace() &&
1240 (!getCurLexicalContext()->isFileContext() ||
1241 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1242 Diag(Id.getLoc(), diag::err_omp_var_scope)
1243 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1245 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1246 Diag(VD->getLocation(),
1247 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1251 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1252 // A threadprivate directive for static block-scope variables must appear
1253 // in the scope of the variable and not in a nested scope.
1254 if (CanonicalVD->isStaticLocal() && CurScope &&
1255 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1256 Diag(Id.getLoc(), diag::err_omp_var_scope)
1257 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1259 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1260 Diag(VD->getLocation(),
1261 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1266 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1267 // A threadprivate directive must lexically precede all references to any
1268 // of the variables in its list.
1269 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1270 Diag(Id.getLoc(), diag::err_omp_var_used)
1271 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1275 QualType ExprType = VD->getType().getNonReferenceType();
1276 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1277 SourceLocation(), VD,
1278 /*RefersToEnclosingVariableOrCapture=*/false,
1279 Id.getLoc(), ExprType, VK_LValue);
1282 Sema::DeclGroupPtrTy
1283 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1284 ArrayRef<Expr *> VarList) {
1285 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1286 CurContext->addDecl(D);
1287 return DeclGroupPtrTy::make(DeclGroupRef(D));
1293 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1297 bool VisitDeclRefExpr(const DeclRefExpr *E) {
1298 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1299 if (VD->hasLocalStorage()) {
1300 SemaRef.Diag(E->getLocStart(),
1301 diag::err_omp_local_var_in_threadprivate_init)
1302 << E->getSourceRange();
1303 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1304 << VD << VD->getSourceRange();
1310 bool VisitStmt(const Stmt *S) {
1311 for (auto Child : S->children()) {
1312 if (Child && Visit(Child))
1317 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1321 OMPThreadPrivateDecl *
1322 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1323 SmallVector<Expr *, 8> Vars;
1324 for (auto &RefExpr : VarList) {
1325 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
1326 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1327 SourceLocation ILoc = DE->getExprLoc();
1329 // Mark variable as used.
1330 VD->setReferenced();
1331 VD->markUsed(Context);
1333 QualType QType = VD->getType();
1334 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1335 // It will be analyzed later.
1340 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1341 // A threadprivate variable must not have an incomplete type.
1342 if (RequireCompleteType(ILoc, VD->getType(),
1343 diag::err_omp_threadprivate_incomplete_type)) {
1347 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1348 // A threadprivate variable must not have a reference type.
1349 if (VD->getType()->isReferenceType()) {
1350 Diag(ILoc, diag::err_omp_ref_type_arg)
1351 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1353 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1354 Diag(VD->getLocation(),
1355 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1360 // Check if this is a TLS variable. If TLS is not being supported, produce
1361 // the corresponding diagnostic.
1362 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1363 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1364 getLangOpts().OpenMPUseTLS &&
1365 getASTContext().getTargetInfo().isTLSSupported())) ||
1366 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1367 !VD->isLocalVarDecl())) {
1368 Diag(ILoc, diag::err_omp_var_thread_local)
1369 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1371 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1372 Diag(VD->getLocation(),
1373 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1378 // Check if initial value of threadprivate variable reference variable with
1379 // local storage (it is not supported by runtime).
1380 if (auto Init = VD->getAnyInitializer()) {
1381 LocalVarRefChecker Checker(*this);
1382 if (Checker.Visit(Init))
1386 Vars.push_back(RefExpr);
1387 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1388 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1389 Context, SourceRange(Loc, Loc)));
1390 if (auto *ML = Context.getASTMutationListener())
1391 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1393 OMPThreadPrivateDecl *D = nullptr;
1394 if (!Vars.empty()) {
1395 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1397 D->setAccess(AS_public);
1402 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1403 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
1404 bool IsLoopIterVar = false) {
1406 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1407 << getOpenMPClauseName(DVar.CKind);
1411 PDSA_StaticMemberShared,
1412 PDSA_StaticLocalVarShared,
1413 PDSA_LoopIterVarPrivate,
1414 PDSA_LoopIterVarLinear,
1415 PDSA_LoopIterVarLastprivate,
1416 PDSA_ConstVarShared,
1417 PDSA_GlobalVarShared,
1418 PDSA_TaskVarFirstprivate,
1419 PDSA_LocalVarPrivate,
1421 } Reason = PDSA_Implicit;
1422 bool ReportHint = false;
1423 auto ReportLoc = D->getLocation();
1424 auto *VD = dyn_cast<VarDecl>(D);
1425 if (IsLoopIterVar) {
1426 if (DVar.CKind == OMPC_private)
1427 Reason = PDSA_LoopIterVarPrivate;
1428 else if (DVar.CKind == OMPC_lastprivate)
1429 Reason = PDSA_LoopIterVarLastprivate;
1431 Reason = PDSA_LoopIterVarLinear;
1432 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1433 DVar.CKind == OMPC_firstprivate) {
1434 Reason = PDSA_TaskVarFirstprivate;
1435 ReportLoc = DVar.ImplicitDSALoc;
1436 } else if (VD && VD->isStaticLocal())
1437 Reason = PDSA_StaticLocalVarShared;
1438 else if (VD && VD->isStaticDataMember())
1439 Reason = PDSA_StaticMemberShared;
1440 else if (VD && VD->isFileVarDecl())
1441 Reason = PDSA_GlobalVarShared;
1442 else if (D->getType().isConstant(SemaRef.getASTContext()))
1443 Reason = PDSA_ConstVarShared;
1444 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1446 Reason = PDSA_LocalVarPrivate;
1448 if (Reason != PDSA_Implicit) {
1449 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1450 << Reason << ReportHint
1451 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1452 } else if (DVar.ImplicitDSALoc.isValid()) {
1453 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1454 << getOpenMPClauseName(DVar.CKind);
1459 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1464 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1465 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
1468 void VisitDeclRefExpr(DeclRefExpr *E) {
1469 if (E->isTypeDependent() || E->isValueDependent() ||
1470 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1472 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1473 // Skip internally declared variables.
1474 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1477 auto DVar = Stack->getTopDSA(VD, false);
1478 // Check if the variable has explicit DSA set and stop analysis if it so.
1482 auto ELoc = E->getExprLoc();
1483 auto DKind = Stack->getCurrentDirective();
1484 // The default(none) clause requires that each variable that is referenced
1485 // in the construct, and does not have a predetermined data-sharing
1486 // attribute, must have its data-sharing attribute explicitly determined
1487 // by being listed in a data-sharing attribute clause.
1488 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1489 isParallelOrTaskRegion(DKind) &&
1490 VarsWithInheritedDSA.count(VD) == 0) {
1491 VarsWithInheritedDSA[VD] = E;
1495 // OpenMP [2.9.3.6, Restrictions, p.2]
1496 // A list item that appears in a reduction clause of the innermost
1497 // enclosing worksharing or parallel construct may not be accessed in an
1499 DVar = Stack->hasInnermostDSA(
1500 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1501 [](OpenMPDirectiveKind K) -> bool {
1502 return isOpenMPParallelDirective(K) ||
1503 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1506 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1508 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1509 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1513 // Define implicit data-sharing attributes for task.
1514 DVar = Stack->getImplicitDSA(VD, false);
1515 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1516 !Stack->isLoopControlVariable(VD).first)
1517 ImplicitFirstprivate.push_back(E);
1520 void VisitMemberExpr(MemberExpr *E) {
1521 if (E->isTypeDependent() || E->isValueDependent() ||
1522 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1524 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1525 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1526 auto DVar = Stack->getTopDSA(FD, false);
1527 // Check if the variable has explicit DSA set and stop analysis if it
1532 auto ELoc = E->getExprLoc();
1533 auto DKind = Stack->getCurrentDirective();
1534 // OpenMP [2.9.3.6, Restrictions, p.2]
1535 // A list item that appears in a reduction clause of the innermost
1536 // enclosing worksharing or parallel construct may not be accessed in
1537 // an explicit task.
1538 DVar = Stack->hasInnermostDSA(
1539 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1540 [](OpenMPDirectiveKind K) -> bool {
1541 return isOpenMPParallelDirective(K) ||
1542 isOpenMPWorksharingDirective(K) ||
1543 isOpenMPTeamsDirective(K);
1546 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1548 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1549 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1553 // Define implicit data-sharing attributes for task.
1554 DVar = Stack->getImplicitDSA(FD, false);
1555 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1556 !Stack->isLoopControlVariable(FD).first)
1557 ImplicitFirstprivate.push_back(E);
1560 Visit(E->getBase());
1562 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
1563 for (auto *C : S->clauses()) {
1564 // Skip analysis of arguments of implicitly defined firstprivate clause
1565 // for task directives.
1566 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1567 for (auto *CC : C->children()) {
1573 void VisitStmt(Stmt *S) {
1574 for (auto *C : S->children()) {
1575 if (C && !isa<OMPExecutableDirective>(C))
1580 bool isErrorFound() { return ErrorFound; }
1581 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
1582 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
1583 return VarsWithInheritedDSA;
1586 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1587 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1591 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1594 case OMPD_parallel_for:
1595 case OMPD_parallel_for_simd:
1596 case OMPD_parallel_sections:
1598 case OMPD_target_teams: {
1599 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1600 QualType KmpInt32PtrTy =
1601 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1602 Sema::CapturedParamNameType Params[] = {
1603 std::make_pair(".global_tid.", KmpInt32PtrTy),
1604 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1605 std::make_pair(StringRef(), QualType()) // __context with shared vars
1607 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1611 case OMPD_target_parallel: {
1612 Sema::CapturedParamNameType ParamsTarget[] = {
1613 std::make_pair(StringRef(), QualType()) // __context with shared vars
1615 // Start a captured region for 'target' with no implicit parameters.
1616 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1618 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1619 QualType KmpInt32PtrTy =
1620 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1621 Sema::CapturedParamNameType ParamsParallel[] = {
1622 std::make_pair(".global_tid.", KmpInt32PtrTy),
1623 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1624 std::make_pair(StringRef(), QualType()) // __context with shared vars
1626 // Start a captured region for 'parallel'.
1627 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1639 case OMPD_taskgroup:
1640 case OMPD_distribute:
1643 case OMPD_target_data:
1645 case OMPD_target_parallel_for:
1646 case OMPD_target_parallel_for_simd:
1647 case OMPD_target_simd: {
1648 Sema::CapturedParamNameType Params[] = {
1649 std::make_pair(StringRef(), QualType()) // __context with shared vars
1651 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1656 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1657 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1658 FunctionProtoType::ExtProtoInfo EPI;
1659 EPI.Variadic = true;
1660 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1661 Sema::CapturedParamNameType Params[] = {
1662 std::make_pair(".global_tid.", KmpInt32Ty),
1663 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1664 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1665 std::make_pair(".copy_fn.",
1666 Context.getPointerType(CopyFnType).withConst()),
1667 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1668 std::make_pair(StringRef(), QualType()) // __context with shared vars
1670 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1672 // Mark this captured region as inlined, because we don't use outlined
1673 // function directly.
1674 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1675 AlwaysInlineAttr::CreateImplicit(
1676 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1680 case OMPD_taskloop_simd: {
1681 QualType KmpInt32Ty =
1682 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1683 QualType KmpUInt64Ty =
1684 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1685 QualType KmpInt64Ty =
1686 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1687 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1688 FunctionProtoType::ExtProtoInfo EPI;
1689 EPI.Variadic = true;
1690 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1691 Sema::CapturedParamNameType Params[] = {
1692 std::make_pair(".global_tid.", KmpInt32Ty),
1693 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1694 std::make_pair(".privates.",
1695 Context.VoidPtrTy.withConst().withRestrict()),
1698 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1699 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1700 std::make_pair(".lb.", KmpUInt64Ty),
1701 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1702 std::make_pair(".liter.", KmpInt32Ty),
1703 std::make_pair(StringRef(), QualType()) // __context with shared vars
1705 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1707 // Mark this captured region as inlined, because we don't use outlined
1708 // function directly.
1709 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1710 AlwaysInlineAttr::CreateImplicit(
1711 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1714 case OMPD_distribute_parallel_for_simd:
1715 case OMPD_distribute_simd:
1716 case OMPD_distribute_parallel_for:
1717 case OMPD_teams_distribute:
1718 case OMPD_teams_distribute_simd:
1719 case OMPD_teams_distribute_parallel_for_simd:
1720 case OMPD_teams_distribute_parallel_for:
1721 case OMPD_target_teams_distribute:
1722 case OMPD_target_teams_distribute_parallel_for:
1723 case OMPD_target_teams_distribute_parallel_for_simd:
1724 case OMPD_target_teams_distribute_simd: {
1725 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1726 QualType KmpInt32PtrTy =
1727 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1728 Sema::CapturedParamNameType Params[] = {
1729 std::make_pair(".global_tid.", KmpInt32PtrTy),
1730 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1731 std::make_pair(".previous.lb.", Context.getSizeType()),
1732 std::make_pair(".previous.ub.", Context.getSizeType()),
1733 std::make_pair(StringRef(), QualType()) // __context with shared vars
1735 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1739 case OMPD_threadprivate:
1740 case OMPD_taskyield:
1743 case OMPD_cancellation_point:
1746 case OMPD_target_enter_data:
1747 case OMPD_target_exit_data:
1748 case OMPD_declare_reduction:
1749 case OMPD_declare_simd:
1750 case OMPD_declare_target:
1751 case OMPD_end_declare_target:
1752 case OMPD_target_update:
1753 llvm_unreachable("OpenMP Directive is not allowed");
1755 llvm_unreachable("Unknown OpenMP directive");
1759 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
1760 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1761 getOpenMPCaptureRegions(CaptureRegions, DKind);
1762 return CaptureRegions.size();
1765 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
1766 Expr *CaptureExpr, bool WithInit,
1767 bool AsExpression) {
1768 assert(CaptureExpr);
1769 ASTContext &C = S.getASTContext();
1770 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
1771 QualType Ty = Init->getType();
1772 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1773 if (S.getLangOpts().CPlusPlus)
1774 Ty = C.getLValueReferenceType(Ty);
1776 Ty = C.getPointerType(Ty);
1778 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1779 if (!Res.isUsable())
1785 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1786 CaptureExpr->getLocStart());
1788 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
1789 S.CurContext->addHiddenDecl(CED);
1790 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
1794 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1796 OMPCapturedExprDecl *CD;
1797 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1798 CD = cast<OMPCapturedExprDecl>(VD);
1800 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1801 /*AsExpression=*/false);
1802 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1803 CaptureExpr->getExprLoc());
1806 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1809 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1810 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1811 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1812 CaptureExpr->getExprLoc());
1814 ExprResult Res = Ref;
1815 if (!S.getLangOpts().CPlusPlus &&
1816 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1817 Ref->getType()->isPointerType())
1818 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1819 if (!Res.isUsable())
1821 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
1825 // OpenMP directives parsed in this section are represented as a
1826 // CapturedStatement with an associated statement. If a syntax error
1827 // is detected during the parsing of the associated statement, the
1828 // compiler must abort processing and close the CapturedStatement.
1830 // Combined directives such as 'target parallel' have more than one
1831 // nested CapturedStatements. This RAII ensures that we unwind out
1832 // of all the nested CapturedStatements when an error is found.
1833 class CaptureRegionUnwinderRAII {
1837 OpenMPDirectiveKind DKind;
1840 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
1841 OpenMPDirectiveKind DKind)
1842 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
1843 ~CaptureRegionUnwinderRAII() {
1845 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
1846 while (--ThisCaptureLevel >= 0)
1847 S.ActOnCapturedRegionError();
1853 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1854 ArrayRef<OMPClause *> Clauses) {
1855 bool ErrorFound = false;
1856 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
1857 *this, ErrorFound, DSAStack->getCurrentDirective());
1858 if (!S.isUsable()) {
1863 OMPOrderedClause *OC = nullptr;
1864 OMPScheduleClause *SC = nullptr;
1865 SmallVector<OMPLinearClause *, 4> LCs;
1866 SmallVector<OMPClauseWithPreInit *, 8> PICs;
1867 // This is required for proper codegen.
1868 for (auto *Clause : Clauses) {
1869 if (isOpenMPPrivate(Clause->getClauseKind()) ||
1870 Clause->getClauseKind() == OMPC_copyprivate ||
1871 (getLangOpts().OpenMPUseTLS &&
1872 getASTContext().getTargetInfo().isTLSSupported() &&
1873 Clause->getClauseKind() == OMPC_copyin)) {
1874 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
1875 // Mark all variables in private list clauses as used in inner region.
1876 for (auto *VarRef : Clause->children()) {
1877 if (auto *E = cast_or_null<Expr>(VarRef)) {
1878 MarkDeclarationsReferencedInExpr(E);
1881 DSAStack->setForceVarCapturing(/*V=*/false);
1882 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
1883 if (auto *C = OMPClauseWithPreInit::get(Clause))
1885 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1886 if (auto *E = C->getPostUpdateExpr())
1887 MarkDeclarationsReferencedInExpr(E);
1890 if (Clause->getClauseKind() == OMPC_schedule)
1891 SC = cast<OMPScheduleClause>(Clause);
1892 else if (Clause->getClauseKind() == OMPC_ordered)
1893 OC = cast<OMPOrderedClause>(Clause);
1894 else if (Clause->getClauseKind() == OMPC_linear)
1895 LCs.push_back(cast<OMPLinearClause>(Clause));
1897 // OpenMP, 2.7.1 Loop Construct, Restrictions
1898 // The nonmonotonic modifier cannot be specified if an ordered clause is
1901 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1902 SC->getSecondScheduleModifier() ==
1903 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1905 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1906 ? SC->getFirstScheduleModifierLoc()
1907 : SC->getSecondScheduleModifierLoc(),
1908 diag::err_omp_schedule_nonmonotonic_ordered)
1909 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1912 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1913 for (auto *C : LCs) {
1914 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1915 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1919 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1920 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1921 OC->getNumForLoops()) {
1922 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1923 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1930 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1931 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
1932 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
1933 // Mark all variables in private list clauses as used in inner region.
1934 // Required for proper codegen of combined directives.
1935 // TODO: add processing for other clauses.
1936 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
1937 for (auto *C : PICs) {
1938 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
1939 // Find the particular capture region for the clause if the
1940 // directive is a combined one with multiple capture regions.
1941 // If the directive is not a combined one, the capture region
1942 // associated with the clause is OMPD_unknown and is generated
1944 if (CaptureRegion == ThisCaptureRegion ||
1945 CaptureRegion == OMPD_unknown) {
1946 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1947 for (auto *D : DS->decls())
1948 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1953 SR = ActOnCapturedRegionEnd(SR.get());
1958 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1959 OpenMPDirectiveKind CurrentRegion,
1960 const DeclarationNameInfo &CurrentName,
1961 OpenMPDirectiveKind CancelRegion,
1962 SourceLocation StartLoc) {
1963 if (Stack->getCurScope()) {
1964 auto ParentRegion = Stack->getParentDirective();
1965 auto OffendingRegion = ParentRegion;
1966 bool NestingProhibited = false;
1967 bool CloseNesting = true;
1968 bool OrphanSeen = false;
1971 ShouldBeInParallelRegion,
1972 ShouldBeInOrderedRegion,
1973 ShouldBeInTargetRegion,
1974 ShouldBeInTeamsRegion
1975 } Recommend = NoRecommend;
1976 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
1977 // OpenMP [2.16, Nesting of Regions]
1978 // OpenMP constructs may not be nested inside a simd region.
1979 // OpenMP [2.8.1,simd Construct, Restrictions]
1980 // An ordered construct with the simd clause is the only OpenMP
1981 // construct that can appear in the simd region.
1982 // Allowing a SIMD construct nested in another SIMD construct is an
1983 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
1985 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
1986 ? diag::err_omp_prohibited_region_simd
1987 : diag::warn_omp_nesting_simd);
1988 return CurrentRegion != OMPD_simd;
1990 if (ParentRegion == OMPD_atomic) {
1991 // OpenMP [2.16, Nesting of Regions]
1992 // OpenMP constructs may not be nested inside an atomic region.
1993 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1996 if (CurrentRegion == OMPD_section) {
1997 // OpenMP [2.7.2, sections Construct, Restrictions]
1998 // Orphaned section directives are prohibited. That is, the section
1999 // directives must appear within the sections construct and must not be
2000 // encountered elsewhere in the sections region.
2001 if (ParentRegion != OMPD_sections &&
2002 ParentRegion != OMPD_parallel_sections) {
2003 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2004 << (ParentRegion != OMPD_unknown)
2005 << getOpenMPDirectiveName(ParentRegion);
2010 // Allow some constructs (except teams) to be orphaned (they could be
2011 // used in functions, called from OpenMP regions with the required
2013 if (ParentRegion == OMPD_unknown &&
2014 !isOpenMPNestingTeamsDirective(CurrentRegion))
2016 if (CurrentRegion == OMPD_cancellation_point ||
2017 CurrentRegion == OMPD_cancel) {
2018 // OpenMP [2.16, Nesting of Regions]
2019 // A cancellation point construct for which construct-type-clause is
2020 // taskgroup must be nested inside a task construct. A cancellation
2021 // point construct for which construct-type-clause is not taskgroup must
2022 // be closely nested inside an OpenMP construct that matches the type
2023 // specified in construct-type-clause.
2024 // A cancel construct for which construct-type-clause is taskgroup must be
2025 // nested inside a task construct. A cancel construct for which
2026 // construct-type-clause is not taskgroup must be closely nested inside an
2027 // OpenMP construct that matches the type specified in
2028 // construct-type-clause.
2030 !((CancelRegion == OMPD_parallel &&
2031 (ParentRegion == OMPD_parallel ||
2032 ParentRegion == OMPD_target_parallel)) ||
2033 (CancelRegion == OMPD_for &&
2034 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2035 ParentRegion == OMPD_target_parallel_for)) ||
2036 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2037 (CancelRegion == OMPD_sections &&
2038 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2039 ParentRegion == OMPD_parallel_sections)));
2040 } else if (CurrentRegion == OMPD_master) {
2041 // OpenMP [2.16, Nesting of Regions]
2042 // A master region may not be closely nested inside a worksharing,
2043 // atomic, or explicit task region.
2044 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2045 isOpenMPTaskingDirective(ParentRegion);
2046 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2047 // OpenMP [2.16, Nesting of Regions]
2048 // A critical region may not be nested (closely or otherwise) inside a
2049 // critical region with the same name. Note that this restriction is not
2050 // sufficient to prevent deadlock.
2051 SourceLocation PreviousCriticalLoc;
2052 bool DeadLock = Stack->hasDirective(
2053 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2054 const DeclarationNameInfo &DNI,
2055 SourceLocation Loc) -> bool {
2056 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2057 PreviousCriticalLoc = Loc;
2062 false /* skip top directive */);
2064 SemaRef.Diag(StartLoc,
2065 diag::err_omp_prohibited_region_critical_same_name)
2066 << CurrentName.getName();
2067 if (PreviousCriticalLoc.isValid())
2068 SemaRef.Diag(PreviousCriticalLoc,
2069 diag::note_omp_previous_critical_region);
2072 } else if (CurrentRegion == OMPD_barrier) {
2073 // OpenMP [2.16, Nesting of Regions]
2074 // A barrier region may not be closely nested inside a worksharing,
2075 // explicit task, critical, ordered, atomic, or master region.
2076 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2077 isOpenMPTaskingDirective(ParentRegion) ||
2078 ParentRegion == OMPD_master ||
2079 ParentRegion == OMPD_critical ||
2080 ParentRegion == OMPD_ordered;
2081 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
2082 !isOpenMPParallelDirective(CurrentRegion) &&
2083 !isOpenMPTeamsDirective(CurrentRegion)) {
2084 // OpenMP [2.16, Nesting of Regions]
2085 // A worksharing region may not be closely nested inside a worksharing,
2086 // explicit task, critical, ordered, atomic, or master region.
2087 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2088 isOpenMPTaskingDirective(ParentRegion) ||
2089 ParentRegion == OMPD_master ||
2090 ParentRegion == OMPD_critical ||
2091 ParentRegion == OMPD_ordered;
2092 Recommend = ShouldBeInParallelRegion;
2093 } else if (CurrentRegion == OMPD_ordered) {
2094 // OpenMP [2.16, Nesting of Regions]
2095 // An ordered region may not be closely nested inside a critical,
2096 // atomic, or explicit task region.
2097 // An ordered region must be closely nested inside a loop region (or
2098 // parallel loop region) with an ordered clause.
2099 // OpenMP [2.8.1,simd Construct, Restrictions]
2100 // An ordered construct with the simd clause is the only OpenMP construct
2101 // that can appear in the simd region.
2102 NestingProhibited = ParentRegion == OMPD_critical ||
2103 isOpenMPTaskingDirective(ParentRegion) ||
2104 !(isOpenMPSimdDirective(ParentRegion) ||
2105 Stack->isParentOrderedRegion());
2106 Recommend = ShouldBeInOrderedRegion;
2107 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
2108 // OpenMP [2.16, Nesting of Regions]
2109 // If specified, a teams construct must be contained within a target
2111 NestingProhibited = ParentRegion != OMPD_target;
2112 OrphanSeen = ParentRegion == OMPD_unknown;
2113 Recommend = ShouldBeInTargetRegion;
2114 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2116 if (!NestingProhibited &&
2117 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2118 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2119 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
2120 // OpenMP [2.16, Nesting of Regions]
2121 // distribute, parallel, parallel sections, parallel workshare, and the
2122 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2123 // constructs that can be closely nested in the teams region.
2124 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2125 !isOpenMPDistributeDirective(CurrentRegion);
2126 Recommend = ShouldBeInParallelRegion;
2128 if (!NestingProhibited &&
2129 isOpenMPNestingDistributeDirective(CurrentRegion)) {
2130 // OpenMP 4.5 [2.17 Nesting of Regions]
2131 // The region associated with the distribute construct must be strictly
2132 // nested inside a teams region
2134 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
2135 Recommend = ShouldBeInTeamsRegion;
2137 if (!NestingProhibited &&
2138 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2139 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2140 // OpenMP 4.5 [2.17 Nesting of Regions]
2141 // If a target, target update, target data, target enter data, or
2142 // target exit data construct is encountered during execution of a
2143 // target region, the behavior is unspecified.
2144 NestingProhibited = Stack->hasDirective(
2145 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2146 SourceLocation) -> bool {
2147 if (isOpenMPTargetExecutionDirective(K)) {
2148 OffendingRegion = K;
2153 false /* don't skip top directive */);
2154 CloseNesting = false;
2156 if (NestingProhibited) {
2158 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2159 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2161 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2162 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2163 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2171 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2172 ArrayRef<OMPClause *> Clauses,
2173 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2174 bool ErrorFound = false;
2175 unsigned NamedModifiersNumber = 0;
2176 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2178 SmallVector<SourceLocation, 4> NameModifierLoc;
2179 for (const auto *C : Clauses) {
2180 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2181 // At most one if clause without a directive-name-modifier can appear on
2183 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2184 if (FoundNameModifiers[CurNM]) {
2185 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2186 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2187 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2189 } else if (CurNM != OMPD_unknown) {
2190 NameModifierLoc.push_back(IC->getNameModifierLoc());
2191 ++NamedModifiersNumber;
2193 FoundNameModifiers[CurNM] = IC;
2194 if (CurNM == OMPD_unknown)
2196 // Check if the specified name modifier is allowed for the current
2198 // At most one if clause with the particular directive-name-modifier can
2199 // appear on the directive.
2200 bool MatchFound = false;
2201 for (auto NM : AllowedNameModifiers) {
2208 S.Diag(IC->getNameModifierLoc(),
2209 diag::err_omp_wrong_if_directive_name_modifier)
2210 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2215 // If any if clause on the directive includes a directive-name-modifier then
2216 // all if clauses on the directive must include a directive-name-modifier.
2217 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2218 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2219 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2220 diag::err_omp_no_more_if_clause);
2223 std::string Sep(", ");
2224 unsigned AllowedCnt = 0;
2225 unsigned TotalAllowedNum =
2226 AllowedNameModifiers.size() - NamedModifiersNumber;
2227 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2229 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2230 if (!FoundNameModifiers[NM]) {
2232 Values += getOpenMPDirectiveName(NM);
2234 if (AllowedCnt + 2 == TotalAllowedNum)
2236 else if (AllowedCnt + 1 != TotalAllowedNum)
2241 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2242 diag::err_omp_unnamed_if_clause)
2243 << (TotalAllowedNum > 1) << Values;
2245 for (auto Loc : NameModifierLoc) {
2246 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2253 StmtResult Sema::ActOnOpenMPExecutableDirective(
2254 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2255 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2256 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
2257 StmtResult Res = StmtError();
2258 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2262 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
2263 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
2264 bool ErrorFound = false;
2265 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
2267 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2269 // Check default data sharing attributes for referenced variables.
2270 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2271 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2272 if (DSAChecker.isErrorFound())
2274 // Generate list of implicitly defined firstprivate variables.
2275 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
2277 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2278 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2279 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2280 SourceLocation(), SourceLocation())) {
2281 ClausesWithImplicit.push_back(Implicit);
2282 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2283 DSAChecker.getImplicitFirstprivate().size();
2289 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
2292 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2294 AllowedNameModifiers.push_back(OMPD_parallel);
2297 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2298 VarsWithInheritedDSA);
2301 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2302 VarsWithInheritedDSA);
2305 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2306 EndLoc, VarsWithInheritedDSA);
2309 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2313 assert(ClausesWithImplicit.empty() &&
2314 "No clauses are allowed for 'omp section' directive");
2315 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2318 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2322 assert(ClausesWithImplicit.empty() &&
2323 "No clauses are allowed for 'omp master' directive");
2324 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2327 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2330 case OMPD_parallel_for:
2331 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2332 EndLoc, VarsWithInheritedDSA);
2333 AllowedNameModifiers.push_back(OMPD_parallel);
2335 case OMPD_parallel_for_simd:
2336 Res = ActOnOpenMPParallelForSimdDirective(
2337 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2338 AllowedNameModifiers.push_back(OMPD_parallel);
2340 case OMPD_parallel_sections:
2341 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2343 AllowedNameModifiers.push_back(OMPD_parallel);
2347 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2348 AllowedNameModifiers.push_back(OMPD_task);
2350 case OMPD_taskyield:
2351 assert(ClausesWithImplicit.empty() &&
2352 "No clauses are allowed for 'omp taskyield' directive");
2353 assert(AStmt == nullptr &&
2354 "No associated statement allowed for 'omp taskyield' directive");
2355 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2358 assert(ClausesWithImplicit.empty() &&
2359 "No clauses are allowed for 'omp barrier' directive");
2360 assert(AStmt == nullptr &&
2361 "No associated statement allowed for 'omp barrier' directive");
2362 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2365 assert(ClausesWithImplicit.empty() &&
2366 "No clauses are allowed for 'omp taskwait' directive");
2367 assert(AStmt == nullptr &&
2368 "No associated statement allowed for 'omp taskwait' directive");
2369 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2371 case OMPD_taskgroup:
2372 assert(ClausesWithImplicit.empty() &&
2373 "No clauses are allowed for 'omp taskgroup' directive");
2374 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2377 assert(AStmt == nullptr &&
2378 "No associated statement allowed for 'omp flush' directive");
2379 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2382 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2386 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2391 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2394 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2396 AllowedNameModifiers.push_back(OMPD_target);
2398 case OMPD_target_parallel:
2399 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2401 AllowedNameModifiers.push_back(OMPD_target);
2402 AllowedNameModifiers.push_back(OMPD_parallel);
2404 case OMPD_target_parallel_for:
2405 Res = ActOnOpenMPTargetParallelForDirective(
2406 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2407 AllowedNameModifiers.push_back(OMPD_target);
2408 AllowedNameModifiers.push_back(OMPD_parallel);
2410 case OMPD_cancellation_point:
2411 assert(ClausesWithImplicit.empty() &&
2412 "No clauses are allowed for 'omp cancellation point' directive");
2413 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2414 "cancellation point' directive");
2415 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2418 assert(AStmt == nullptr &&
2419 "No associated statement allowed for 'omp cancel' directive");
2420 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2422 AllowedNameModifiers.push_back(OMPD_cancel);
2424 case OMPD_target_data:
2425 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2427 AllowedNameModifiers.push_back(OMPD_target_data);
2429 case OMPD_target_enter_data:
2430 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2432 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2434 case OMPD_target_exit_data:
2435 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2437 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2440 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2441 EndLoc, VarsWithInheritedDSA);
2442 AllowedNameModifiers.push_back(OMPD_taskloop);
2444 case OMPD_taskloop_simd:
2445 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2446 EndLoc, VarsWithInheritedDSA);
2447 AllowedNameModifiers.push_back(OMPD_taskloop);
2449 case OMPD_distribute:
2450 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2451 EndLoc, VarsWithInheritedDSA);
2453 case OMPD_target_update:
2454 assert(!AStmt && "Statement is not allowed for target update");
2456 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2457 AllowedNameModifiers.push_back(OMPD_target_update);
2459 case OMPD_distribute_parallel_for:
2460 Res = ActOnOpenMPDistributeParallelForDirective(
2461 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2462 AllowedNameModifiers.push_back(OMPD_parallel);
2464 case OMPD_distribute_parallel_for_simd:
2465 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2466 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2467 AllowedNameModifiers.push_back(OMPD_parallel);
2469 case OMPD_distribute_simd:
2470 Res = ActOnOpenMPDistributeSimdDirective(
2471 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2473 case OMPD_target_parallel_for_simd:
2474 Res = ActOnOpenMPTargetParallelForSimdDirective(
2475 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2476 AllowedNameModifiers.push_back(OMPD_target);
2477 AllowedNameModifiers.push_back(OMPD_parallel);
2479 case OMPD_target_simd:
2480 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2481 EndLoc, VarsWithInheritedDSA);
2482 AllowedNameModifiers.push_back(OMPD_target);
2484 case OMPD_teams_distribute:
2485 Res = ActOnOpenMPTeamsDistributeDirective(
2486 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2488 case OMPD_teams_distribute_simd:
2489 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2490 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2492 case OMPD_teams_distribute_parallel_for_simd:
2493 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2494 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2495 AllowedNameModifiers.push_back(OMPD_parallel);
2497 case OMPD_teams_distribute_parallel_for:
2498 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2499 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2500 AllowedNameModifiers.push_back(OMPD_parallel);
2502 case OMPD_target_teams:
2503 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2505 AllowedNameModifiers.push_back(OMPD_target);
2507 case OMPD_target_teams_distribute:
2508 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2509 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2510 AllowedNameModifiers.push_back(OMPD_target);
2512 case OMPD_target_teams_distribute_parallel_for:
2513 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2514 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2515 AllowedNameModifiers.push_back(OMPD_target);
2516 AllowedNameModifiers.push_back(OMPD_parallel);
2518 case OMPD_target_teams_distribute_parallel_for_simd:
2519 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2520 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2521 AllowedNameModifiers.push_back(OMPD_target);
2522 AllowedNameModifiers.push_back(OMPD_parallel);
2524 case OMPD_target_teams_distribute_simd:
2525 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2526 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2527 AllowedNameModifiers.push_back(OMPD_target);
2529 case OMPD_declare_target:
2530 case OMPD_end_declare_target:
2531 case OMPD_threadprivate:
2532 case OMPD_declare_reduction:
2533 case OMPD_declare_simd:
2534 llvm_unreachable("OpenMP Directive is not allowed");
2536 llvm_unreachable("Unknown OpenMP directive");
2539 for (auto P : VarsWithInheritedDSA) {
2540 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2541 << P.first << P.second->getSourceRange();
2543 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2545 if (!AllowedNameModifiers.empty())
2546 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2554 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2555 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
2556 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
2557 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2558 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
2559 assert(Aligneds.size() == Alignments.size());
2560 assert(Linears.size() == LinModifiers.size());
2561 assert(Linears.size() == Steps.size());
2562 if (!DG || DG.get().isNull())
2563 return DeclGroupPtrTy();
2565 if (!DG.get().isSingleDecl()) {
2566 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
2569 auto *ADecl = DG.get().getSingleDecl();
2570 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2571 ADecl = FTD->getTemplatedDecl();
2573 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2575 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
2576 return DeclGroupPtrTy();
2579 // OpenMP [2.8.2, declare simd construct, Description]
2580 // The parameter of the simdlen clause must be a constant positive integer
2584 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
2585 // OpenMP [2.8.2, declare simd construct, Description]
2586 // The special this pointer can be used as if was one of the arguments to the
2587 // function in any of the linear, aligned, or uniform clauses.
2588 // The uniform clause declares one or more arguments to have an invariant
2589 // value for all concurrent invocations of the function in the execution of a
2590 // single SIMD loop.
2591 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2592 Expr *UniformedLinearThis = nullptr;
2593 for (auto *E : Uniforms) {
2594 E = E->IgnoreParenImpCasts();
2595 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2596 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2597 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2598 FD->getParamDecl(PVD->getFunctionScopeIndex())
2599 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2600 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
2603 if (isa<CXXThisExpr>(E)) {
2604 UniformedLinearThis = E;
2607 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2608 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2610 // OpenMP [2.8.2, declare simd construct, Description]
2611 // The aligned clause declares that the object to which each list item points
2612 // is aligned to the number of bytes expressed in the optional parameter of
2613 // the aligned clause.
2614 // The special this pointer can be used as if was one of the arguments to the
2615 // function in any of the linear, aligned, or uniform clauses.
2616 // The type of list items appearing in the aligned clause must be array,
2617 // pointer, reference to array, or reference to pointer.
2618 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2619 Expr *AlignedThis = nullptr;
2620 for (auto *E : Aligneds) {
2621 E = E->IgnoreParenImpCasts();
2622 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2623 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2624 auto *CanonPVD = PVD->getCanonicalDecl();
2625 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2626 FD->getParamDecl(PVD->getFunctionScopeIndex())
2627 ->getCanonicalDecl() == CanonPVD) {
2628 // OpenMP [2.8.1, simd construct, Restrictions]
2629 // A list-item cannot appear in more than one aligned clause.
2630 if (AlignedArgs.count(CanonPVD) > 0) {
2631 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2632 << 1 << E->getSourceRange();
2633 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2634 diag::note_omp_explicit_dsa)
2635 << getOpenMPClauseName(OMPC_aligned);
2638 AlignedArgs[CanonPVD] = E;
2639 QualType QTy = PVD->getType()
2640 .getNonReferenceType()
2641 .getUnqualifiedType()
2642 .getCanonicalType();
2643 const Type *Ty = QTy.getTypePtrOrNull();
2644 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2645 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2646 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2647 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2652 if (isa<CXXThisExpr>(E)) {
2654 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2655 << 2 << E->getSourceRange();
2656 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2657 << getOpenMPClauseName(OMPC_aligned);
2662 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2663 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2665 // The optional parameter of the aligned clause, alignment, must be a constant
2666 // positive integer expression. If no optional parameter is specified,
2667 // implementation-defined default alignments for SIMD instructions on the
2668 // target platforms are assumed.
2669 SmallVector<Expr *, 4> NewAligns;
2670 for (auto *E : Alignments) {
2673 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2674 NewAligns.push_back(Align.get());
2676 // OpenMP [2.8.2, declare simd construct, Description]
2677 // The linear clause declares one or more list items to be private to a SIMD
2678 // lane and to have a linear relationship with respect to the iteration space
2680 // The special this pointer can be used as if was one of the arguments to the
2681 // function in any of the linear, aligned, or uniform clauses.
2682 // When a linear-step expression is specified in a linear clause it must be
2683 // either a constant integer expression or an integer-typed parameter that is
2684 // specified in a uniform clause on the directive.
2685 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2686 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2687 auto MI = LinModifiers.begin();
2688 for (auto *E : Linears) {
2689 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2691 E = E->IgnoreParenImpCasts();
2692 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2693 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2694 auto *CanonPVD = PVD->getCanonicalDecl();
2695 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2696 FD->getParamDecl(PVD->getFunctionScopeIndex())
2697 ->getCanonicalDecl() == CanonPVD) {
2698 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2699 // A list-item cannot appear in more than one linear clause.
2700 if (LinearArgs.count(CanonPVD) > 0) {
2701 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2702 << getOpenMPClauseName(OMPC_linear)
2703 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2704 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2705 diag::note_omp_explicit_dsa)
2706 << getOpenMPClauseName(OMPC_linear);
2709 // Each argument can appear in at most one uniform or linear clause.
2710 if (UniformedArgs.count(CanonPVD) > 0) {
2711 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2712 << getOpenMPClauseName(OMPC_linear)
2713 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2714 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2715 diag::note_omp_explicit_dsa)
2716 << getOpenMPClauseName(OMPC_uniform);
2719 LinearArgs[CanonPVD] = E;
2720 if (E->isValueDependent() || E->isTypeDependent() ||
2721 E->isInstantiationDependent() ||
2722 E->containsUnexpandedParameterPack())
2724 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2725 PVD->getOriginalType());
2729 if (isa<CXXThisExpr>(E)) {
2730 if (UniformedLinearThis) {
2731 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2732 << getOpenMPClauseName(OMPC_linear)
2733 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2734 << E->getSourceRange();
2735 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2736 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2740 UniformedLinearThis = E;
2741 if (E->isValueDependent() || E->isTypeDependent() ||
2742 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2744 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2748 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2749 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2751 Expr *Step = nullptr;
2752 Expr *NewStep = nullptr;
2753 SmallVector<Expr *, 4> NewSteps;
2754 for (auto *E : Steps) {
2755 // Skip the same step expression, it was checked already.
2756 if (Step == E || !E) {
2757 NewSteps.push_back(E ? NewStep : nullptr);
2761 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2762 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2763 auto *CanonPVD = PVD->getCanonicalDecl();
2764 if (UniformedArgs.count(CanonPVD) == 0) {
2765 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2766 << Step->getSourceRange();
2767 } else if (E->isValueDependent() || E->isTypeDependent() ||
2768 E->isInstantiationDependent() ||
2769 E->containsUnexpandedParameterPack() ||
2770 CanonPVD->getType()->hasIntegerRepresentation())
2771 NewSteps.push_back(Step);
2773 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2774 << Step->getSourceRange();
2779 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2780 !Step->isInstantiationDependent() &&
2781 !Step->containsUnexpandedParameterPack()) {
2782 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2785 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2787 NewSteps.push_back(NewStep);
2789 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2790 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
2791 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
2792 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2793 const_cast<Expr **>(Linears.data()), Linears.size(),
2794 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2795 NewSteps.data(), NewSteps.size(), SR);
2796 ADecl->addAttr(NewAttr);
2797 return ConvertDeclToDeclGroup(ADecl);
2800 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2802 SourceLocation StartLoc,
2803 SourceLocation EndLoc) {
2807 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2808 // 1.2.2 OpenMP Language Terminology
2809 // Structured block - An executable statement with a single entry at the
2810 // top and a single exit at the bottom.
2811 // The point of exit cannot be a branch out of the structured block.
2812 // longjmp() and throw() must not violate the entry/exit criteria.
2813 CS->getCapturedDecl()->setNothrow();
2815 getCurFunction()->setHasBranchProtectedScope();
2817 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2818 DSAStack->isCancelRegion());
2822 /// \brief Helper class for checking canonical form of the OpenMP loops and
2823 /// extracting iteration space of each loop in the loop nest, that will be used
2824 /// for IR generation.
2825 class OpenMPIterationSpaceChecker {
2826 /// \brief Reference to Sema.
2828 /// \brief A location for diagnostics (when there is no some better location).
2829 SourceLocation DefaultLoc;
2830 /// \brief A location for diagnostics (when increment is not compatible).
2831 SourceLocation ConditionLoc;
2832 /// \brief A source location for referring to loop init later.
2833 SourceRange InitSrcRange;
2834 /// \brief A source location for referring to condition later.
2835 SourceRange ConditionSrcRange;
2836 /// \brief A source location for referring to increment later.
2837 SourceRange IncrementSrcRange;
2838 /// \brief Loop variable.
2839 ValueDecl *LCDecl = nullptr;
2840 /// \brief Reference to loop variable.
2841 Expr *LCRef = nullptr;
2842 /// \brief Lower bound (initializer for the var).
2844 /// \brief Upper bound.
2846 /// \brief Loop step (increment).
2847 Expr *Step = nullptr;
2848 /// \brief This flag is true when condition is one of:
2853 bool TestIsLessOp = false;
2854 /// \brief This flag is true when condition is strict ( < or > ).
2855 bool TestIsStrictOp = false;
2856 /// \brief This flag is true when step is subtracted on each iteration.
2857 bool SubtractStep = false;
2860 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2861 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
2862 /// \brief Check init-expr for canonical loop form and save loop counter
2863 /// variable - #Var and its initialization value - #LB.
2864 bool CheckInit(Stmt *S, bool EmitDiags = true);
2865 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2866 /// for less/greater and for strict/non-strict comparison.
2867 bool CheckCond(Expr *S);
2868 /// \brief Check incr-expr for canonical loop form and return true if it
2869 /// does not conform, otherwise save loop step (#Step).
2870 bool CheckInc(Expr *S);
2871 /// \brief Return the loop counter variable.
2872 ValueDecl *GetLoopDecl() const { return LCDecl; }
2873 /// \brief Return the reference expression to loop counter variable.
2874 Expr *GetLoopDeclRefExpr() const { return LCRef; }
2875 /// \brief Source range of the loop init.
2876 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2877 /// \brief Source range of the loop condition.
2878 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2879 /// \brief Source range of the loop increment.
2880 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2881 /// \brief True if the step should be subtracted.
2882 bool ShouldSubtractStep() const { return SubtractStep; }
2883 /// \brief Build the expression to calculate the number of iterations.
2885 BuildNumIterations(Scope *S, const bool LimitedType,
2886 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
2887 /// \brief Build the precondition expression for the loops.
2888 Expr *BuildPreCond(Scope *S, Expr *Cond,
2889 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
2890 /// \brief Build reference expression to the counter be used for codegen.
2891 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2892 DSAStackTy &DSA) const;
2893 /// \brief Build reference expression to the private counter be used for
2895 Expr *BuildPrivateCounterVar() const;
2896 /// \brief Build initialization of the counter be used for codegen.
2897 Expr *BuildCounterInit() const;
2898 /// \brief Build step of the counter be used for codegen.
2899 Expr *BuildCounterStep() const;
2900 /// \brief Return true if any expression is dependent.
2901 bool Dependent() const;
2904 /// \brief Check the right-hand side of an assignment in the increment
2906 bool CheckIncRHS(Expr *RHS);
2907 /// \brief Helper to set loop counter variable and its initializer.
2908 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
2909 /// \brief Helper to set upper bound.
2910 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
2912 /// \brief Helper to set loop increment.
2913 bool SetStep(Expr *NewStep, bool Subtract);
2916 bool OpenMPIterationSpaceChecker::Dependent() const {
2918 assert(!LB && !UB && !Step);
2921 return LCDecl->getType()->isDependentType() ||
2922 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2923 (Step && Step->isValueDependent());
2926 static Expr *getExprAsWritten(Expr *E) {
2927 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2928 E = ExprTemp->getSubExpr();
2930 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2931 E = MTE->GetTemporaryExpr();
2933 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2934 E = Binder->getSubExpr();
2936 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2937 E = ICE->getSubExprAsWritten();
2938 return E->IgnoreParens();
2941 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2944 // State consistency checking to ensure correct usage.
2945 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
2946 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2947 if (!NewLCDecl || !NewLB)
2949 LCDecl = getCanonicalDecl(NewLCDecl);
2950 LCRef = NewLCRefExpr;
2951 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2952 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2953 if ((Ctor->isCopyOrMoveConstructor() ||
2954 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2955 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
2956 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
2961 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2962 SourceRange SR, SourceLocation SL) {
2963 // State consistency checking to ensure correct usage.
2964 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2965 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2969 TestIsLessOp = LessOp;
2970 TestIsStrictOp = StrictOp;
2971 ConditionSrcRange = SR;
2976 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2977 // State consistency checking to ensure correct usage.
2978 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
2981 if (!NewStep->isValueDependent()) {
2982 // Check that the step is integer expression.
2983 SourceLocation StepLoc = NewStep->getLocStart();
2985 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2986 if (Val.isInvalid())
2988 NewStep = Val.get();
2990 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2991 // If test-expr is of form var relational-op b and relational-op is < or
2992 // <= then incr-expr must cause var to increase on each iteration of the
2993 // loop. If test-expr is of form var relational-op b and relational-op is
2994 // > or >= then incr-expr must cause var to decrease on each iteration of
2996 // If test-expr is of form b relational-op var and relational-op is < or
2997 // <= then incr-expr must cause var to decrease on each iteration of the
2998 // loop. If test-expr is of form b relational-op var and relational-op is
2999 // > or >= then incr-expr must cause var to increase on each iteration of
3001 llvm::APSInt Result;
3002 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3003 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3005 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
3007 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
3008 bool IsConstZero = IsConstant && !Result.getBoolValue();
3009 if (UB && (IsConstZero ||
3010 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
3011 : (IsConstPos || (IsUnsigned && !Subtract))))) {
3012 SemaRef.Diag(NewStep->getExprLoc(),
3013 diag::err_omp_loop_incr_not_compatible)
3014 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
3015 SemaRef.Diag(ConditionLoc,
3016 diag::note_omp_loop_cond_requres_compatible_incr)
3017 << TestIsLessOp << ConditionSrcRange;
3020 if (TestIsLessOp == Subtract) {
3022 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3024 Subtract = !Subtract;
3029 SubtractStep = Subtract;
3033 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
3034 // Check init-expr for canonical loop form and save loop counter
3035 // variable - #Var and its initialization value - #LB.
3036 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3038 // integer-type var = lb
3039 // random-access-iterator-type var = lb
3040 // pointer-type var = lb
3044 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3048 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3049 if (!ExprTemp->cleanupsHaveSideEffects())
3050 S = ExprTemp->getSubExpr();
3052 InitSrcRange = S->getSourceRange();
3053 if (Expr *E = dyn_cast<Expr>(S))
3054 S = E->IgnoreParens();
3055 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3056 if (BO->getOpcode() == BO_Assign) {
3057 auto *LHS = BO->getLHS()->IgnoreParens();
3058 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3059 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3060 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3061 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3062 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3064 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3065 if (ME->isArrow() &&
3066 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3067 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3070 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
3071 if (DS->isSingleDecl()) {
3072 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
3073 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
3074 // Accept non-canonical init form here but emit ext. warning.
3075 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
3076 SemaRef.Diag(S->getLocStart(),
3077 diag::ext_omp_loop_not_canonical_init)
3078 << S->getSourceRange();
3079 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
3083 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3084 if (CE->getOperator() == OO_Equal) {
3085 auto *LHS = CE->getArg(0);
3086 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3087 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3088 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3089 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3090 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3092 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3093 if (ME->isArrow() &&
3094 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3095 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3100 if (Dependent() || SemaRef.CurContext->isDependentContext())
3103 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3104 << S->getSourceRange();
3109 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
3110 /// variable (which may be the loop variable) if possible.
3111 static const ValueDecl *GetInitLCDecl(Expr *E) {
3114 E = getExprAsWritten(E);
3115 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3116 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3117 if ((Ctor->isCopyOrMoveConstructor() ||
3118 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3119 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3120 E = CE->getArg(0)->IgnoreParenImpCasts();
3121 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3122 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3123 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3124 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3125 return getCanonicalDecl(ME->getMemberDecl());
3126 return getCanonicalDecl(VD);
3129 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3130 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3131 return getCanonicalDecl(ME->getMemberDecl());
3135 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3136 // Check test-expr for canonical form, save upper-bound UB, flags for
3137 // less/greater and for strict/non-strict comparison.
3138 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3139 // var relational-op b
3140 // b relational-op var
3143 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
3146 S = getExprAsWritten(S);
3147 SourceLocation CondLoc = S->getLocStart();
3148 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3149 if (BO->isRelationalOp()) {
3150 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3151 return SetUB(BO->getRHS(),
3152 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3153 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3154 BO->getSourceRange(), BO->getOperatorLoc());
3155 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
3156 return SetUB(BO->getLHS(),
3157 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3158 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3159 BO->getSourceRange(), BO->getOperatorLoc());
3161 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3162 if (CE->getNumArgs() == 2) {
3163 auto Op = CE->getOperator();
3166 case OO_GreaterEqual:
3169 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3170 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3171 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3172 CE->getOperatorLoc());
3173 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
3174 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3175 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3176 CE->getOperatorLoc());
3183 if (Dependent() || SemaRef.CurContext->isDependentContext())
3185 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
3186 << S->getSourceRange() << LCDecl;
3190 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3191 // RHS of canonical loop form increment can be:
3196 RHS = RHS->IgnoreParenImpCasts();
3197 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
3198 if (BO->isAdditiveOp()) {
3199 bool IsAdd = BO->getOpcode() == BO_Add;
3200 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3201 return SetStep(BO->getRHS(), !IsAdd);
3202 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
3203 return SetStep(BO->getLHS(), false);
3205 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
3206 bool IsAdd = CE->getOperator() == OO_Plus;
3207 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
3208 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3209 return SetStep(CE->getArg(1), !IsAdd);
3210 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
3211 return SetStep(CE->getArg(0), false);
3214 if (Dependent() || SemaRef.CurContext->isDependentContext())
3216 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3217 << RHS->getSourceRange() << LCDecl;
3221 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3222 // Check incr-expr for canonical loop form and return true if it
3223 // does not conform.
3224 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3236 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
3239 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3240 if (!ExprTemp->cleanupsHaveSideEffects())
3241 S = ExprTemp->getSubExpr();
3243 IncrementSrcRange = S->getSourceRange();
3244 S = S->IgnoreParens();
3245 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
3246 if (UO->isIncrementDecrementOp() &&
3247 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
3248 return SetStep(SemaRef
3249 .ActOnIntegerConstant(UO->getLocStart(),
3250 (UO->isDecrementOp() ? -1 : 1))
3253 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3254 switch (BO->getOpcode()) {
3257 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3258 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3261 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3262 return CheckIncRHS(BO->getRHS());
3267 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3268 switch (CE->getOperator()) {
3271 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3272 return SetStep(SemaRef
3273 .ActOnIntegerConstant(
3275 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3281 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3282 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3285 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3286 return CheckIncRHS(CE->getArg(1));
3292 if (Dependent() || SemaRef.CurContext->isDependentContext())
3294 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3295 << S->getSourceRange() << LCDecl;
3300 tryBuildCapture(Sema &SemaRef, Expr *Capture,
3301 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3302 if (SemaRef.CurContext->isDependentContext())
3303 return ExprResult(Capture);
3304 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3305 return SemaRef.PerformImplicitConversion(
3306 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3307 /*AllowExplicit=*/true);
3308 auto I = Captures.find(Capture);
3309 if (I != Captures.end())
3310 return buildCapture(SemaRef, Capture, I->second);
3311 DeclRefExpr *Ref = nullptr;
3312 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3313 Captures[Capture] = Ref;
3317 /// \brief Build the expression to calculate the number of iterations.
3318 Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3319 Scope *S, const bool LimitedType,
3320 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3322 auto VarType = LCDecl->getType().getNonReferenceType();
3323 if (VarType->isIntegerType() || VarType->isPointerType() ||
3324 SemaRef.getLangOpts().CPlusPlus) {
3326 auto *UBExpr = TestIsLessOp ? UB : LB;
3327 auto *LBExpr = TestIsLessOp ? LB : UB;
3328 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3329 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
3330 if (!Upper || !Lower)
3333 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3335 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
3336 // BuildBinOp already emitted error, this one is to point user to upper
3337 // and lower bound, and to tell what is passed to 'operator-'.
3338 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3339 << Upper->getSourceRange() << Lower->getSourceRange();
3344 if (!Diff.isUsable())
3347 // Upper - Lower [- 1]
3349 Diff = SemaRef.BuildBinOp(
3350 S, DefaultLoc, BO_Sub, Diff.get(),
3351 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3352 if (!Diff.isUsable())
3355 // Upper - Lower [- 1] + Step
3356 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3357 if (!NewStep.isUsable())
3359 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
3360 if (!Diff.isUsable())
3363 // Parentheses (for dumping/debugging purposes only).
3364 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3365 if (!Diff.isUsable())
3368 // (Upper - Lower [- 1] + Step) / Step
3369 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
3370 if (!Diff.isUsable())
3373 // OpenMP runtime requires 32-bit or 64-bit loop variables.
3374 QualType Type = Diff.get()->getType();
3375 auto &C = SemaRef.Context;
3376 bool UseVarType = VarType->hasIntegerRepresentation() &&
3377 C.getTypeSize(Type) > C.getTypeSize(VarType);
3378 if (!Type->isIntegerType() || UseVarType) {
3380 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3381 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3382 : Type->hasSignedIntegerRepresentation();
3383 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
3384 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3385 Diff = SemaRef.PerformImplicitConversion(
3386 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3387 if (!Diff.isUsable())
3392 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3393 if (NewSize != C.getTypeSize(Type)) {
3394 if (NewSize < C.getTypeSize(Type)) {
3395 assert(NewSize == 64 && "incorrect loop var size");
3396 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3397 << InitSrcRange << ConditionSrcRange;
3399 QualType NewType = C.getIntTypeForBitwidth(
3400 NewSize, Type->hasSignedIntegerRepresentation() ||
3401 C.getTypeSize(Type) < NewSize);
3402 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3403 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3404 Sema::AA_Converting, true);
3405 if (!Diff.isUsable())
3414 Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3415 Scope *S, Expr *Cond,
3416 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3417 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3418 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3419 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3421 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3422 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3423 if (!NewLB.isUsable() || !NewUB.isUsable())
3426 auto CondExpr = SemaRef.BuildBinOp(
3427 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3428 : (TestIsStrictOp ? BO_GT : BO_GE),
3429 NewLB.get(), NewUB.get());
3430 if (CondExpr.isUsable()) {
3431 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3432 SemaRef.Context.BoolTy))
3433 CondExpr = SemaRef.PerformImplicitConversion(
3434 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3435 /*AllowExplicit=*/true);
3437 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3438 // Otherwise use original loop conditon and evaluate it in runtime.
3439 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3442 /// \brief Build reference expression to the counter be used for codegen.
3443 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
3444 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
3445 auto *VD = dyn_cast<VarDecl>(LCDecl);
3447 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3448 auto *Ref = buildDeclRefExpr(
3449 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
3450 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3451 // If the loop control decl is explicitly marked as private, do not mark it
3452 // as captured again.
3453 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3454 Captures.insert(std::make_pair(LCRef, Ref));
3457 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
3461 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
3462 if (LCDecl && !LCDecl->isInvalidDecl()) {
3463 auto Type = LCDecl->getType().getNonReferenceType();
3465 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3466 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
3467 if (PrivateVar->isInvalidDecl())
3469 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3474 /// \brief Build initialization of the counter to be used for codegen.
3475 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3477 /// \brief Build step of the counter be used for codegen.
3478 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3480 /// \brief Iteration space of a single for loop.
3481 struct LoopIterationSpace final {
3482 /// \brief Condition of the loop.
3483 Expr *PreCond = nullptr;
3484 /// \brief This expression calculates the number of iterations in the loop.
3485 /// It is always possible to calculate it before starting the loop.
3486 Expr *NumIterations = nullptr;
3487 /// \brief The loop counter variable.
3488 Expr *CounterVar = nullptr;
3489 /// \brief Private loop counter variable.
3490 Expr *PrivateCounterVar = nullptr;
3491 /// \brief This is initializer for the initial value of #CounterVar.
3492 Expr *CounterInit = nullptr;
3493 /// \brief This is step for the #CounterVar used to generate its update:
3494 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
3495 Expr *CounterStep = nullptr;
3496 /// \brief Should step be subtracted?
3497 bool Subtract = false;
3498 /// \brief Source range of the loop init.
3499 SourceRange InitSrcRange;
3500 /// \brief Source range of the loop condition.
3501 SourceRange CondSrcRange;
3502 /// \brief Source range of the loop increment.
3503 SourceRange IncSrcRange;
3508 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3509 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3510 assert(Init && "Expected loop in canonical form.");
3511 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3512 if (AssociatedLoops > 0 &&
3513 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3514 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
3515 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3516 if (auto *D = ISC.GetLoopDecl()) {
3517 auto *VD = dyn_cast<VarDecl>(D);
3519 if (auto *Private = IsOpenMPCapturedDecl(D))
3522 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3523 /*WithInit=*/false);
3524 VD = cast<VarDecl>(Ref->getDecl());
3527 DSAStack->addLoopControlVariable(D, VD);
3530 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
3534 /// \brief Called on a for stmt to check and extract its iteration space
3535 /// for further processing (such as collapsing).
3536 static bool CheckOpenMPIterationSpace(
3537 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3538 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
3539 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
3540 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
3541 LoopIterationSpace &ResultIterSpace,
3542 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3543 // OpenMP [2.6, Canonical Loop Form]
3544 // for (init-expr; test-expr; incr-expr) structured-block
3545 auto *For = dyn_cast_or_null<ForStmt>(S);
3547 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
3548 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3549 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3550 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3551 if (NestedLoopCount > 1) {
3552 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3553 SemaRef.Diag(DSA.getConstructLoc(),
3554 diag::note_omp_collapse_ordered_expr)
3555 << 2 << CollapseLoopCountExpr->getSourceRange()
3556 << OrderedLoopCountExpr->getSourceRange();
3557 else if (CollapseLoopCountExpr)
3558 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3559 diag::note_omp_collapse_ordered_expr)
3560 << 0 << CollapseLoopCountExpr->getSourceRange();
3562 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3563 diag::note_omp_collapse_ordered_expr)
3564 << 1 << OrderedLoopCountExpr->getSourceRange();
3568 assert(For->getBody());
3570 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3573 auto Init = For->getInit();
3574 if (ISC.CheckInit(Init))
3577 bool HasErrors = false;
3579 // Check loop variable's type.
3580 if (auto *LCDecl = ISC.GetLoopDecl()) {
3581 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
3583 // OpenMP [2.6, Canonical Loop Form]
3584 // Var is one of the following:
3585 // A variable of signed or unsigned integer type.
3586 // For C++, a variable of a random access iterator type.
3587 // For C, a variable of a pointer type.
3588 auto VarType = LCDecl->getType().getNonReferenceType();
3589 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3590 !VarType->isPointerType() &&
3591 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3592 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3593 << SemaRef.getLangOpts().CPlusPlus;
3597 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3599 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3600 // parallel for construct is (are) private.
3601 // The loop iteration variable in the associated for-loop of a simd
3602 // construct with just one associated for-loop is linear with a
3603 // constant-linear-step that is the increment of the associated for-loop.
3604 // Exclude loop var from the list of variables with implicitly defined data
3605 // sharing attributes.
3606 VarsWithImplicitDSA.erase(LCDecl);
3608 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3609 // in a Construct, C/C++].
3610 // The loop iteration variable in the associated for-loop of a simd
3611 // construct with just one associated for-loop may be listed in a linear
3612 // clause with a constant-linear-step that is the increment of the
3613 // associated for-loop.
3614 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3615 // parallel for construct may be listed in a private or lastprivate clause.
3616 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3617 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3618 // declared in the loop and it is predetermined as a private.
3619 auto PredeterminedCKind =
3620 isOpenMPSimdDirective(DKind)
3621 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3623 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3624 DVar.CKind != PredeterminedCKind) ||
3625 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3626 isOpenMPDistributeDirective(DKind)) &&
3627 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3628 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3629 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3630 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3631 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3632 << getOpenMPClauseName(PredeterminedCKind);
3633 if (DVar.RefExpr == nullptr)
3634 DVar.CKind = PredeterminedCKind;
3635 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3637 } else if (LoopDeclRefExpr != nullptr) {
3638 // Make the loop iteration variable private (for worksharing constructs),
3639 // linear (for simd directives with the only one associated loop) or
3640 // lastprivate (for simd directives with several collapsed or ordered
3642 if (DVar.CKind == OMPC_unknown)
3643 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3644 [](OpenMPDirectiveKind) -> bool { return true; },
3645 /*FromParent=*/false);
3646 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3649 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3652 HasErrors |= ISC.CheckCond(For->getCond());
3655 HasErrors |= ISC.CheckInc(For->getInc());
3658 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
3661 // Build the loop's iteration space representation.
3662 ResultIterSpace.PreCond =
3663 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
3664 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
3666 (isOpenMPWorksharingDirective(DKind) ||
3667 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3669 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
3670 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
3671 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3672 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3673 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3674 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3675 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3676 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3678 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3679 ResultIterSpace.NumIterations == nullptr ||
3680 ResultIterSpace.CounterVar == nullptr ||
3681 ResultIterSpace.PrivateCounterVar == nullptr ||
3682 ResultIterSpace.CounterInit == nullptr ||
3683 ResultIterSpace.CounterStep == nullptr);
3688 /// \brief Build 'VarRef = Start.
3690 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3692 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3693 // Build 'VarRef = Start.
3694 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3695 if (!NewStart.isUsable())
3697 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
3698 VarRef.get()->getType())) {
3699 NewStart = SemaRef.PerformImplicitConversion(
3700 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3701 /*AllowExplicit=*/true);
3702 if (!NewStart.isUsable())
3707 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3711 /// \brief Build 'VarRef = Start + Iter * Step'.
3713 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3714 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3715 ExprResult Step, bool Subtract,
3716 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
3717 // Add parentheses (for debugging purposes only).
3718 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3719 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3723 ExprResult NewStep = Step;
3725 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
3726 if (NewStep.isInvalid())
3729 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
3730 if (!Update.isUsable())
3733 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3734 // 'VarRef = Start (+|-) Iter * Step'.
3735 ExprResult NewStart = Start;
3737 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
3738 if (NewStart.isInvalid())
3741 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3742 ExprResult SavedUpdate = Update;
3743 ExprResult UpdateVal;
3744 if (VarRef.get()->getType()->isOverloadableType() ||
3745 NewStart.get()->getType()->isOverloadableType() ||
3746 Update.get()->getType()->isOverloadableType()) {
3747 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3748 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3750 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3751 if (Update.isUsable()) {
3753 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3754 VarRef.get(), SavedUpdate.get());
3755 if (UpdateVal.isUsable()) {
3756 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3760 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3763 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3764 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3765 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3766 NewStart.get(), SavedUpdate.get());
3767 if (!Update.isUsable())
3770 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3771 VarRef.get()->getType())) {
3772 Update = SemaRef.PerformImplicitConversion(
3773 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3774 if (!Update.isUsable())
3778 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3783 /// \brief Convert integer expression \a E to make it have at least \a Bits
3785 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
3788 auto &C = SemaRef.Context;
3789 QualType OldType = E->getType();
3790 unsigned HasBits = C.getTypeSize(OldType);
3791 if (HasBits >= Bits)
3792 return ExprResult(E);
3793 // OK to convert to signed, because new type has more bits than old.
3794 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3795 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3799 /// \brief Check if the given expression \a E is a constant integer that fits
3800 /// into \a Bits bits.
3801 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3804 llvm::APSInt Result;
3805 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3806 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3810 /// Build preinits statement for the given declarations.
3811 static Stmt *buildPreInits(ASTContext &Context,
3812 SmallVectorImpl<Decl *> &PreInits) {
3813 if (!PreInits.empty()) {
3814 return new (Context) DeclStmt(
3815 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3816 SourceLocation(), SourceLocation());
3821 /// Build preinits statement for the given declarations.
3822 static Stmt *buildPreInits(ASTContext &Context,
3823 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3824 if (!Captures.empty()) {
3825 SmallVector<Decl *, 16> PreInits;
3826 for (auto &Pair : Captures)
3827 PreInits.push_back(Pair.second->getDecl());
3828 return buildPreInits(Context, PreInits);
3833 /// Build postupdate expression for the given list of postupdates expressions.
3834 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3835 Expr *PostUpdate = nullptr;
3836 if (!PostUpdates.empty()) {
3837 for (auto *E : PostUpdates) {
3838 Expr *ConvE = S.BuildCStyleCastExpr(
3840 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3843 PostUpdate = PostUpdate
3844 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3853 /// \brief Called on a for stmt to check itself and nested loops (if any).
3854 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3855 /// number of collapsed loops otherwise.
3857 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3858 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3860 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
3861 OMPLoopDirective::HelperExprs &Built) {
3862 unsigned NestedLoopCount = 1;
3863 if (CollapseLoopCountExpr) {
3864 // Found 'collapse' clause - calculate collapse number.
3865 llvm::APSInt Result;
3866 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
3867 NestedLoopCount = Result.getLimitedValue();
3869 if (OrderedLoopCountExpr) {
3870 // Found 'ordered' clause - calculate collapse number.
3871 llvm::APSInt Result;
3872 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3873 if (Result.getLimitedValue() < NestedLoopCount) {
3874 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3875 diag::err_omp_wrong_ordered_loop_count)
3876 << OrderedLoopCountExpr->getSourceRange();
3877 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3878 diag::note_collapse_loop_count)
3879 << CollapseLoopCountExpr->getSourceRange();
3881 NestedLoopCount = Result.getLimitedValue();
3884 // This is helper routine for loop directives (e.g., 'for', 'simd',
3885 // 'for simd', etc.).
3886 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
3887 SmallVector<LoopIterationSpace, 4> IterSpaces;
3888 IterSpaces.resize(NestedLoopCount);
3889 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
3890 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
3891 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
3892 NestedLoopCount, CollapseLoopCountExpr,
3893 OrderedLoopCountExpr, VarsWithImplicitDSA,
3894 IterSpaces[Cnt], Captures))
3896 // Move on to the next nested for loop, or to the loop body.
3897 // OpenMP [2.8.1, simd construct, Restrictions]
3898 // All loops associated with the construct must be perfectly nested; that
3899 // is, there must be no intervening code nor any OpenMP directive between
3901 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
3904 Built.clear(/* size */ NestedLoopCount);
3906 if (SemaRef.CurContext->isDependentContext())
3907 return NestedLoopCount;
3909 // An example of what is generated for the following code:
3911 // #pragma omp simd collapse(2) ordered(2)
3912 // for (i = 0; i < NI; ++i)
3913 // for (k = 0; k < NK; ++k)
3914 // for (j = J0; j < NJ; j+=2) {
3918 // We generate the code below.
3919 // Note: the loop body may be outlined in CodeGen.
3920 // Note: some counters may be C++ classes, operator- is used to find number of
3921 // iterations and operator+= to calculate counter value.
3922 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3923 // or i64 is currently supported).
3925 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3926 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3927 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3928 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3929 // // similar updates for vars in clauses (e.g. 'linear')
3930 // <loop body (using local i and j)>
3932 // i = NI; // assign final values of counters
3936 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3937 // the iteration counts of the collapsed for loops.
3938 // Precondition tests if there is at least one iteration (all conditions are
3940 auto PreCond = ExprResult(IterSpaces[0].PreCond);
3941 auto N0 = IterSpaces[0].NumIterations;
3942 ExprResult LastIteration32 = WidenIterationCount(
3943 32 /* Bits */, SemaRef
3944 .PerformImplicitConversion(
3945 N0->IgnoreImpCasts(), N0->getType(),
3946 Sema::AA_Converting, /*AllowExplicit=*/true)
3949 ExprResult LastIteration64 = WidenIterationCount(
3950 64 /* Bits */, SemaRef
3951 .PerformImplicitConversion(
3952 N0->IgnoreImpCasts(), N0->getType(),
3953 Sema::AA_Converting, /*AllowExplicit=*/true)
3957 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3958 return NestedLoopCount;
3960 auto &C = SemaRef.Context;
3961 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3963 Scope *CurScope = DSA.getCurScope();
3964 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
3965 if (PreCond.isUsable()) {
3967 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
3968 PreCond.get(), IterSpaces[Cnt].PreCond);
3970 auto N = IterSpaces[Cnt].NumIterations;
3971 SourceLocation Loc = N->getExprLoc();
3972 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3973 if (LastIteration32.isUsable())
3974 LastIteration32 = SemaRef.BuildBinOp(
3975 CurScope, Loc, BO_Mul, LastIteration32.get(),
3977 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3978 Sema::AA_Converting,
3979 /*AllowExplicit=*/true)
3981 if (LastIteration64.isUsable())
3982 LastIteration64 = SemaRef.BuildBinOp(
3983 CurScope, Loc, BO_Mul, LastIteration64.get(),
3985 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3986 Sema::AA_Converting,
3987 /*AllowExplicit=*/true)
3991 // Choose either the 32-bit or 64-bit version.
3992 ExprResult LastIteration = LastIteration64;
3993 if (LastIteration32.isUsable() &&
3994 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3995 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3998 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3999 LastIteration64.get(), SemaRef)))
4000 LastIteration = LastIteration32;
4001 QualType VType = LastIteration.get()->getType();
4002 QualType RealVType = VType;
4003 QualType StrideVType = VType;
4004 if (isOpenMPTaskLoopDirective(DKind)) {
4006 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4008 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4011 if (!LastIteration.isUsable())
4014 // Save the number of iterations.
4015 ExprResult NumIterations = LastIteration;
4017 LastIteration = SemaRef.BuildBinOp(
4018 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4019 LastIteration.get(),
4020 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4021 if (!LastIteration.isUsable())
4025 // Calculate the last iteration number beforehand instead of doing this on
4026 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4027 llvm::APSInt Result;
4029 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4030 ExprResult CalcLastIteration;
4032 ExprResult SaveRef =
4033 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
4034 LastIteration = SaveRef;
4036 // Prepare SaveRef + 1.
4037 NumIterations = SemaRef.BuildBinOp(
4038 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
4039 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4040 if (!NumIterations.isUsable())
4044 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4046 // Build variables passed into runtime, necessary for worksharing directives.
4047 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
4048 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4049 isOpenMPDistributeDirective(DKind)) {
4050 // Lower bound variable, initialized with zero.
4051 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4052 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
4053 SemaRef.AddInitializerToDecl(LBDecl,
4054 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4055 /*DirectInit*/ false);
4057 // Upper bound variable, initialized with last iteration number.
4058 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4059 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
4060 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
4061 /*DirectInit*/ false);
4063 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4064 // This will be used to implement clause 'lastprivate'.
4065 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
4066 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4067 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
4068 SemaRef.AddInitializerToDecl(ILDecl,
4069 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4070 /*DirectInit*/ false);
4072 // Stride variable returned by runtime (we initialize it to 1 by default).
4074 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4075 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
4076 SemaRef.AddInitializerToDecl(STDecl,
4077 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4078 /*DirectInit*/ false);
4080 // Build expression: UB = min(UB, LastIteration)
4081 // It is necessary for CodeGen of directives with static scheduling.
4082 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4083 UB.get(), LastIteration.get());
4084 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4085 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4086 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4088 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
4090 // If we have a combined directive that combines 'distribute', 'for' or
4091 // 'simd' we need to be able to access the bounds of the schedule of the
4092 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4093 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4094 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4095 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4097 // We expect to have at least 2 more parameters than the 'parallel'
4098 // directive does - the lower and upper bounds of the previous schedule.
4099 assert(CD->getNumParams() >= 4 &&
4100 "Unexpected number of parameters in loop combined directive");
4102 // Set the proper type for the bounds given what we learned from the
4104 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4105 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4107 // Previous lower and upper bounds are obtained from the region
4110 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4112 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4116 // Build the iteration variable and its initialization before loop.
4120 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4121 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
4123 (isOpenMPWorksharingDirective(DKind) ||
4124 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4126 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4127 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4128 Init = SemaRef.ActOnFinishFullExpr(Init.get());
4131 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
4132 SourceLocation CondLoc;
4134 (isOpenMPWorksharingDirective(DKind) ||
4135 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4136 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4137 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4138 NumIterations.get());
4140 // Loop increment (IV = IV + 1)
4141 SourceLocation IncLoc;
4143 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4144 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4145 if (!Inc.isUsable())
4147 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
4148 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4149 if (!Inc.isUsable())
4152 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4153 // Used for directives with static scheduling.
4154 ExprResult NextLB, NextUB;
4155 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4156 isOpenMPDistributeDirective(DKind)) {
4158 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4159 if (!NextLB.isUsable())
4163 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4164 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4165 if (!NextLB.isUsable())
4168 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4169 if (!NextUB.isUsable())
4173 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4174 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4175 if (!NextUB.isUsable())
4179 // Build updates and final values of the loop counters.
4180 bool HasErrors = false;
4181 Built.Counters.resize(NestedLoopCount);
4182 Built.Inits.resize(NestedLoopCount);
4183 Built.Updates.resize(NestedLoopCount);
4184 Built.Finals.resize(NestedLoopCount);
4185 SmallVector<Expr *, 4> LoopMultipliers;
4188 // Go from inner nested loop to outer.
4189 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4190 LoopIterationSpace &IS = IterSpaces[Cnt];
4191 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4192 // Build: Iter = (IV / Div) % IS.NumIters
4193 // where Div is product of previous iterations' IS.NumIters.
4195 if (Div.isUsable()) {
4197 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4200 assert((Cnt == (int)NestedLoopCount - 1) &&
4201 "unusable div expected on first iteration only");
4204 if (Cnt != 0 && Iter.isUsable())
4205 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4207 if (!Iter.isUsable()) {
4212 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
4213 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4214 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4215 IS.CounterVar->getExprLoc(),
4216 /*RefersToCapture=*/true);
4217 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
4218 IS.CounterInit, Captures);
4219 if (!Init.isUsable()) {
4223 ExprResult Update = BuildCounterUpdate(
4224 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4225 IS.CounterStep, IS.Subtract, &Captures);
4226 if (!Update.isUsable()) {
4231 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4232 ExprResult Final = BuildCounterUpdate(
4233 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
4234 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
4235 if (!Final.isUsable()) {
4240 // Build Div for the next iteration: Div <- Div * IS.NumIters
4243 Div = IS.NumIterations;
4245 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4248 // Add parentheses (for debugging purposes only).
4250 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
4251 if (!Div.isUsable()) {
4255 LoopMultipliers.push_back(Div.get());
4257 if (!Update.isUsable() || !Final.isUsable()) {
4262 Built.Counters[Cnt] = IS.CounterVar;
4263 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
4264 Built.Inits[Cnt] = Init.get();
4265 Built.Updates[Cnt] = Update.get();
4266 Built.Finals[Cnt] = Final.get();
4274 Built.IterationVarRef = IV.get();
4275 Built.LastIteration = LastIteration.get();
4276 Built.NumIterations = NumIterations.get();
4277 Built.CalcLastIteration =
4278 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
4279 Built.PreCond = PreCond.get();
4280 Built.PreInits = buildPreInits(C, Captures);
4281 Built.Cond = Cond.get();
4282 Built.Init = Init.get();
4283 Built.Inc = Inc.get();
4284 Built.LB = LB.get();
4285 Built.UB = UB.get();
4286 Built.IL = IL.get();
4287 Built.ST = ST.get();
4288 Built.EUB = EUB.get();
4289 Built.NLB = NextLB.get();
4290 Built.NUB = NextUB.get();
4291 Built.PrevLB = PrevLB.get();
4292 Built.PrevUB = PrevUB.get();
4294 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4295 // Fill data for doacross depend clauses.
4296 for (auto Pair : DSA.getDoacrossDependClauses()) {
4297 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4298 Pair.first->setCounterValue(CounterVal);
4300 if (NestedLoopCount != Pair.second.size() ||
4301 NestedLoopCount != LoopMultipliers.size() + 1) {
4302 // Erroneous case - clause has some problems.
4303 Pair.first->setCounterValue(CounterVal);
4306 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4307 auto I = Pair.second.rbegin();
4308 auto IS = IterSpaces.rbegin();
4309 auto ILM = LoopMultipliers.rbegin();
4310 Expr *UpCounterVal = CounterVal;
4311 Expr *Multiplier = nullptr;
4312 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4314 assert(IS->CounterStep);
4315 Expr *NormalizedOffset =
4317 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4318 I->first, IS->CounterStep)
4323 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4324 NormalizedOffset, Multiplier)
4327 assert(I->second == OO_Plus || I->second == OO_Minus);
4328 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
4329 UpCounterVal = SemaRef
4330 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4331 UpCounterVal, NormalizedOffset)
4339 Pair.first->setCounterValue(UpCounterVal);
4343 return NestedLoopCount;
4346 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
4347 auto CollapseClauses =
4348 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4349 if (CollapseClauses.begin() != CollapseClauses.end())
4350 return (*CollapseClauses.begin())->getNumForLoops();
4354 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
4355 auto OrderedClauses =
4356 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4357 if (OrderedClauses.begin() != OrderedClauses.end())
4358 return (*OrderedClauses.begin())->getNumForLoops();
4362 static bool checkSimdlenSafelenSpecified(Sema &S,
4363 const ArrayRef<OMPClause *> Clauses) {
4364 OMPSafelenClause *Safelen = nullptr;
4365 OMPSimdlenClause *Simdlen = nullptr;
4367 for (auto *Clause : Clauses) {
4368 if (Clause->getClauseKind() == OMPC_safelen)
4369 Safelen = cast<OMPSafelenClause>(Clause);
4370 else if (Clause->getClauseKind() == OMPC_simdlen)
4371 Simdlen = cast<OMPSimdlenClause>(Clause);
4372 if (Safelen && Simdlen)
4376 if (Simdlen && Safelen) {
4377 llvm::APSInt SimdlenRes, SafelenRes;
4378 auto SimdlenLength = Simdlen->getSimdlen();
4379 auto SafelenLength = Safelen->getSafelen();
4380 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4381 SimdlenLength->isInstantiationDependent() ||
4382 SimdlenLength->containsUnexpandedParameterPack())
4384 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4385 SafelenLength->isInstantiationDependent() ||
4386 SafelenLength->containsUnexpandedParameterPack())
4388 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4389 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4390 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4391 // If both simdlen and safelen clauses are specified, the value of the
4392 // simdlen parameter must be less than or equal to the value of the safelen
4394 if (SimdlenRes > SafelenRes) {
4395 S.Diag(SimdlenLength->getExprLoc(),
4396 diag::err_omp_wrong_simdlen_safelen_values)
4397 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4404 StmtResult Sema::ActOnOpenMPSimdDirective(
4405 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4406 SourceLocation EndLoc,
4407 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4411 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4412 OMPLoopDirective::HelperExprs B;
4413 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4414 // define the nested loops number.
4415 unsigned NestedLoopCount = CheckOpenMPLoop(
4416 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4417 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4418 if (NestedLoopCount == 0)
4421 assert((CurContext->isDependentContext() || B.builtAll()) &&
4422 "omp simd loop exprs were not built");
4424 if (!CurContext->isDependentContext()) {
4425 // Finalize the clauses that need pre-built expressions for CodeGen.
4426 for (auto C : Clauses) {
4427 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4428 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4429 B.NumIterations, *this, CurScope,
4435 if (checkSimdlenSafelenSpecified(*this, Clauses))
4438 getCurFunction()->setHasBranchProtectedScope();
4439 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4443 StmtResult Sema::ActOnOpenMPForDirective(
4444 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4445 SourceLocation EndLoc,
4446 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4450 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4451 OMPLoopDirective::HelperExprs B;
4452 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4453 // define the nested loops number.
4454 unsigned NestedLoopCount = CheckOpenMPLoop(
4455 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4456 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4457 if (NestedLoopCount == 0)
4460 assert((CurContext->isDependentContext() || B.builtAll()) &&
4461 "omp for loop exprs were not built");
4463 if (!CurContext->isDependentContext()) {
4464 // Finalize the clauses that need pre-built expressions for CodeGen.
4465 for (auto C : Clauses) {
4466 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4467 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4468 B.NumIterations, *this, CurScope,
4474 getCurFunction()->setHasBranchProtectedScope();
4475 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4476 Clauses, AStmt, B, DSAStack->isCancelRegion());
4479 StmtResult Sema::ActOnOpenMPForSimdDirective(
4480 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4481 SourceLocation EndLoc,
4482 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4486 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4487 OMPLoopDirective::HelperExprs B;
4488 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4489 // define the nested loops number.
4490 unsigned NestedLoopCount =
4491 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4492 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4493 VarsWithImplicitDSA, B);
4494 if (NestedLoopCount == 0)
4497 assert((CurContext->isDependentContext() || B.builtAll()) &&
4498 "omp for simd loop exprs were not built");
4500 if (!CurContext->isDependentContext()) {
4501 // Finalize the clauses that need pre-built expressions for CodeGen.
4502 for (auto C : Clauses) {
4503 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4504 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4505 B.NumIterations, *this, CurScope,
4511 if (checkSimdlenSafelenSpecified(*this, Clauses))
4514 getCurFunction()->setHasBranchProtectedScope();
4515 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4519 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4521 SourceLocation StartLoc,
4522 SourceLocation EndLoc) {
4526 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4527 auto BaseStmt = AStmt;
4528 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4529 BaseStmt = CS->getCapturedStmt();
4530 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4531 auto S = C->children();
4532 if (S.begin() == S.end())
4534 // All associated statements must be '#pragma omp section' except for
4536 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4537 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4539 Diag(SectionStmt->getLocStart(),
4540 diag::err_omp_sections_substmt_not_section);
4543 cast<OMPSectionDirective>(SectionStmt)
4544 ->setHasCancel(DSAStack->isCancelRegion());
4547 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4551 getCurFunction()->setHasBranchProtectedScope();
4553 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4554 DSAStack->isCancelRegion());
4557 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4558 SourceLocation StartLoc,
4559 SourceLocation EndLoc) {
4563 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4565 getCurFunction()->setHasBranchProtectedScope();
4566 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
4568 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4569 DSAStack->isCancelRegion());
4572 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4574 SourceLocation StartLoc,
4575 SourceLocation EndLoc) {
4579 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4581 getCurFunction()->setHasBranchProtectedScope();
4583 // OpenMP [2.7.3, single Construct, Restrictions]
4584 // The copyprivate clause must not be used with the nowait clause.
4585 OMPClause *Nowait = nullptr;
4586 OMPClause *Copyprivate = nullptr;
4587 for (auto *Clause : Clauses) {
4588 if (Clause->getClauseKind() == OMPC_nowait)
4590 else if (Clause->getClauseKind() == OMPC_copyprivate)
4591 Copyprivate = Clause;
4592 if (Copyprivate && Nowait) {
4593 Diag(Copyprivate->getLocStart(),
4594 diag::err_omp_single_copyprivate_with_nowait);
4595 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4600 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4603 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4604 SourceLocation StartLoc,
4605 SourceLocation EndLoc) {
4609 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4611 getCurFunction()->setHasBranchProtectedScope();
4613 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4616 StmtResult Sema::ActOnOpenMPCriticalDirective(
4617 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4618 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
4622 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4624 bool ErrorFound = false;
4626 SourceLocation HintLoc;
4627 bool DependentHint = false;
4628 for (auto *C : Clauses) {
4629 if (C->getClauseKind() == OMPC_hint) {
4630 if (!DirName.getName()) {
4631 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4634 Expr *E = cast<OMPHintClause>(C)->getHint();
4635 if (E->isTypeDependent() || E->isValueDependent() ||
4636 E->isInstantiationDependent())
4637 DependentHint = true;
4639 Hint = E->EvaluateKnownConstInt(Context);
4640 HintLoc = C->getLocStart();
4646 auto Pair = DSAStack->getCriticalWithHint(DirName);
4647 if (Pair.first && DirName.getName() && !DependentHint) {
4648 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4649 Diag(StartLoc, diag::err_omp_critical_with_hint);
4650 if (HintLoc.isValid()) {
4651 Diag(HintLoc, diag::note_omp_critical_hint_here)
4652 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4654 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4655 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4656 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4658 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4659 /*Radix=*/10, /*Signed=*/false);
4661 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4665 getCurFunction()->setHasBranchProtectedScope();
4667 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4669 if (!Pair.first && DirName.getName() && !DependentHint)
4670 DSAStack->addCriticalWithHint(Dir, Hint);
4674 StmtResult Sema::ActOnOpenMPParallelForDirective(
4675 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4676 SourceLocation EndLoc,
4677 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4681 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4682 // 1.2.2 OpenMP Language Terminology
4683 // Structured block - An executable statement with a single entry at the
4684 // top and a single exit at the bottom.
4685 // The point of exit cannot be a branch out of the structured block.
4686 // longjmp() and throw() must not violate the entry/exit criteria.
4687 CS->getCapturedDecl()->setNothrow();
4689 OMPLoopDirective::HelperExprs B;
4690 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4691 // define the nested loops number.
4692 unsigned NestedLoopCount =
4693 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4694 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4695 VarsWithImplicitDSA, B);
4696 if (NestedLoopCount == 0)
4699 assert((CurContext->isDependentContext() || B.builtAll()) &&
4700 "omp parallel for loop exprs were not built");
4702 if (!CurContext->isDependentContext()) {
4703 // Finalize the clauses that need pre-built expressions for CodeGen.
4704 for (auto C : Clauses) {
4705 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4706 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4707 B.NumIterations, *this, CurScope,
4713 getCurFunction()->setHasBranchProtectedScope();
4714 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
4715 NestedLoopCount, Clauses, AStmt, B,
4716 DSAStack->isCancelRegion());
4719 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4720 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4721 SourceLocation EndLoc,
4722 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4726 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4727 // 1.2.2 OpenMP Language Terminology
4728 // Structured block - An executable statement with a single entry at the
4729 // top and a single exit at the bottom.
4730 // The point of exit cannot be a branch out of the structured block.
4731 // longjmp() and throw() must not violate the entry/exit criteria.
4732 CS->getCapturedDecl()->setNothrow();
4734 OMPLoopDirective::HelperExprs B;
4735 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4736 // define the nested loops number.
4737 unsigned NestedLoopCount =
4738 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4739 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4740 VarsWithImplicitDSA, B);
4741 if (NestedLoopCount == 0)
4744 if (!CurContext->isDependentContext()) {
4745 // Finalize the clauses that need pre-built expressions for CodeGen.
4746 for (auto C : Clauses) {
4747 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4748 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4749 B.NumIterations, *this, CurScope,
4755 if (checkSimdlenSafelenSpecified(*this, Clauses))
4758 getCurFunction()->setHasBranchProtectedScope();
4759 return OMPParallelForSimdDirective::Create(
4760 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
4764 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4765 Stmt *AStmt, SourceLocation StartLoc,
4766 SourceLocation EndLoc) {
4770 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4771 auto BaseStmt = AStmt;
4772 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4773 BaseStmt = CS->getCapturedStmt();
4774 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4775 auto S = C->children();
4776 if (S.begin() == S.end())
4778 // All associated statements must be '#pragma omp section' except for
4780 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4781 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4783 Diag(SectionStmt->getLocStart(),
4784 diag::err_omp_parallel_sections_substmt_not_section);
4787 cast<OMPSectionDirective>(SectionStmt)
4788 ->setHasCancel(DSAStack->isCancelRegion());
4791 Diag(AStmt->getLocStart(),
4792 diag::err_omp_parallel_sections_not_compound_stmt);
4796 getCurFunction()->setHasBranchProtectedScope();
4798 return OMPParallelSectionsDirective::Create(
4799 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
4802 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4803 Stmt *AStmt, SourceLocation StartLoc,
4804 SourceLocation EndLoc) {
4808 auto *CS = cast<CapturedStmt>(AStmt);
4809 // 1.2.2 OpenMP Language Terminology
4810 // Structured block - An executable statement with a single entry at the
4811 // top and a single exit at the bottom.
4812 // The point of exit cannot be a branch out of the structured block.
4813 // longjmp() and throw() must not violate the entry/exit criteria.
4814 CS->getCapturedDecl()->setNothrow();
4816 getCurFunction()->setHasBranchProtectedScope();
4818 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4819 DSAStack->isCancelRegion());
4822 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4823 SourceLocation EndLoc) {
4824 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4827 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4828 SourceLocation EndLoc) {
4829 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4832 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4833 SourceLocation EndLoc) {
4834 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4837 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4838 SourceLocation StartLoc,
4839 SourceLocation EndLoc) {
4843 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4845 getCurFunction()->setHasBranchProtectedScope();
4847 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4850 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4851 SourceLocation StartLoc,
4852 SourceLocation EndLoc) {
4853 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4854 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4857 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4859 SourceLocation StartLoc,
4860 SourceLocation EndLoc) {
4861 OMPClause *DependFound = nullptr;
4862 OMPClause *DependSourceClause = nullptr;
4863 OMPClause *DependSinkClause = nullptr;
4864 bool ErrorFound = false;
4865 OMPThreadsClause *TC = nullptr;
4866 OMPSIMDClause *SC = nullptr;
4867 for (auto *C : Clauses) {
4868 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4870 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4871 if (DependSourceClause) {
4872 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4873 << getOpenMPDirectiveName(OMPD_ordered)
4874 << getOpenMPClauseName(OMPC_depend) << 2;
4877 DependSourceClause = C;
4878 if (DependSinkClause) {
4879 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4883 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4884 if (DependSourceClause) {
4885 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4889 DependSinkClause = C;
4891 } else if (C->getClauseKind() == OMPC_threads)
4892 TC = cast<OMPThreadsClause>(C);
4893 else if (C->getClauseKind() == OMPC_simd)
4894 SC = cast<OMPSIMDClause>(C);
4896 if (!ErrorFound && !SC &&
4897 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
4898 // OpenMP [2.8.1,simd Construct, Restrictions]
4899 // An ordered construct with the simd clause is the only OpenMP construct
4900 // that can appear in the simd region.
4901 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
4903 } else if (DependFound && (TC || SC)) {
4904 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4905 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4907 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4908 Diag(DependFound->getLocStart(),
4909 diag::err_omp_ordered_directive_without_param);
4911 } else if (TC || Clauses.empty()) {
4912 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4913 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4914 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4916 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4920 if ((!AStmt && !DependFound) || ErrorFound)
4924 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4926 getCurFunction()->setHasBranchProtectedScope();
4929 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4933 /// \brief Helper class for checking expression in 'omp atomic [update]'
4935 class OpenMPAtomicUpdateChecker {
4936 /// \brief Error results for atomic update expressions.
4937 enum ExprAnalysisErrorCode {
4938 /// \brief A statement is not an expression statement.
4940 /// \brief Expression is not builtin binary or unary operation.
4941 NotABinaryOrUnaryExpression,
4942 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4943 NotAnUnaryIncDecExpression,
4944 /// \brief An expression is not of scalar type.
4946 /// \brief A binary operation is not an assignment operation.
4948 /// \brief RHS part of the binary operation is not a binary expression.
4949 NotABinaryExpression,
4950 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4953 /// \brief RHS binary operation does not have reference to the updated LHS
4955 NotAnUpdateExpression,
4956 /// \brief No errors is found.
4959 /// \brief Reference to Sema.
4961 /// \brief A location for note diagnostics (when error is found).
4962 SourceLocation NoteLoc;
4963 /// \brief 'x' lvalue part of the source atomic expression.
4965 /// \brief 'expr' rvalue part of the source atomic expression.
4967 /// \brief Helper expression of the form
4968 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4969 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4971 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4972 /// important for non-associative operations.
4973 bool IsXLHSInRHSPart;
4974 BinaryOperatorKind Op;
4975 SourceLocation OpLoc;
4976 /// \brief true if the source expression is a postfix unary operation, false
4977 /// if it is a prefix unary operation.
4978 bool IsPostfixUpdate;
4981 OpenMPAtomicUpdateChecker(Sema &SemaRef)
4982 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
4983 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
4984 /// \brief Check specified statement that it is suitable for 'atomic update'
4985 /// constructs and extract 'x', 'expr' and Operation from the original
4986 /// expression. If DiagId and NoteId == 0, then only check is performed
4987 /// without error notification.
4988 /// \param DiagId Diagnostic which should be emitted if error is found.
4989 /// \param NoteId Diagnostic note for the main error message.
4990 /// \return true if statement is not an update expression, false otherwise.
4991 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
4992 /// \brief Return the 'x' lvalue part of the source atomic expression.
4993 Expr *getX() const { return X; }
4994 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4995 Expr *getExpr() const { return E; }
4996 /// \brief Return the update expression used in calculation of the updated
4997 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4998 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4999 Expr *getUpdateExpr() const { return UpdateExpr; }
5000 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5001 /// false otherwise.
5002 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5004 /// \brief true if the source expression is a postfix unary operation, false
5005 /// if it is a prefix unary operation.
5006 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5009 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5010 unsigned NoteId = 0);
5014 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5015 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5016 ExprAnalysisErrorCode ErrorFound = NoError;
5017 SourceLocation ErrorLoc, NoteLoc;
5018 SourceRange ErrorRange, NoteRange;
5019 // Allowed constructs are:
5020 // x = x binop expr;
5021 // x = expr binop x;
5022 if (AtomicBinOp->getOpcode() == BO_Assign) {
5023 X = AtomicBinOp->getLHS();
5024 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5025 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5026 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5027 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5028 AtomicInnerBinOp->isBitwiseOp()) {
5029 Op = AtomicInnerBinOp->getOpcode();
5030 OpLoc = AtomicInnerBinOp->getOperatorLoc();
5031 auto *LHS = AtomicInnerBinOp->getLHS();
5032 auto *RHS = AtomicInnerBinOp->getRHS();
5033 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5034 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5035 /*Canonical=*/true);
5036 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5037 /*Canonical=*/true);
5038 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5039 /*Canonical=*/true);
5042 IsXLHSInRHSPart = true;
5043 } else if (XId == RHSId) {
5045 IsXLHSInRHSPart = false;
5047 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5048 ErrorRange = AtomicInnerBinOp->getSourceRange();
5049 NoteLoc = X->getExprLoc();
5050 NoteRange = X->getSourceRange();
5051 ErrorFound = NotAnUpdateExpression;
5054 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5055 ErrorRange = AtomicInnerBinOp->getSourceRange();
5056 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5057 NoteRange = SourceRange(NoteLoc, NoteLoc);
5058 ErrorFound = NotABinaryOperator;
5061 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5062 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5063 ErrorFound = NotABinaryExpression;
5066 ErrorLoc = AtomicBinOp->getExprLoc();
5067 ErrorRange = AtomicBinOp->getSourceRange();
5068 NoteLoc = AtomicBinOp->getOperatorLoc();
5069 NoteRange = SourceRange(NoteLoc, NoteLoc);
5070 ErrorFound = NotAnAssignmentOp;
5072 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5073 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5074 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5076 } else if (SemaRef.CurContext->isDependentContext())
5077 E = X = UpdateExpr = nullptr;
5078 return ErrorFound != NoError;
5081 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5083 ExprAnalysisErrorCode ErrorFound = NoError;
5084 SourceLocation ErrorLoc, NoteLoc;
5085 SourceRange ErrorRange, NoteRange;
5086 // Allowed constructs are:
5092 // x = x binop expr;
5093 // x = expr binop x;
5094 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5095 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5096 if (AtomicBody->getType()->isScalarType() ||
5097 AtomicBody->isInstantiationDependent()) {
5098 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5099 AtomicBody->IgnoreParenImpCasts())) {
5100 // Check for Compound Assignment Operation
5101 Op = BinaryOperator::getOpForCompoundAssignment(
5102 AtomicCompAssignOp->getOpcode());
5103 OpLoc = AtomicCompAssignOp->getOperatorLoc();
5104 E = AtomicCompAssignOp->getRHS();
5105 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
5106 IsXLHSInRHSPart = true;
5107 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5108 AtomicBody->IgnoreParenImpCasts())) {
5109 // Check for Binary Operation
5110 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
5112 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5113 AtomicBody->IgnoreParenImpCasts())) {
5114 // Check for Unary Operation
5115 if (AtomicUnaryOp->isIncrementDecrementOp()) {
5116 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
5117 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5118 OpLoc = AtomicUnaryOp->getOperatorLoc();
5119 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
5120 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5121 IsXLHSInRHSPart = true;
5123 ErrorFound = NotAnUnaryIncDecExpression;
5124 ErrorLoc = AtomicUnaryOp->getExprLoc();
5125 ErrorRange = AtomicUnaryOp->getSourceRange();
5126 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5127 NoteRange = SourceRange(NoteLoc, NoteLoc);
5129 } else if (!AtomicBody->isInstantiationDependent()) {
5130 ErrorFound = NotABinaryOrUnaryExpression;
5131 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5132 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5135 ErrorFound = NotAScalarType;
5136 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5137 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5140 ErrorFound = NotAnExpression;
5141 NoteLoc = ErrorLoc = S->getLocStart();
5142 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5144 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5145 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5146 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5148 } else if (SemaRef.CurContext->isDependentContext())
5149 E = X = UpdateExpr = nullptr;
5150 if (ErrorFound == NoError && E && X) {
5151 // Build an update expression of form 'OpaqueValueExpr(x) binop
5152 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5153 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5154 auto *OVEX = new (SemaRef.getASTContext())
5155 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5156 auto *OVEExpr = new (SemaRef.getASTContext())
5157 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5159 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5160 IsXLHSInRHSPart ? OVEExpr : OVEX);
5161 if (Update.isInvalid())
5163 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5165 if (Update.isInvalid())
5167 UpdateExpr = Update.get();
5169 return ErrorFound != NoError;
5172 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5174 SourceLocation StartLoc,
5175 SourceLocation EndLoc) {
5179 auto *CS = cast<CapturedStmt>(AStmt);
5180 // 1.2.2 OpenMP Language Terminology
5181 // Structured block - An executable statement with a single entry at the
5182 // top and a single exit at the bottom.
5183 // The point of exit cannot be a branch out of the structured block.
5184 // longjmp() and throw() must not violate the entry/exit criteria.
5185 OpenMPClauseKind AtomicKind = OMPC_unknown;
5186 SourceLocation AtomicKindLoc;
5187 for (auto *C : Clauses) {
5188 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
5189 C->getClauseKind() == OMPC_update ||
5190 C->getClauseKind() == OMPC_capture) {
5191 if (AtomicKind != OMPC_unknown) {
5192 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5193 << SourceRange(C->getLocStart(), C->getLocEnd());
5194 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5195 << getOpenMPClauseName(AtomicKind);
5197 AtomicKind = C->getClauseKind();
5198 AtomicKindLoc = C->getLocStart();
5203 auto Body = CS->getCapturedStmt();
5204 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5205 Body = EWC->getSubExpr();
5211 bool IsXLHSInRHSPart = false;
5212 bool IsPostfixUpdate = false;
5213 // OpenMP [2.12.6, atomic Construct]
5214 // In the next expressions:
5215 // * x and v (as applicable) are both l-value expressions with scalar type.
5216 // * During the execution of an atomic region, multiple syntactic
5217 // occurrences of x must designate the same storage location.
5218 // * Neither of v and expr (as applicable) may access the storage location
5220 // * Neither of x and expr (as applicable) may access the storage location
5222 // * expr is an expression with scalar type.
5223 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5224 // * binop, binop=, ++, and -- are not overloaded operators.
5225 // * The expression x binop expr must be numerically equivalent to x binop
5226 // (expr). This requirement is satisfied if the operators in expr have
5227 // precedence greater than binop, or by using parentheses around expr or
5228 // subexpressions of expr.
5229 // * The expression expr binop x must be numerically equivalent to (expr)
5230 // binop x. This requirement is satisfied if the operators in expr have
5231 // precedence equal to or greater than binop, or by using parentheses around
5232 // expr or subexpressions of expr.
5233 // * For forms that allow multiple occurrences of x, the number of times
5234 // that x is evaluated is unspecified.
5235 if (AtomicKind == OMPC_read) {
5242 } ErrorFound = NoError;
5243 SourceLocation ErrorLoc, NoteLoc;
5244 SourceRange ErrorRange, NoteRange;
5245 // If clause is read:
5247 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5249 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5250 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5251 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5252 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5253 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5254 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5255 if (!X->isLValue() || !V->isLValue()) {
5256 auto NotLValueExpr = X->isLValue() ? V : X;
5257 ErrorFound = NotAnLValue;
5258 ErrorLoc = AtomicBinOp->getExprLoc();
5259 ErrorRange = AtomicBinOp->getSourceRange();
5260 NoteLoc = NotLValueExpr->getExprLoc();
5261 NoteRange = NotLValueExpr->getSourceRange();
5263 } else if (!X->isInstantiationDependent() ||
5264 !V->isInstantiationDependent()) {
5265 auto NotScalarExpr =
5266 (X->isInstantiationDependent() || X->getType()->isScalarType())
5269 ErrorFound = NotAScalarType;
5270 ErrorLoc = AtomicBinOp->getExprLoc();
5271 ErrorRange = AtomicBinOp->getSourceRange();
5272 NoteLoc = NotScalarExpr->getExprLoc();
5273 NoteRange = NotScalarExpr->getSourceRange();
5275 } else if (!AtomicBody->isInstantiationDependent()) {
5276 ErrorFound = NotAnAssignmentOp;
5277 ErrorLoc = AtomicBody->getExprLoc();
5278 ErrorRange = AtomicBody->getSourceRange();
5279 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5280 : AtomicBody->getExprLoc();
5281 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5282 : AtomicBody->getSourceRange();
5285 ErrorFound = NotAnExpression;
5286 NoteLoc = ErrorLoc = Body->getLocStart();
5287 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5289 if (ErrorFound != NoError) {
5290 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5292 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5295 } else if (CurContext->isDependentContext())
5297 } else if (AtomicKind == OMPC_write) {
5304 } ErrorFound = NoError;
5305 SourceLocation ErrorLoc, NoteLoc;
5306 SourceRange ErrorRange, NoteRange;
5307 // If clause is write:
5309 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5311 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5312 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5313 X = AtomicBinOp->getLHS();
5314 E = AtomicBinOp->getRHS();
5315 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5316 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5317 if (!X->isLValue()) {
5318 ErrorFound = NotAnLValue;
5319 ErrorLoc = AtomicBinOp->getExprLoc();
5320 ErrorRange = AtomicBinOp->getSourceRange();
5321 NoteLoc = X->getExprLoc();
5322 NoteRange = X->getSourceRange();
5324 } else if (!X->isInstantiationDependent() ||
5325 !E->isInstantiationDependent()) {
5326 auto NotScalarExpr =
5327 (X->isInstantiationDependent() || X->getType()->isScalarType())
5330 ErrorFound = NotAScalarType;
5331 ErrorLoc = AtomicBinOp->getExprLoc();
5332 ErrorRange = AtomicBinOp->getSourceRange();
5333 NoteLoc = NotScalarExpr->getExprLoc();
5334 NoteRange = NotScalarExpr->getSourceRange();
5336 } else if (!AtomicBody->isInstantiationDependent()) {
5337 ErrorFound = NotAnAssignmentOp;
5338 ErrorLoc = AtomicBody->getExprLoc();
5339 ErrorRange = AtomicBody->getSourceRange();
5340 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5341 : AtomicBody->getExprLoc();
5342 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5343 : AtomicBody->getSourceRange();
5346 ErrorFound = NotAnExpression;
5347 NoteLoc = ErrorLoc = Body->getLocStart();
5348 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5350 if (ErrorFound != NoError) {
5351 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5353 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5356 } else if (CurContext->isDependentContext())
5358 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
5359 // If clause is update:
5365 // x = x binop expr;
5366 // x = expr binop x;
5367 OpenMPAtomicUpdateChecker Checker(*this);
5368 if (Checker.checkStatement(
5369 Body, (AtomicKind == OMPC_update)
5370 ? diag::err_omp_atomic_update_not_expression_statement
5371 : diag::err_omp_atomic_not_expression_statement,
5372 diag::note_omp_atomic_update))
5374 if (!CurContext->isDependentContext()) {
5375 E = Checker.getExpr();
5377 UE = Checker.getUpdateExpr();
5378 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5380 } else if (AtomicKind == OMPC_capture) {
5383 NotACompoundStatement,
5384 NotTwoSubstatements,
5385 NotASpecificExpression,
5387 } ErrorFound = NoError;
5388 SourceLocation ErrorLoc, NoteLoc;
5389 SourceRange ErrorRange, NoteRange;
5390 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5391 // If clause is a capture:
5396 // v = x binop= expr;
5397 // v = x = x binop expr;
5398 // v = x = expr binop x;
5400 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5401 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5402 V = AtomicBinOp->getLHS();
5403 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5404 OpenMPAtomicUpdateChecker Checker(*this);
5405 if (Checker.checkStatement(
5406 Body, diag::err_omp_atomic_capture_not_expression_statement,
5407 diag::note_omp_atomic_update))
5409 E = Checker.getExpr();
5411 UE = Checker.getUpdateExpr();
5412 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5413 IsPostfixUpdate = Checker.isPostfixUpdate();
5414 } else if (!AtomicBody->isInstantiationDependent()) {
5415 ErrorLoc = AtomicBody->getExprLoc();
5416 ErrorRange = AtomicBody->getSourceRange();
5417 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5418 : AtomicBody->getExprLoc();
5419 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5420 : AtomicBody->getSourceRange();
5421 ErrorFound = NotAnAssignmentOp;
5423 if (ErrorFound != NoError) {
5424 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5426 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5428 } else if (CurContext->isDependentContext()) {
5429 UE = V = E = X = nullptr;
5432 // If clause is a capture:
5433 // { v = x; x = expr; }
5438 // { v = x; x binop= expr; }
5439 // { v = x; x = x binop expr; }
5440 // { v = x; x = expr binop x; }
5445 // { x binop= expr; v = x; }
5446 // { x = x binop expr; v = x; }
5447 // { x = expr binop x; v = x; }
5448 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5449 // Check that this is { expr1; expr2; }
5450 if (CS->size() == 2) {
5451 auto *First = CS->body_front();
5452 auto *Second = CS->body_back();
5453 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5454 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5455 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5456 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5457 // Need to find what subexpression is 'v' and what is 'x'.
5458 OpenMPAtomicUpdateChecker Checker(*this);
5459 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5460 BinaryOperator *BinOp = nullptr;
5461 if (IsUpdateExprFound) {
5462 BinOp = dyn_cast<BinaryOperator>(First);
5463 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5465 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5470 // { v = x; x binop= expr; }
5471 // { v = x; x = x binop expr; }
5472 // { v = x; x = expr binop x; }
5473 // Check that the first expression has form v = x.
5474 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5475 llvm::FoldingSetNodeID XId, PossibleXId;
5476 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5477 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5478 IsUpdateExprFound = XId == PossibleXId;
5479 if (IsUpdateExprFound) {
5480 V = BinOp->getLHS();
5482 E = Checker.getExpr();
5483 UE = Checker.getUpdateExpr();
5484 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5485 IsPostfixUpdate = true;
5488 if (!IsUpdateExprFound) {
5489 IsUpdateExprFound = !Checker.checkStatement(First);
5491 if (IsUpdateExprFound) {
5492 BinOp = dyn_cast<BinaryOperator>(Second);
5493 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5495 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5500 // { x binop= expr; v = x; }
5501 // { x = x binop expr; v = x; }
5502 // { x = expr binop x; v = x; }
5503 // Check that the second expression has form v = x.
5504 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5505 llvm::FoldingSetNodeID XId, PossibleXId;
5506 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5507 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5508 IsUpdateExprFound = XId == PossibleXId;
5509 if (IsUpdateExprFound) {
5510 V = BinOp->getLHS();
5512 E = Checker.getExpr();
5513 UE = Checker.getUpdateExpr();
5514 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5515 IsPostfixUpdate = false;
5519 if (!IsUpdateExprFound) {
5520 // { v = x; x = expr; }
5521 auto *FirstExpr = dyn_cast<Expr>(First);
5522 auto *SecondExpr = dyn_cast<Expr>(Second);
5523 if (!FirstExpr || !SecondExpr ||
5524 !(FirstExpr->isInstantiationDependent() ||
5525 SecondExpr->isInstantiationDependent())) {
5526 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5527 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
5528 ErrorFound = NotAnAssignmentOp;
5529 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5530 : First->getLocStart();
5531 NoteRange = ErrorRange = FirstBinOp
5532 ? FirstBinOp->getSourceRange()
5533 : SourceRange(ErrorLoc, ErrorLoc);
5535 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5536 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5537 ErrorFound = NotAnAssignmentOp;
5538 NoteLoc = ErrorLoc = SecondBinOp
5539 ? SecondBinOp->getOperatorLoc()
5540 : Second->getLocStart();
5541 NoteRange = ErrorRange =
5542 SecondBinOp ? SecondBinOp->getSourceRange()
5543 : SourceRange(ErrorLoc, ErrorLoc);
5545 auto *PossibleXRHSInFirst =
5546 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5547 auto *PossibleXLHSInSecond =
5548 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5549 llvm::FoldingSetNodeID X1Id, X2Id;
5550 PossibleXRHSInFirst->Profile(X1Id, Context,
5551 /*Canonical=*/true);
5552 PossibleXLHSInSecond->Profile(X2Id, Context,
5553 /*Canonical=*/true);
5554 IsUpdateExprFound = X1Id == X2Id;
5555 if (IsUpdateExprFound) {
5556 V = FirstBinOp->getLHS();
5557 X = SecondBinOp->getLHS();
5558 E = SecondBinOp->getRHS();
5560 IsXLHSInRHSPart = false;
5561 IsPostfixUpdate = true;
5563 ErrorFound = NotASpecificExpression;
5564 ErrorLoc = FirstBinOp->getExprLoc();
5565 ErrorRange = FirstBinOp->getSourceRange();
5566 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5567 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5574 NoteLoc = ErrorLoc = Body->getLocStart();
5575 NoteRange = ErrorRange =
5576 SourceRange(Body->getLocStart(), Body->getLocStart());
5577 ErrorFound = NotTwoSubstatements;
5580 NoteLoc = ErrorLoc = Body->getLocStart();
5581 NoteRange = ErrorRange =
5582 SourceRange(Body->getLocStart(), Body->getLocStart());
5583 ErrorFound = NotACompoundStatement;
5585 if (ErrorFound != NoError) {
5586 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5588 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5590 } else if (CurContext->isDependentContext()) {
5591 UE = V = E = X = nullptr;
5596 getCurFunction()->setHasBranchProtectedScope();
5598 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5599 X, V, E, UE, IsXLHSInRHSPart,
5603 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5605 SourceLocation StartLoc,
5606 SourceLocation EndLoc) {
5610 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5611 // 1.2.2 OpenMP Language Terminology
5612 // Structured block - An executable statement with a single entry at the
5613 // top and a single exit at the bottom.
5614 // The point of exit cannot be a branch out of the structured block.
5615 // longjmp() and throw() must not violate the entry/exit criteria.
5616 CS->getCapturedDecl()->setNothrow();
5618 // OpenMP [2.16, Nesting of Regions]
5619 // If specified, a teams construct must be contained within a target
5620 // construct. That target construct must contain no statements or directives
5621 // outside of the teams construct.
5622 if (DSAStack->hasInnerTeamsRegion()) {
5623 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5624 bool OMPTeamsFound = true;
5625 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5626 auto I = CS->body_begin();
5627 while (I != CS->body_end()) {
5628 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
5629 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5630 OMPTeamsFound = false;
5635 assert(I != CS->body_end() && "Not found statement");
5638 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5639 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
5641 if (!OMPTeamsFound) {
5642 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5643 Diag(DSAStack->getInnerTeamsRegionLoc(),
5644 diag::note_omp_nested_teams_construct_here);
5645 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5646 << isa<OMPExecutableDirective>(S);
5651 getCurFunction()->setHasBranchProtectedScope();
5653 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5657 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5658 Stmt *AStmt, SourceLocation StartLoc,
5659 SourceLocation EndLoc) {
5663 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5664 // 1.2.2 OpenMP Language Terminology
5665 // Structured block - An executable statement with a single entry at the
5666 // top and a single exit at the bottom.
5667 // The point of exit cannot be a branch out of the structured block.
5668 // longjmp() and throw() must not violate the entry/exit criteria.
5669 CS->getCapturedDecl()->setNothrow();
5671 getCurFunction()->setHasBranchProtectedScope();
5673 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5677 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5678 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5679 SourceLocation EndLoc,
5680 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5684 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5685 // 1.2.2 OpenMP Language Terminology
5686 // Structured block - An executable statement with a single entry at the
5687 // top and a single exit at the bottom.
5688 // The point of exit cannot be a branch out of the structured block.
5689 // longjmp() and throw() must not violate the entry/exit criteria.
5690 CS->getCapturedDecl()->setNothrow();
5692 OMPLoopDirective::HelperExprs B;
5693 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5694 // define the nested loops number.
5695 unsigned NestedLoopCount =
5696 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5697 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5698 VarsWithImplicitDSA, B);
5699 if (NestedLoopCount == 0)
5702 assert((CurContext->isDependentContext() || B.builtAll()) &&
5703 "omp target parallel for loop exprs were not built");
5705 if (!CurContext->isDependentContext()) {
5706 // Finalize the clauses that need pre-built expressions for CodeGen.
5707 for (auto C : Clauses) {
5708 if (auto *LC = dyn_cast<OMPLinearClause>(C))
5709 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5710 B.NumIterations, *this, CurScope,
5716 getCurFunction()->setHasBranchProtectedScope();
5717 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5718 NestedLoopCount, Clauses, AStmt,
5719 B, DSAStack->isCancelRegion());
5722 /// \brief Check for existence of a map clause in the list of clauses.
5723 static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5724 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5726 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5734 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5736 SourceLocation StartLoc,
5737 SourceLocation EndLoc) {
5741 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5743 // OpenMP [2.10.1, Restrictions, p. 97]
5744 // At least one map clause must appear on the directive.
5745 if (!HasMapClause(Clauses)) {
5746 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5747 << getOpenMPDirectiveName(OMPD_target_data);
5751 getCurFunction()->setHasBranchProtectedScope();
5753 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5758 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5759 SourceLocation StartLoc,
5760 SourceLocation EndLoc) {
5761 // OpenMP [2.10.2, Restrictions, p. 99]
5762 // At least one map clause must appear on the directive.
5763 if (!HasMapClause(Clauses)) {
5764 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5765 << getOpenMPDirectiveName(OMPD_target_enter_data);
5769 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5774 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5775 SourceLocation StartLoc,
5776 SourceLocation EndLoc) {
5777 // OpenMP [2.10.3, Restrictions, p. 102]
5778 // At least one map clause must appear on the directive.
5779 if (!HasMapClause(Clauses)) {
5780 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5781 << getOpenMPDirectiveName(OMPD_target_exit_data);
5785 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5788 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5789 SourceLocation StartLoc,
5790 SourceLocation EndLoc) {
5791 bool seenMotionClause = false;
5792 for (auto *C : Clauses) {
5793 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
5794 seenMotionClause = true;
5796 if (!seenMotionClause) {
5797 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5800 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5803 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5804 Stmt *AStmt, SourceLocation StartLoc,
5805 SourceLocation EndLoc) {
5809 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5810 // 1.2.2 OpenMP Language Terminology
5811 // Structured block - An executable statement with a single entry at the
5812 // top and a single exit at the bottom.
5813 // The point of exit cannot be a branch out of the structured block.
5814 // longjmp() and throw() must not violate the entry/exit criteria.
5815 CS->getCapturedDecl()->setNothrow();
5817 getCurFunction()->setHasBranchProtectedScope();
5819 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5823 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5824 SourceLocation EndLoc,
5825 OpenMPDirectiveKind CancelRegion) {
5826 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5827 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5828 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5829 << getOpenMPDirectiveName(CancelRegion);
5832 if (DSAStack->isParentNowaitRegion()) {
5833 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5836 if (DSAStack->isParentOrderedRegion()) {
5837 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5840 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5844 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5845 SourceLocation StartLoc,
5846 SourceLocation EndLoc,
5847 OpenMPDirectiveKind CancelRegion) {
5848 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5849 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5850 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5851 << getOpenMPDirectiveName(CancelRegion);
5854 if (DSAStack->isParentNowaitRegion()) {
5855 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5858 if (DSAStack->isParentOrderedRegion()) {
5859 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5862 DSAStack->setParentCancelRegion(/*Cancel=*/true);
5863 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5867 static bool checkGrainsizeNumTasksClauses(Sema &S,
5868 ArrayRef<OMPClause *> Clauses) {
5869 OMPClause *PrevClause = nullptr;
5870 bool ErrorFound = false;
5871 for (auto *C : Clauses) {
5872 if (C->getClauseKind() == OMPC_grainsize ||
5873 C->getClauseKind() == OMPC_num_tasks) {
5876 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5877 S.Diag(C->getLocStart(),
5878 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5879 << getOpenMPClauseName(C->getClauseKind())
5880 << getOpenMPClauseName(PrevClause->getClauseKind());
5881 S.Diag(PrevClause->getLocStart(),
5882 diag::note_omp_previous_grainsize_num_tasks)
5883 << getOpenMPClauseName(PrevClause->getClauseKind());
5891 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5892 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5893 SourceLocation EndLoc,
5894 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5898 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5899 OMPLoopDirective::HelperExprs B;
5900 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5901 // define the nested loops number.
5902 unsigned NestedLoopCount =
5903 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
5904 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5905 VarsWithImplicitDSA, B);
5906 if (NestedLoopCount == 0)
5909 assert((CurContext->isDependentContext() || B.builtAll()) &&
5910 "omp for loop exprs were not built");
5912 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5913 // The grainsize clause and num_tasks clause are mutually exclusive and may
5914 // not appear on the same taskloop directive.
5915 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5918 getCurFunction()->setHasBranchProtectedScope();
5919 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5920 NestedLoopCount, Clauses, AStmt, B);
5923 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5924 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5925 SourceLocation EndLoc,
5926 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5930 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5931 OMPLoopDirective::HelperExprs B;
5932 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5933 // define the nested loops number.
5934 unsigned NestedLoopCount =
5935 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5936 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5937 VarsWithImplicitDSA, B);
5938 if (NestedLoopCount == 0)
5941 assert((CurContext->isDependentContext() || B.builtAll()) &&
5942 "omp for loop exprs were not built");
5944 if (!CurContext->isDependentContext()) {
5945 // Finalize the clauses that need pre-built expressions for CodeGen.
5946 for (auto C : Clauses) {
5947 if (auto *LC = dyn_cast<OMPLinearClause>(C))
5948 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5949 B.NumIterations, *this, CurScope,
5955 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5956 // The grainsize clause and num_tasks clause are mutually exclusive and may
5957 // not appear on the same taskloop directive.
5958 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5961 getCurFunction()->setHasBranchProtectedScope();
5962 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5963 NestedLoopCount, Clauses, AStmt, B);
5966 StmtResult Sema::ActOnOpenMPDistributeDirective(
5967 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5968 SourceLocation EndLoc,
5969 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5973 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5974 OMPLoopDirective::HelperExprs B;
5975 // In presence of clause 'collapse' with number of loops, it will
5976 // define the nested loops number.
5977 unsigned NestedLoopCount =
5978 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5979 nullptr /*ordered not a clause on distribute*/, AStmt,
5980 *this, *DSAStack, VarsWithImplicitDSA, B);
5981 if (NestedLoopCount == 0)
5984 assert((CurContext->isDependentContext() || B.builtAll()) &&
5985 "omp for loop exprs were not built");
5987 getCurFunction()->setHasBranchProtectedScope();
5988 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5989 NestedLoopCount, Clauses, AStmt, B);
5992 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
5993 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5994 SourceLocation EndLoc,
5995 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5999 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6000 // 1.2.2 OpenMP Language Terminology
6001 // Structured block - An executable statement with a single entry at the
6002 // top and a single exit at the bottom.
6003 // The point of exit cannot be a branch out of the structured block.
6004 // longjmp() and throw() must not violate the entry/exit criteria.
6005 CS->getCapturedDecl()->setNothrow();
6007 OMPLoopDirective::HelperExprs B;
6008 // In presence of clause 'collapse' with number of loops, it will
6009 // define the nested loops number.
6010 unsigned NestedLoopCount = CheckOpenMPLoop(
6011 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6012 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6013 VarsWithImplicitDSA, B);
6014 if (NestedLoopCount == 0)
6017 assert((CurContext->isDependentContext() || B.builtAll()) &&
6018 "omp for loop exprs were not built");
6020 getCurFunction()->setHasBranchProtectedScope();
6021 return OMPDistributeParallelForDirective::Create(
6022 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6025 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6026 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6027 SourceLocation EndLoc,
6028 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6032 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6033 // 1.2.2 OpenMP Language Terminology
6034 // Structured block - An executable statement with a single entry at the
6035 // top and a single exit at the bottom.
6036 // The point of exit cannot be a branch out of the structured block.
6037 // longjmp() and throw() must not violate the entry/exit criteria.
6038 CS->getCapturedDecl()->setNothrow();
6040 OMPLoopDirective::HelperExprs B;
6041 // In presence of clause 'collapse' with number of loops, it will
6042 // define the nested loops number.
6043 unsigned NestedLoopCount = CheckOpenMPLoop(
6044 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6045 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6046 VarsWithImplicitDSA, B);
6047 if (NestedLoopCount == 0)
6050 assert((CurContext->isDependentContext() || B.builtAll()) &&
6051 "omp for loop exprs were not built");
6053 if (checkSimdlenSafelenSpecified(*this, Clauses))
6056 getCurFunction()->setHasBranchProtectedScope();
6057 return OMPDistributeParallelForSimdDirective::Create(
6058 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6061 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6062 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6063 SourceLocation EndLoc,
6064 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6068 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6069 // 1.2.2 OpenMP Language Terminology
6070 // Structured block - An executable statement with a single entry at the
6071 // top and a single exit at the bottom.
6072 // The point of exit cannot be a branch out of the structured block.
6073 // longjmp() and throw() must not violate the entry/exit criteria.
6074 CS->getCapturedDecl()->setNothrow();
6076 OMPLoopDirective::HelperExprs B;
6077 // In presence of clause 'collapse' with number of loops, it will
6078 // define the nested loops number.
6079 unsigned NestedLoopCount =
6080 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6081 nullptr /*ordered not a clause on distribute*/, AStmt,
6082 *this, *DSAStack, VarsWithImplicitDSA, B);
6083 if (NestedLoopCount == 0)
6086 assert((CurContext->isDependentContext() || B.builtAll()) &&
6087 "omp for loop exprs were not built");
6089 if (checkSimdlenSafelenSpecified(*this, Clauses))
6092 getCurFunction()->setHasBranchProtectedScope();
6093 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6094 NestedLoopCount, Clauses, AStmt, B);
6097 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6098 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6099 SourceLocation EndLoc,
6100 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6104 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6105 // 1.2.2 OpenMP Language Terminology
6106 // Structured block - An executable statement with a single entry at the
6107 // top and a single exit at the bottom.
6108 // The point of exit cannot be a branch out of the structured block.
6109 // longjmp() and throw() must not violate the entry/exit criteria.
6110 CS->getCapturedDecl()->setNothrow();
6112 OMPLoopDirective::HelperExprs B;
6113 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6114 // define the nested loops number.
6115 unsigned NestedLoopCount = CheckOpenMPLoop(
6116 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6117 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6118 VarsWithImplicitDSA, B);
6119 if (NestedLoopCount == 0)
6122 assert((CurContext->isDependentContext() || B.builtAll()) &&
6123 "omp target parallel for simd loop exprs were not built");
6125 if (!CurContext->isDependentContext()) {
6126 // Finalize the clauses that need pre-built expressions for CodeGen.
6127 for (auto C : Clauses) {
6128 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6129 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6130 B.NumIterations, *this, CurScope,
6135 if (checkSimdlenSafelenSpecified(*this, Clauses))
6138 getCurFunction()->setHasBranchProtectedScope();
6139 return OMPTargetParallelForSimdDirective::Create(
6140 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6143 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6144 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6145 SourceLocation EndLoc,
6146 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6150 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6151 // 1.2.2 OpenMP Language Terminology
6152 // Structured block - An executable statement with a single entry at the
6153 // top and a single exit at the bottom.
6154 // The point of exit cannot be a branch out of the structured block.
6155 // longjmp() and throw() must not violate the entry/exit criteria.
6156 CS->getCapturedDecl()->setNothrow();
6158 OMPLoopDirective::HelperExprs B;
6159 // In presence of clause 'collapse' with number of loops, it will define the
6160 // nested loops number.
6161 unsigned NestedLoopCount =
6162 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6163 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6164 VarsWithImplicitDSA, B);
6165 if (NestedLoopCount == 0)
6168 assert((CurContext->isDependentContext() || B.builtAll()) &&
6169 "omp target simd loop exprs were not built");
6171 if (!CurContext->isDependentContext()) {
6172 // Finalize the clauses that need pre-built expressions for CodeGen.
6173 for (auto C : Clauses) {
6174 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6175 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6176 B.NumIterations, *this, CurScope,
6182 if (checkSimdlenSafelenSpecified(*this, Clauses))
6185 getCurFunction()->setHasBranchProtectedScope();
6186 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6187 NestedLoopCount, Clauses, AStmt, B);
6190 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6191 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6192 SourceLocation EndLoc,
6193 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6197 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6198 // 1.2.2 OpenMP Language Terminology
6199 // Structured block - An executable statement with a single entry at the
6200 // top and a single exit at the bottom.
6201 // The point of exit cannot be a branch out of the structured block.
6202 // longjmp() and throw() must not violate the entry/exit criteria.
6203 CS->getCapturedDecl()->setNothrow();
6205 OMPLoopDirective::HelperExprs B;
6206 // In presence of clause 'collapse' with number of loops, it will
6207 // define the nested loops number.
6208 unsigned NestedLoopCount =
6209 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6210 nullptr /*ordered not a clause on distribute*/, AStmt,
6211 *this, *DSAStack, VarsWithImplicitDSA, B);
6212 if (NestedLoopCount == 0)
6215 assert((CurContext->isDependentContext() || B.builtAll()) &&
6216 "omp teams distribute loop exprs were not built");
6218 getCurFunction()->setHasBranchProtectedScope();
6219 return OMPTeamsDistributeDirective::Create(
6220 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6223 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6224 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6225 SourceLocation EndLoc,
6226 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6230 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6231 // 1.2.2 OpenMP Language Terminology
6232 // Structured block - An executable statement with a single entry at the
6233 // top and a single exit at the bottom.
6234 // The point of exit cannot be a branch out of the structured block.
6235 // longjmp() and throw() must not violate the entry/exit criteria.
6236 CS->getCapturedDecl()->setNothrow();
6238 OMPLoopDirective::HelperExprs B;
6239 // In presence of clause 'collapse' with number of loops, it will
6240 // define the nested loops number.
6241 unsigned NestedLoopCount = CheckOpenMPLoop(
6242 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6243 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6244 VarsWithImplicitDSA, B);
6246 if (NestedLoopCount == 0)
6249 assert((CurContext->isDependentContext() || B.builtAll()) &&
6250 "omp teams distribute simd loop exprs were not built");
6252 if (!CurContext->isDependentContext()) {
6253 // Finalize the clauses that need pre-built expressions for CodeGen.
6254 for (auto C : Clauses) {
6255 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6256 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6257 B.NumIterations, *this, CurScope,
6263 if (checkSimdlenSafelenSpecified(*this, Clauses))
6266 getCurFunction()->setHasBranchProtectedScope();
6267 return OMPTeamsDistributeSimdDirective::Create(
6268 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6271 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6272 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6273 SourceLocation EndLoc,
6274 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6278 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6279 // 1.2.2 OpenMP Language Terminology
6280 // Structured block - An executable statement with a single entry at the
6281 // top and a single exit at the bottom.
6282 // The point of exit cannot be a branch out of the structured block.
6283 // longjmp() and throw() must not violate the entry/exit criteria.
6284 CS->getCapturedDecl()->setNothrow();
6286 OMPLoopDirective::HelperExprs B;
6287 // In presence of clause 'collapse' with number of loops, it will
6288 // define the nested loops number.
6289 auto NestedLoopCount = CheckOpenMPLoop(
6290 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6291 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6292 VarsWithImplicitDSA, B);
6294 if (NestedLoopCount == 0)
6297 assert((CurContext->isDependentContext() || B.builtAll()) &&
6298 "omp for loop exprs were not built");
6300 if (!CurContext->isDependentContext()) {
6301 // Finalize the clauses that need pre-built expressions for CodeGen.
6302 for (auto C : Clauses) {
6303 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6304 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6305 B.NumIterations, *this, CurScope,
6311 if (checkSimdlenSafelenSpecified(*this, Clauses))
6314 getCurFunction()->setHasBranchProtectedScope();
6315 return OMPTeamsDistributeParallelForSimdDirective::Create(
6316 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6319 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6320 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6321 SourceLocation EndLoc,
6322 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6326 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6327 // 1.2.2 OpenMP Language Terminology
6328 // Structured block - An executable statement with a single entry at the
6329 // top and a single exit at the bottom.
6330 // The point of exit cannot be a branch out of the structured block.
6331 // longjmp() and throw() must not violate the entry/exit criteria.
6332 CS->getCapturedDecl()->setNothrow();
6334 OMPLoopDirective::HelperExprs B;
6335 // In presence of clause 'collapse' with number of loops, it will
6336 // define the nested loops number.
6337 unsigned NestedLoopCount = CheckOpenMPLoop(
6338 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6339 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6340 VarsWithImplicitDSA, B);
6342 if (NestedLoopCount == 0)
6345 assert((CurContext->isDependentContext() || B.builtAll()) &&
6346 "omp for loop exprs were not built");
6348 if (!CurContext->isDependentContext()) {
6349 // Finalize the clauses that need pre-built expressions for CodeGen.
6350 for (auto C : Clauses) {
6351 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6352 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6353 B.NumIterations, *this, CurScope,
6359 getCurFunction()->setHasBranchProtectedScope();
6360 return OMPTeamsDistributeParallelForDirective::Create(
6361 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6364 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6366 SourceLocation StartLoc,
6367 SourceLocation EndLoc) {
6371 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6372 // 1.2.2 OpenMP Language Terminology
6373 // Structured block - An executable statement with a single entry at the
6374 // top and a single exit at the bottom.
6375 // The point of exit cannot be a branch out of the structured block.
6376 // longjmp() and throw() must not violate the entry/exit criteria.
6377 CS->getCapturedDecl()->setNothrow();
6379 getCurFunction()->setHasBranchProtectedScope();
6381 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6385 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6386 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6387 SourceLocation EndLoc,
6388 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6392 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6393 // 1.2.2 OpenMP Language Terminology
6394 // Structured block - An executable statement with a single entry at the
6395 // top and a single exit at the bottom.
6396 // The point of exit cannot be a branch out of the structured block.
6397 // longjmp() and throw() must not violate the entry/exit criteria.
6398 CS->getCapturedDecl()->setNothrow();
6400 OMPLoopDirective::HelperExprs B;
6401 // In presence of clause 'collapse' with number of loops, it will
6402 // define the nested loops number.
6403 auto NestedLoopCount = CheckOpenMPLoop(
6404 OMPD_target_teams_distribute,
6405 getCollapseNumberExpr(Clauses),
6406 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6407 VarsWithImplicitDSA, B);
6408 if (NestedLoopCount == 0)
6411 assert((CurContext->isDependentContext() || B.builtAll()) &&
6412 "omp target teams distribute loop exprs were not built");
6414 getCurFunction()->setHasBranchProtectedScope();
6415 return OMPTargetTeamsDistributeDirective::Create(
6416 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6419 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6420 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6421 SourceLocation EndLoc,
6422 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6426 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6427 // 1.2.2 OpenMP Language Terminology
6428 // Structured block - An executable statement with a single entry at the
6429 // top and a single exit at the bottom.
6430 // The point of exit cannot be a branch out of the structured block.
6431 // longjmp() and throw() must not violate the entry/exit criteria.
6432 CS->getCapturedDecl()->setNothrow();
6434 OMPLoopDirective::HelperExprs B;
6435 // In presence of clause 'collapse' with number of loops, it will
6436 // define the nested loops number.
6437 auto NestedLoopCount = CheckOpenMPLoop(
6438 OMPD_target_teams_distribute_parallel_for,
6439 getCollapseNumberExpr(Clauses),
6440 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6441 VarsWithImplicitDSA, B);
6442 if (NestedLoopCount == 0)
6445 assert((CurContext->isDependentContext() || B.builtAll()) &&
6446 "omp target teams distribute parallel for loop exprs were not built");
6448 if (!CurContext->isDependentContext()) {
6449 // Finalize the clauses that need pre-built expressions for CodeGen.
6450 for (auto C : Clauses) {
6451 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6452 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6453 B.NumIterations, *this, CurScope,
6459 getCurFunction()->setHasBranchProtectedScope();
6460 return OMPTargetTeamsDistributeParallelForDirective::Create(
6461 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6464 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6465 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6466 SourceLocation EndLoc,
6467 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6471 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6472 // 1.2.2 OpenMP Language Terminology
6473 // Structured block - An executable statement with a single entry at the
6474 // top and a single exit at the bottom.
6475 // The point of exit cannot be a branch out of the structured block.
6476 // longjmp() and throw() must not violate the entry/exit criteria.
6477 CS->getCapturedDecl()->setNothrow();
6479 OMPLoopDirective::HelperExprs B;
6480 // In presence of clause 'collapse' with number of loops, it will
6481 // define the nested loops number.
6482 auto NestedLoopCount = CheckOpenMPLoop(
6483 OMPD_target_teams_distribute_parallel_for_simd,
6484 getCollapseNumberExpr(Clauses),
6485 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6486 VarsWithImplicitDSA, B);
6487 if (NestedLoopCount == 0)
6490 assert((CurContext->isDependentContext() || B.builtAll()) &&
6491 "omp target teams distribute parallel for simd loop exprs were not "
6494 if (!CurContext->isDependentContext()) {
6495 // Finalize the clauses that need pre-built expressions for CodeGen.
6496 for (auto C : Clauses) {
6497 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6498 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6499 B.NumIterations, *this, CurScope,
6505 getCurFunction()->setHasBranchProtectedScope();
6506 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6507 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6510 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6511 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6512 SourceLocation EndLoc,
6513 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6517 auto *CS = cast<CapturedStmt>(AStmt);
6518 // 1.2.2 OpenMP Language Terminology
6519 // Structured block - An executable statement with a single entry at the
6520 // top and a single exit at the bottom.
6521 // The point of exit cannot be a branch out of the structured block.
6522 // longjmp() and throw() must not violate the entry/exit criteria.
6523 CS->getCapturedDecl()->setNothrow();
6525 OMPLoopDirective::HelperExprs B;
6526 // In presence of clause 'collapse' with number of loops, it will
6527 // define the nested loops number.
6528 auto NestedLoopCount = CheckOpenMPLoop(
6529 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6530 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6531 VarsWithImplicitDSA, B);
6532 if (NestedLoopCount == 0)
6535 assert((CurContext->isDependentContext() || B.builtAll()) &&
6536 "omp target teams distribute simd loop exprs were not built");
6538 getCurFunction()->setHasBranchProtectedScope();
6539 return OMPTargetTeamsDistributeSimdDirective::Create(
6540 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6543 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
6544 SourceLocation StartLoc,
6545 SourceLocation LParenLoc,
6546 SourceLocation EndLoc) {
6547 OMPClause *Res = nullptr;
6550 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6552 case OMPC_num_threads:
6553 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6556 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6559 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6562 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6565 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6568 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6570 case OMPC_num_teams:
6571 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6573 case OMPC_thread_limit:
6574 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6577 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6579 case OMPC_grainsize:
6580 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6582 case OMPC_num_tasks:
6583 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6586 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6590 case OMPC_proc_bind:
6593 case OMPC_firstprivate:
6594 case OMPC_lastprivate:
6596 case OMPC_reduction:
6600 case OMPC_copyprivate:
6603 case OMPC_mergeable:
6604 case OMPC_threadprivate:
6616 case OMPC_dist_schedule:
6617 case OMPC_defaultmap:
6622 case OMPC_use_device_ptr:
6623 case OMPC_is_device_ptr:
6624 llvm_unreachable("Clause is not allowed.");
6629 // An OpenMP directive such as 'target parallel' has two captured regions:
6630 // for the 'target' and 'parallel' respectively. This function returns
6631 // the region in which to capture expressions associated with a clause.
6632 // A return value of OMPD_unknown signifies that the expression should not
6634 static OpenMPDirectiveKind
6635 getOpenMPCaptureRegionForClause(OpenMPDirectiveKind DKind,
6636 OpenMPClauseKind CKind,
6637 OpenMPDirectiveKind NameModifier) {
6638 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
6643 case OMPD_target_parallel:
6644 // If this clause applies to the nested 'parallel' region, capture within
6645 // the 'target' region, otherwise do not capture.
6646 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
6647 CaptureRegion = OMPD_target;
6651 case OMPD_parallel_sections:
6652 case OMPD_parallel_for:
6653 case OMPD_parallel_for_simd:
6655 case OMPD_target_simd:
6656 case OMPD_target_parallel_for:
6657 case OMPD_target_parallel_for_simd:
6658 case OMPD_target_teams:
6659 case OMPD_target_teams_distribute:
6660 case OMPD_target_teams_distribute_simd:
6661 case OMPD_target_teams_distribute_parallel_for:
6662 case OMPD_target_teams_distribute_parallel_for_simd:
6663 case OMPD_teams_distribute_parallel_for:
6664 case OMPD_teams_distribute_parallel_for_simd:
6665 case OMPD_distribute_parallel_for:
6666 case OMPD_distribute_parallel_for_simd:
6669 case OMPD_taskloop_simd:
6670 case OMPD_target_data:
6671 case OMPD_target_enter_data:
6672 case OMPD_target_exit_data:
6673 case OMPD_target_update:
6674 // Do not capture if-clause expressions.
6676 case OMPD_threadprivate:
6677 case OMPD_taskyield:
6680 case OMPD_cancellation_point:
6682 case OMPD_declare_reduction:
6683 case OMPD_declare_simd:
6684 case OMPD_declare_target:
6685 case OMPD_end_declare_target:
6695 case OMPD_taskgroup:
6696 case OMPD_distribute:
6699 case OMPD_distribute_simd:
6700 case OMPD_teams_distribute:
6701 case OMPD_teams_distribute_simd:
6702 llvm_unreachable("Unexpected OpenMP directive with if-clause");
6704 llvm_unreachable("Unknown OpenMP directive");
6708 case OMPC_dist_schedule:
6709 case OMPC_firstprivate:
6710 case OMPC_lastprivate:
6711 case OMPC_reduction:
6714 case OMPC_proc_bind:
6716 case OMPC_num_threads:
6724 case OMPC_copyprivate:
6728 case OMPC_mergeable:
6729 case OMPC_threadprivate:
6741 case OMPC_num_teams:
6742 case OMPC_thread_limit:
6744 case OMPC_grainsize:
6746 case OMPC_num_tasks:
6748 case OMPC_defaultmap:
6753 case OMPC_use_device_ptr:
6754 case OMPC_is_device_ptr:
6755 llvm_unreachable("Unexpected OpenMP clause.");
6757 return CaptureRegion;
6760 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6761 Expr *Condition, SourceLocation StartLoc,
6762 SourceLocation LParenLoc,
6763 SourceLocation NameModifierLoc,
6764 SourceLocation ColonLoc,
6765 SourceLocation EndLoc) {
6766 Expr *ValExpr = Condition;
6767 Stmt *HelperValStmt = nullptr;
6768 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
6769 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6770 !Condition->isInstantiationDependent() &&
6771 !Condition->containsUnexpandedParameterPack()) {
6772 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
6773 if (Val.isInvalid())
6776 ValExpr = MakeFullExpr(Val.get()).get();
6778 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6780 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
6781 if (CaptureRegion != OMPD_unknown) {
6782 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
6783 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
6784 HelperValStmt = buildPreInits(Context, Captures);
6788 return new (Context)
6789 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
6790 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
6793 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6794 SourceLocation StartLoc,
6795 SourceLocation LParenLoc,
6796 SourceLocation EndLoc) {
6797 Expr *ValExpr = Condition;
6798 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6799 !Condition->isInstantiationDependent() &&
6800 !Condition->containsUnexpandedParameterPack()) {
6801 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
6802 if (Val.isInvalid())
6805 ValExpr = MakeFullExpr(Val.get()).get();
6808 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6810 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6815 class IntConvertDiagnoser : public ICEConvertDiagnoser {
6817 IntConvertDiagnoser()
6818 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
6819 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6820 QualType T) override {
6821 return S.Diag(Loc, diag::err_omp_not_integral) << T;
6823 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6824 QualType T) override {
6825 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6827 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6829 QualType ConvTy) override {
6830 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6832 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6833 QualType ConvTy) override {
6834 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
6835 << ConvTy->isEnumeralType() << ConvTy;
6837 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6838 QualType T) override {
6839 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6841 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6842 QualType ConvTy) override {
6843 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
6844 << ConvTy->isEnumeralType() << ConvTy;
6846 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6847 QualType) override {
6848 llvm_unreachable("conversion functions are permitted");
6851 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6854 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
6855 OpenMPClauseKind CKind,
6856 bool StrictlyPositive) {
6857 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6858 !ValExpr->isInstantiationDependent()) {
6859 SourceLocation Loc = ValExpr->getExprLoc();
6861 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6862 if (Value.isInvalid())
6865 ValExpr = Value.get();
6866 // The expression must evaluate to a non-negative integer value.
6867 llvm::APSInt Result;
6868 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
6869 Result.isSigned() &&
6870 !((!StrictlyPositive && Result.isNonNegative()) ||
6871 (StrictlyPositive && Result.isStrictlyPositive()))) {
6872 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
6873 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6874 << ValExpr->getSourceRange();
6881 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6882 SourceLocation StartLoc,
6883 SourceLocation LParenLoc,
6884 SourceLocation EndLoc) {
6885 Expr *ValExpr = NumThreads;
6887 // OpenMP [2.5, Restrictions]
6888 // The num_threads expression must evaluate to a positive integer value.
6889 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6890 /*StrictlyPositive=*/true))
6893 return new (Context)
6894 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6897 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
6898 OpenMPClauseKind CKind,
6899 bool StrictlyPositive) {
6902 if (E->isValueDependent() || E->isTypeDependent() ||
6903 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
6905 llvm::APSInt Result;
6906 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6907 if (ICE.isInvalid())
6909 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6910 (!StrictlyPositive && !Result.isNonNegative())) {
6911 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
6912 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6913 << E->getSourceRange();
6916 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6917 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6918 << E->getSourceRange();
6921 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6922 DSAStack->setAssociatedLoops(Result.getExtValue());
6923 else if (CKind == OMPC_ordered)
6924 DSAStack->setAssociatedLoops(Result.getExtValue());
6928 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
6929 SourceLocation LParenLoc,
6930 SourceLocation EndLoc) {
6931 // OpenMP [2.8.1, simd construct, Description]
6932 // The parameter of the safelen clause must be a constant
6933 // positive integer expression.
6934 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
6935 if (Safelen.isInvalid())
6937 return new (Context)
6938 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
6941 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
6942 SourceLocation LParenLoc,
6943 SourceLocation EndLoc) {
6944 // OpenMP [2.8.1, simd construct, Description]
6945 // The parameter of the simdlen clause must be a constant
6946 // positive integer expression.
6947 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
6948 if (Simdlen.isInvalid())
6950 return new (Context)
6951 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
6954 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6955 SourceLocation StartLoc,
6956 SourceLocation LParenLoc,
6957 SourceLocation EndLoc) {
6958 // OpenMP [2.7.1, loop construct, Description]
6959 // OpenMP [2.8.1, simd construct, Description]
6960 // OpenMP [2.9.6, distribute construct, Description]
6961 // The parameter of the collapse clause must be a constant
6962 // positive integer expression.
6963 ExprResult NumForLoopsResult =
6964 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6965 if (NumForLoopsResult.isInvalid())
6967 return new (Context)
6968 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
6971 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6972 SourceLocation EndLoc,
6973 SourceLocation LParenLoc,
6974 Expr *NumForLoops) {
6975 // OpenMP [2.7.1, loop construct, Description]
6976 // OpenMP [2.8.1, simd construct, Description]
6977 // OpenMP [2.9.6, distribute construct, Description]
6978 // The parameter of the ordered clause must be a constant
6979 // positive integer expression if any.
6980 if (NumForLoops && LParenLoc.isValid()) {
6981 ExprResult NumForLoopsResult =
6982 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
6983 if (NumForLoopsResult.isInvalid())
6985 NumForLoops = NumForLoopsResult.get();
6987 NumForLoops = nullptr;
6988 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
6989 return new (Context)
6990 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6993 OMPClause *Sema::ActOnOpenMPSimpleClause(
6994 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6995 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
6996 OMPClause *Res = nullptr;
7000 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7001 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
7003 case OMPC_proc_bind:
7004 Res = ActOnOpenMPProcBindClause(
7005 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7010 case OMPC_num_threads:
7016 case OMPC_firstprivate:
7017 case OMPC_lastprivate:
7019 case OMPC_reduction:
7023 case OMPC_copyprivate:
7027 case OMPC_mergeable:
7028 case OMPC_threadprivate:
7040 case OMPC_num_teams:
7041 case OMPC_thread_limit:
7043 case OMPC_grainsize:
7045 case OMPC_num_tasks:
7047 case OMPC_dist_schedule:
7048 case OMPC_defaultmap:
7053 case OMPC_use_device_ptr:
7054 case OMPC_is_device_ptr:
7055 llvm_unreachable("Clause is not allowed.");
7061 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7062 ArrayRef<unsigned> Exclude = llvm::None) {
7064 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7065 unsigned Skipped = Exclude.size();
7066 auto S = Exclude.begin(), E = Exclude.end();
7067 for (unsigned i = First; i < Last; ++i) {
7068 if (std::find(S, E, i) != E) {
7073 Values += getOpenMPSimpleClauseTypeName(K, i);
7075 if (i == Bound - Skipped)
7077 else if (i != Bound + 1 - Skipped)
7083 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7084 SourceLocation KindKwLoc,
7085 SourceLocation StartLoc,
7086 SourceLocation LParenLoc,
7087 SourceLocation EndLoc) {
7088 if (Kind == OMPC_DEFAULT_unknown) {
7089 static_assert(OMPC_DEFAULT_unknown > 0,
7090 "OMPC_DEFAULT_unknown not greater than 0");
7091 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
7092 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7093 /*Last=*/OMPC_DEFAULT_unknown)
7094 << getOpenMPClauseName(OMPC_default);
7098 case OMPC_DEFAULT_none:
7099 DSAStack->setDefaultDSANone(KindKwLoc);
7101 case OMPC_DEFAULT_shared:
7102 DSAStack->setDefaultDSAShared(KindKwLoc);
7104 case OMPC_DEFAULT_unknown:
7105 llvm_unreachable("Clause kind is not allowed.");
7108 return new (Context)
7109 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
7112 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7113 SourceLocation KindKwLoc,
7114 SourceLocation StartLoc,
7115 SourceLocation LParenLoc,
7116 SourceLocation EndLoc) {
7117 if (Kind == OMPC_PROC_BIND_unknown) {
7118 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
7119 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7120 /*Last=*/OMPC_PROC_BIND_unknown)
7121 << getOpenMPClauseName(OMPC_proc_bind);
7124 return new (Context)
7125 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
7128 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
7129 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
7130 SourceLocation StartLoc, SourceLocation LParenLoc,
7131 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
7132 SourceLocation EndLoc) {
7133 OMPClause *Res = nullptr;
7136 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7137 assert(Argument.size() == NumberOfElements &&
7138 ArgumentLoc.size() == NumberOfElements);
7139 Res = ActOnOpenMPScheduleClause(
7140 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7141 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7142 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7143 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7144 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
7147 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7148 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7149 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7152 case OMPC_dist_schedule:
7153 Res = ActOnOpenMPDistScheduleClause(
7154 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7155 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7157 case OMPC_defaultmap:
7158 enum { Modifier, DefaultmapKind };
7159 Res = ActOnOpenMPDefaultmapClause(
7160 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7161 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
7162 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7166 case OMPC_num_threads:
7171 case OMPC_proc_bind:
7173 case OMPC_firstprivate:
7174 case OMPC_lastprivate:
7176 case OMPC_reduction:
7180 case OMPC_copyprivate:
7184 case OMPC_mergeable:
7185 case OMPC_threadprivate:
7197 case OMPC_num_teams:
7198 case OMPC_thread_limit:
7200 case OMPC_grainsize:
7202 case OMPC_num_tasks:
7208 case OMPC_use_device_ptr:
7209 case OMPC_is_device_ptr:
7210 llvm_unreachable("Clause is not allowed.");
7215 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7216 OpenMPScheduleClauseModifier M2,
7217 SourceLocation M1Loc, SourceLocation M2Loc) {
7218 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7219 SmallVector<unsigned, 2> Excluded;
7220 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7221 Excluded.push_back(M2);
7222 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7223 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7224 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7225 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7226 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7227 << getListOfPossibleValues(OMPC_schedule,
7228 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7229 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7231 << getOpenMPClauseName(OMPC_schedule);
7237 OMPClause *Sema::ActOnOpenMPScheduleClause(
7238 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
7239 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
7240 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7241 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7242 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7243 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7245 // OpenMP, 2.7.1, Loop Construct, Restrictions
7246 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7248 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7249 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7250 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7251 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7252 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7253 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7254 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7255 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7258 if (Kind == OMPC_SCHEDULE_unknown) {
7260 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7261 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7262 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7263 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7266 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7267 /*Last=*/OMPC_SCHEDULE_unknown);
7269 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7270 << Values << getOpenMPClauseName(OMPC_schedule);
7273 // OpenMP, 2.7.1, Loop Construct, Restrictions
7274 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7275 // schedule(guided).
7276 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7277 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7278 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7279 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7280 diag::err_omp_schedule_nonmonotonic_static);
7283 Expr *ValExpr = ChunkSize;
7284 Stmt *HelperValStmt = nullptr;
7286 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7287 !ChunkSize->isInstantiationDependent() &&
7288 !ChunkSize->containsUnexpandedParameterPack()) {
7289 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7291 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7292 if (Val.isInvalid())
7295 ValExpr = Val.get();
7297 // OpenMP [2.7.1, Restrictions]
7298 // chunk_size must be a loop invariant integer expression with a positive
7300 llvm::APSInt Result;
7301 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7302 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7303 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
7304 << "schedule" << 1 << ChunkSize->getSourceRange();
7307 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7308 !CurContext->isDependentContext()) {
7309 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7310 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7311 HelperValStmt = buildPreInits(Context, Captures);
7316 return new (Context)
7317 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
7318 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
7321 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7322 SourceLocation StartLoc,
7323 SourceLocation EndLoc) {
7324 OMPClause *Res = nullptr;
7327 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7330 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7333 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7335 case OMPC_mergeable:
7336 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7339 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7342 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7345 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7348 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7351 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7354 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7357 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7360 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7364 case OMPC_num_threads:
7370 case OMPC_firstprivate:
7371 case OMPC_lastprivate:
7373 case OMPC_reduction:
7377 case OMPC_copyprivate:
7379 case OMPC_proc_bind:
7380 case OMPC_threadprivate:
7385 case OMPC_num_teams:
7386 case OMPC_thread_limit:
7388 case OMPC_grainsize:
7389 case OMPC_num_tasks:
7391 case OMPC_dist_schedule:
7392 case OMPC_defaultmap:
7397 case OMPC_use_device_ptr:
7398 case OMPC_is_device_ptr:
7399 llvm_unreachable("Clause is not allowed.");
7404 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7405 SourceLocation EndLoc) {
7406 DSAStack->setNowaitRegion();
7407 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7410 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7411 SourceLocation EndLoc) {
7412 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7415 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7416 SourceLocation EndLoc) {
7417 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7420 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7421 SourceLocation EndLoc) {
7422 return new (Context) OMPReadClause(StartLoc, EndLoc);
7425 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7426 SourceLocation EndLoc) {
7427 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7430 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7431 SourceLocation EndLoc) {
7432 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7435 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7436 SourceLocation EndLoc) {
7437 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7440 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7441 SourceLocation EndLoc) {
7442 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7445 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7446 SourceLocation EndLoc) {
7447 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7450 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7451 SourceLocation EndLoc) {
7452 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7455 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7456 SourceLocation EndLoc) {
7457 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7460 OMPClause *Sema::ActOnOpenMPVarListClause(
7461 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7462 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7463 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
7464 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
7465 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7466 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7467 SourceLocation DepLinMapLoc) {
7468 OMPClause *Res = nullptr;
7471 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7473 case OMPC_firstprivate:
7474 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7476 case OMPC_lastprivate:
7477 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7480 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7482 case OMPC_reduction:
7483 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7484 EndLoc, ReductionIdScopeSpec, ReductionId);
7487 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
7488 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
7491 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7495 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7497 case OMPC_copyprivate:
7498 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7501 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7504 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
7505 StartLoc, LParenLoc, EndLoc);
7508 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7509 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7513 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7516 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7518 case OMPC_use_device_ptr:
7519 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7521 case OMPC_is_device_ptr:
7522 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7526 case OMPC_num_threads:
7531 case OMPC_proc_bind:
7536 case OMPC_mergeable:
7537 case OMPC_threadprivate:
7546 case OMPC_num_teams:
7547 case OMPC_thread_limit:
7549 case OMPC_grainsize:
7551 case OMPC_num_tasks:
7553 case OMPC_dist_schedule:
7554 case OMPC_defaultmap:
7557 llvm_unreachable("Clause is not allowed.");
7562 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
7563 ExprObjectKind OK, SourceLocation Loc) {
7564 ExprResult Res = BuildDeclRefExpr(
7565 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7566 if (!Res.isUsable())
7568 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7569 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7570 if (!Res.isUsable())
7573 if (VK != VK_LValue && Res.get()->isGLValue()) {
7574 Res = DefaultLvalueConversion(Res.get());
7575 if (!Res.isUsable())
7581 static std::pair<ValueDecl *, bool>
7582 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7583 SourceRange &ERange, bool AllowArraySection = false) {
7584 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7585 RefExpr->containsUnexpandedParameterPack())
7586 return std::make_pair(nullptr, true);
7588 // OpenMP [3.1, C/C++]
7589 // A list item is a variable name.
7590 // OpenMP [2.9.3.3, Restrictions, p.1]
7591 // A variable that is part of another variable (as an array or
7592 // structure element) cannot appear in a private clause.
7593 RefExpr = RefExpr->IgnoreParens();
7598 } IsArrayExpr = NoArrayExpr;
7599 if (AllowArraySection) {
7600 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7601 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7602 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7603 Base = TempASE->getBase()->IgnoreParenImpCasts();
7605 IsArrayExpr = ArraySubscript;
7606 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7607 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7608 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7609 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7610 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7611 Base = TempASE->getBase()->IgnoreParenImpCasts();
7613 IsArrayExpr = OMPArraySection;
7616 ELoc = RefExpr->getExprLoc();
7617 ERange = RefExpr->getSourceRange();
7618 RefExpr = RefExpr->IgnoreParenImpCasts();
7619 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7620 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7621 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7622 (S.getCurrentThisType().isNull() || !ME ||
7623 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7624 !isa<FieldDecl>(ME->getMemberDecl()))) {
7625 if (IsArrayExpr != NoArrayExpr)
7626 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7631 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7632 : diag::err_omp_expected_var_name_member_expr)
7633 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7635 return std::make_pair(nullptr, false);
7637 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7640 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7641 SourceLocation StartLoc,
7642 SourceLocation LParenLoc,
7643 SourceLocation EndLoc) {
7644 SmallVector<Expr *, 8> Vars;
7645 SmallVector<Expr *, 8> PrivateCopies;
7646 for (auto &RefExpr : VarList) {
7647 assert(RefExpr && "NULL expr in OpenMP private clause.");
7648 SourceLocation ELoc;
7650 Expr *SimpleRefExpr = RefExpr;
7651 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7653 // It will be analyzed later.
7654 Vars.push_back(RefExpr);
7655 PrivateCopies.push_back(nullptr);
7657 ValueDecl *D = Res.first;
7661 QualType Type = D->getType();
7662 auto *VD = dyn_cast<VarDecl>(D);
7664 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7665 // A variable that appears in a private clause must not have an incomplete
7666 // type or a reference type.
7667 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
7669 Type = Type.getNonReferenceType();
7671 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7673 // Variables with the predetermined data-sharing attributes may not be
7674 // listed in data-sharing attributes clauses, except for the cases
7675 // listed below. For these exceptions only, listing a predetermined
7676 // variable in a data-sharing attribute clause is allowed and overrides
7677 // the variable's predetermined data-sharing attributes.
7678 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7679 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
7680 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7681 << getOpenMPClauseName(OMPC_private);
7682 ReportOriginalDSA(*this, DSAStack, D, DVar);
7686 auto CurrDir = DSAStack->getCurrentDirective();
7687 // Variably modified types are not supported for tasks.
7688 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
7689 isOpenMPTaskingDirective(CurrDir)) {
7690 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7691 << getOpenMPClauseName(OMPC_private) << Type
7692 << getOpenMPDirectiveName(CurrDir);
7695 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7696 Diag(D->getLocation(),
7697 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7702 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7703 // A list item cannot appear in both a map clause and a data-sharing
7704 // attribute clause on the same construct
7705 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
7706 CurrDir == OMPD_target_teams ||
7707 CurrDir == OMPD_target_teams_distribute ||
7708 CurrDir == OMPD_target_teams_distribute_parallel_for ||
7709 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
7710 CurrDir == OMPD_target_teams_distribute_simd ||
7711 CurrDir == OMPD_target_parallel_for_simd ||
7712 CurrDir == OMPD_target_parallel_for) {
7713 OpenMPClauseKind ConflictKind;
7714 if (DSAStack->checkMappableExprComponentListsForDecl(
7715 VD, /*CurrentRegionOnly=*/true,
7716 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7717 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7718 ConflictKind = WhereFoundClauseKind;
7721 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
7722 << getOpenMPClauseName(OMPC_private)
7723 << getOpenMPClauseName(ConflictKind)
7724 << getOpenMPDirectiveName(CurrDir);
7725 ReportOriginalDSA(*this, DSAStack, D, DVar);
7730 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7731 // A variable of class type (or array thereof) that appears in a private
7732 // clause requires an accessible, unambiguous default constructor for the
7734 // Generate helper private variable and initialize it with the default
7735 // value. The address of the original variable is replaced by the address of
7736 // the new private variable in CodeGen. This new variable is not added to
7737 // IdResolver, so the code in the OpenMP region uses original variable for
7738 // proper diagnostics.
7739 Type = Type.getUnqualifiedType();
7740 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7741 D->hasAttrs() ? &D->getAttrs() : nullptr);
7742 ActOnUninitializedDecl(VDPrivate);
7743 if (VDPrivate->isInvalidDecl())
7745 auto VDPrivateRefExpr = buildDeclRefExpr(
7746 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
7748 DeclRefExpr *Ref = nullptr;
7749 if (!VD && !CurContext->isDependentContext())
7750 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
7751 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
7752 Vars.push_back((VD || CurContext->isDependentContext())
7753 ? RefExpr->IgnoreParens()
7755 PrivateCopies.push_back(VDPrivateRefExpr);
7761 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7766 class DiagsUninitializedSeveretyRAII {
7768 DiagnosticsEngine &Diags;
7769 SourceLocation SavedLoc;
7773 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7775 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7777 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7778 /*Map*/ diag::Severity::Ignored, Loc);
7781 ~DiagsUninitializedSeveretyRAII() {
7783 Diags.popMappings(SavedLoc);
7788 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7789 SourceLocation StartLoc,
7790 SourceLocation LParenLoc,
7791 SourceLocation EndLoc) {
7792 SmallVector<Expr *, 8> Vars;
7793 SmallVector<Expr *, 8> PrivateCopies;
7794 SmallVector<Expr *, 8> Inits;
7795 SmallVector<Decl *, 4> ExprCaptures;
7796 bool IsImplicitClause =
7797 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7798 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7800 for (auto &RefExpr : VarList) {
7801 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
7802 SourceLocation ELoc;
7804 Expr *SimpleRefExpr = RefExpr;
7805 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7807 // It will be analyzed later.
7808 Vars.push_back(RefExpr);
7809 PrivateCopies.push_back(nullptr);
7810 Inits.push_back(nullptr);
7812 ValueDecl *D = Res.first;
7816 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
7817 QualType Type = D->getType();
7818 auto *VD = dyn_cast<VarDecl>(D);
7820 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7821 // A variable that appears in a private clause must not have an incomplete
7822 // type or a reference type.
7823 if (RequireCompleteType(ELoc, Type,
7824 diag::err_omp_firstprivate_incomplete_type))
7826 Type = Type.getNonReferenceType();
7828 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7829 // A variable of class type (or array thereof) that appears in a private
7830 // clause requires an accessible, unambiguous copy constructor for the
7832 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
7834 // If an implicit firstprivate variable found it was checked already.
7835 DSAStackTy::DSAVarData TopDVar;
7836 if (!IsImplicitClause) {
7837 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7839 bool IsConstant = ElemType.isConstant(Context);
7840 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7841 // A list item that specifies a given variable may not appear in more
7842 // than one clause on the same directive, except that a variable may be
7843 // specified in both firstprivate and lastprivate clauses.
7844 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
7845 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
7846 Diag(ELoc, diag::err_omp_wrong_dsa)
7847 << getOpenMPClauseName(DVar.CKind)
7848 << getOpenMPClauseName(OMPC_firstprivate);
7849 ReportOriginalDSA(*this, DSAStack, D, DVar);
7853 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7855 // Variables with the predetermined data-sharing attributes may not be
7856 // listed in data-sharing attributes clauses, except for the cases
7857 // listed below. For these exceptions only, listing a predetermined
7858 // variable in a data-sharing attribute clause is allowed and overrides
7859 // the variable's predetermined data-sharing attributes.
7860 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7861 // in a Construct, C/C++, p.2]
7862 // Variables with const-qualified type having no mutable member may be
7863 // listed in a firstprivate clause, even if they are static data members.
7864 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
7865 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7866 Diag(ELoc, diag::err_omp_wrong_dsa)
7867 << getOpenMPClauseName(DVar.CKind)
7868 << getOpenMPClauseName(OMPC_firstprivate);
7869 ReportOriginalDSA(*this, DSAStack, D, DVar);
7873 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7874 // OpenMP [2.9.3.4, Restrictions, p.2]
7875 // A list item that is private within a parallel region must not appear
7876 // in a firstprivate clause on a worksharing construct if any of the
7877 // worksharing regions arising from the worksharing construct ever bind
7878 // to any of the parallel regions arising from the parallel construct.
7879 if (isOpenMPWorksharingDirective(CurrDir) &&
7880 !isOpenMPParallelDirective(CurrDir) &&
7881 !isOpenMPTeamsDirective(CurrDir)) {
7882 DVar = DSAStack->getImplicitDSA(D, true);
7883 if (DVar.CKind != OMPC_shared &&
7884 (isOpenMPParallelDirective(DVar.DKind) ||
7885 DVar.DKind == OMPD_unknown)) {
7886 Diag(ELoc, diag::err_omp_required_access)
7887 << getOpenMPClauseName(OMPC_firstprivate)
7888 << getOpenMPClauseName(OMPC_shared);
7889 ReportOriginalDSA(*this, DSAStack, D, DVar);
7893 // OpenMP [2.9.3.4, Restrictions, p.3]
7894 // A list item that appears in a reduction clause of a parallel construct
7895 // must not appear in a firstprivate clause on a worksharing or task
7896 // construct if any of the worksharing or task regions arising from the
7897 // worksharing or task construct ever bind to any of the parallel regions
7898 // arising from the parallel construct.
7899 // OpenMP [2.9.3.4, Restrictions, p.4]
7900 // A list item that appears in a reduction clause in worksharing
7901 // construct must not appear in a firstprivate clause in a task construct
7902 // encountered during execution of any of the worksharing regions arising
7903 // from the worksharing construct.
7904 if (isOpenMPTaskingDirective(CurrDir)) {
7905 DVar = DSAStack->hasInnermostDSA(
7906 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7907 [](OpenMPDirectiveKind K) -> bool {
7908 return isOpenMPParallelDirective(K) ||
7909 isOpenMPWorksharingDirective(K);
7912 if (DVar.CKind == OMPC_reduction &&
7913 (isOpenMPParallelDirective(DVar.DKind) ||
7914 isOpenMPWorksharingDirective(DVar.DKind))) {
7915 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7916 << getOpenMPDirectiveName(DVar.DKind);
7917 ReportOriginalDSA(*this, DSAStack, D, DVar);
7922 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7923 // A list item that is private within a teams region must not appear in a
7924 // firstprivate clause on a distribute construct if any of the distribute
7925 // regions arising from the distribute construct ever bind to any of the
7926 // teams regions arising from the teams construct.
7927 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7928 // A list item that appears in a reduction clause of a teams construct
7929 // must not appear in a firstprivate clause on a distribute construct if
7930 // any of the distribute regions arising from the distribute construct
7931 // ever bind to any of the teams regions arising from the teams construct.
7932 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7933 // A list item may appear in a firstprivate or lastprivate clause but not
7935 if (CurrDir == OMPD_distribute) {
7936 DVar = DSAStack->hasInnermostDSA(
7937 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
7938 [](OpenMPDirectiveKind K) -> bool {
7939 return isOpenMPTeamsDirective(K);
7942 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7943 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
7944 ReportOriginalDSA(*this, DSAStack, D, DVar);
7947 DVar = DSAStack->hasInnermostDSA(
7948 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7949 [](OpenMPDirectiveKind K) -> bool {
7950 return isOpenMPTeamsDirective(K);
7953 if (DVar.CKind == OMPC_reduction &&
7954 isOpenMPTeamsDirective(DVar.DKind)) {
7955 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
7956 ReportOriginalDSA(*this, DSAStack, D, DVar);
7959 DVar = DSAStack->getTopDSA(D, false);
7960 if (DVar.CKind == OMPC_lastprivate) {
7961 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7962 ReportOriginalDSA(*this, DSAStack, D, DVar);
7966 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7967 // A list item cannot appear in both a map clause and a data-sharing
7968 // attribute clause on the same construct
7969 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
7970 CurrDir == OMPD_target_teams ||
7971 CurrDir == OMPD_target_teams_distribute ||
7972 CurrDir == OMPD_target_teams_distribute_parallel_for ||
7973 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
7974 CurrDir == OMPD_target_teams_distribute_simd ||
7975 CurrDir == OMPD_target_parallel_for_simd ||
7976 CurrDir == OMPD_target_parallel_for) {
7977 OpenMPClauseKind ConflictKind;
7978 if (DSAStack->checkMappableExprComponentListsForDecl(
7979 VD, /*CurrentRegionOnly=*/true,
7980 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7981 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7982 ConflictKind = WhereFoundClauseKind;
7985 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
7986 << getOpenMPClauseName(OMPC_firstprivate)
7987 << getOpenMPClauseName(ConflictKind)
7988 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7989 ReportOriginalDSA(*this, DSAStack, D, DVar);
7995 // Variably modified types are not supported for tasks.
7996 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
7997 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
7998 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7999 << getOpenMPClauseName(OMPC_firstprivate) << Type
8000 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8003 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8004 Diag(D->getLocation(),
8005 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8010 Type = Type.getUnqualifiedType();
8011 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8012 D->hasAttrs() ? &D->getAttrs() : nullptr);
8013 // Generate helper private variable and initialize it with the value of the
8014 // original variable. The address of the original variable is replaced by
8015 // the address of the new private variable in the CodeGen. This new variable
8016 // is not added to IdResolver, so the code in the OpenMP region uses
8017 // original variable for proper diagnostics and variable capturing.
8018 Expr *VDInitRefExpr = nullptr;
8019 // For arrays generate initializer for single element and replace it by the
8020 // original array element in CodeGen.
8021 if (Type->isArrayType()) {
8023 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
8024 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
8025 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
8026 ElemType = ElemType.getUnqualifiedType();
8027 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
8028 ".firstprivate.temp");
8029 InitializedEntity Entity =
8030 InitializedEntity::InitializeVariable(VDInitTemp);
8031 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8033 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8034 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8035 if (Result.isInvalid())
8036 VDPrivate->setInvalidDecl();
8038 VDPrivate->setInit(Result.getAs<Expr>());
8039 // Remove temp variable declaration.
8040 Context.Deallocate(VDInitTemp);
8042 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8043 ".firstprivate.temp");
8044 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8045 RefExpr->getExprLoc());
8046 AddInitializerToDecl(VDPrivate,
8047 DefaultLvalueConversion(VDInitRefExpr).get(),
8048 /*DirectInit=*/false);
8050 if (VDPrivate->isInvalidDecl()) {
8051 if (IsImplicitClause) {
8052 Diag(RefExpr->getExprLoc(),
8053 diag::note_omp_task_predetermined_firstprivate_here);
8057 CurContext->addDecl(VDPrivate);
8058 auto VDPrivateRefExpr = buildDeclRefExpr(
8059 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8060 RefExpr->getExprLoc());
8061 DeclRefExpr *Ref = nullptr;
8062 if (!VD && !CurContext->isDependentContext()) {
8063 if (TopDVar.CKind == OMPC_lastprivate)
8064 Ref = TopDVar.PrivateCopy;
8066 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8067 if (!IsOpenMPCapturedDecl(D))
8068 ExprCaptures.push_back(Ref->getDecl());
8071 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
8072 Vars.push_back((VD || CurContext->isDependentContext())
8073 ? RefExpr->IgnoreParens()
8075 PrivateCopies.push_back(VDPrivateRefExpr);
8076 Inits.push_back(VDInitRefExpr);
8082 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
8083 Vars, PrivateCopies, Inits,
8084 buildPreInits(Context, ExprCaptures));
8087 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8088 SourceLocation StartLoc,
8089 SourceLocation LParenLoc,
8090 SourceLocation EndLoc) {
8091 SmallVector<Expr *, 8> Vars;
8092 SmallVector<Expr *, 8> SrcExprs;
8093 SmallVector<Expr *, 8> DstExprs;
8094 SmallVector<Expr *, 8> AssignmentOps;
8095 SmallVector<Decl *, 4> ExprCaptures;
8096 SmallVector<Expr *, 4> ExprPostUpdates;
8097 for (auto &RefExpr : VarList) {
8098 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
8099 SourceLocation ELoc;
8101 Expr *SimpleRefExpr = RefExpr;
8102 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
8104 // It will be analyzed later.
8105 Vars.push_back(RefExpr);
8106 SrcExprs.push_back(nullptr);
8107 DstExprs.push_back(nullptr);
8108 AssignmentOps.push_back(nullptr);
8110 ValueDecl *D = Res.first;
8114 QualType Type = D->getType();
8115 auto *VD = dyn_cast<VarDecl>(D);
8117 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8118 // A variable that appears in a lastprivate clause must not have an
8119 // incomplete type or a reference type.
8120 if (RequireCompleteType(ELoc, Type,
8121 diag::err_omp_lastprivate_incomplete_type))
8123 Type = Type.getNonReferenceType();
8125 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8127 // Variables with the predetermined data-sharing attributes may not be
8128 // listed in data-sharing attributes clauses, except for the cases
8130 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8131 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
8132 DVar.CKind != OMPC_firstprivate &&
8133 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8134 Diag(ELoc, diag::err_omp_wrong_dsa)
8135 << getOpenMPClauseName(DVar.CKind)
8136 << getOpenMPClauseName(OMPC_lastprivate);
8137 ReportOriginalDSA(*this, DSAStack, D, DVar);
8141 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8142 // OpenMP [2.14.3.5, Restrictions, p.2]
8143 // A list item that is private within a parallel region, or that appears in
8144 // the reduction clause of a parallel construct, must not appear in a
8145 // lastprivate clause on a worksharing construct if any of the corresponding
8146 // worksharing regions ever binds to any of the corresponding parallel
8148 DSAStackTy::DSAVarData TopDVar = DVar;
8149 if (isOpenMPWorksharingDirective(CurrDir) &&
8150 !isOpenMPParallelDirective(CurrDir) &&
8151 !isOpenMPTeamsDirective(CurrDir)) {
8152 DVar = DSAStack->getImplicitDSA(D, true);
8153 if (DVar.CKind != OMPC_shared) {
8154 Diag(ELoc, diag::err_omp_required_access)
8155 << getOpenMPClauseName(OMPC_lastprivate)
8156 << getOpenMPClauseName(OMPC_shared);
8157 ReportOriginalDSA(*this, DSAStack, D, DVar);
8162 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8163 // A list item may appear in a firstprivate or lastprivate clause but not
8165 if (CurrDir == OMPD_distribute) {
8166 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8167 if (DVar.CKind == OMPC_firstprivate) {
8168 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8169 ReportOriginalDSA(*this, DSAStack, D, DVar);
8174 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
8175 // A variable of class type (or array thereof) that appears in a
8176 // lastprivate clause requires an accessible, unambiguous default
8177 // constructor for the class type, unless the list item is also specified
8178 // in a firstprivate clause.
8179 // A variable of class type (or array thereof) that appears in a
8180 // lastprivate clause requires an accessible, unambiguous copy assignment
8181 // operator for the class type.
8182 Type = Context.getBaseElementType(Type).getNonReferenceType();
8183 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
8184 Type.getUnqualifiedType(), ".lastprivate.src",
8185 D->hasAttrs() ? &D->getAttrs() : nullptr);
8186 auto *PseudoSrcExpr =
8187 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
8189 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
8190 D->hasAttrs() ? &D->getAttrs() : nullptr);
8191 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
8192 // For arrays generate assignment operation for single element and replace
8193 // it by the original array element in CodeGen.
8194 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
8195 PseudoDstExpr, PseudoSrcExpr);
8196 if (AssignmentOp.isInvalid())
8198 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
8199 /*DiscardedValue=*/true);
8200 if (AssignmentOp.isInvalid())
8203 DeclRefExpr *Ref = nullptr;
8204 if (!VD && !CurContext->isDependentContext()) {
8205 if (TopDVar.CKind == OMPC_firstprivate)
8206 Ref = TopDVar.PrivateCopy;
8208 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8209 if (!IsOpenMPCapturedDecl(D))
8210 ExprCaptures.push_back(Ref->getDecl());
8212 if (TopDVar.CKind == OMPC_firstprivate ||
8213 (!IsOpenMPCapturedDecl(D) &&
8214 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
8215 ExprResult RefRes = DefaultLvalueConversion(Ref);
8216 if (!RefRes.isUsable())
8218 ExprResult PostUpdateRes =
8219 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8221 if (!PostUpdateRes.isUsable())
8223 ExprPostUpdates.push_back(
8224 IgnoredValueConversions(PostUpdateRes.get()).get());
8227 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
8228 Vars.push_back((VD || CurContext->isDependentContext())
8229 ? RefExpr->IgnoreParens()
8231 SrcExprs.push_back(PseudoSrcExpr);
8232 DstExprs.push_back(PseudoDstExpr);
8233 AssignmentOps.push_back(AssignmentOp.get());
8239 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
8240 Vars, SrcExprs, DstExprs, AssignmentOps,
8241 buildPreInits(Context, ExprCaptures),
8242 buildPostUpdate(*this, ExprPostUpdates));
8245 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8246 SourceLocation StartLoc,
8247 SourceLocation LParenLoc,
8248 SourceLocation EndLoc) {
8249 SmallVector<Expr *, 8> Vars;
8250 for (auto &RefExpr : VarList) {
8251 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
8252 SourceLocation ELoc;
8254 Expr *SimpleRefExpr = RefExpr;
8255 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
8257 // It will be analyzed later.
8258 Vars.push_back(RefExpr);
8260 ValueDecl *D = Res.first;
8264 auto *VD = dyn_cast<VarDecl>(D);
8265 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8267 // Variables with the predetermined data-sharing attributes may not be
8268 // listed in data-sharing attributes clauses, except for the cases
8269 // listed below. For these exceptions only, listing a predetermined
8270 // variable in a data-sharing attribute clause is allowed and overrides
8271 // the variable's predetermined data-sharing attributes.
8272 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8273 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8275 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8276 << getOpenMPClauseName(OMPC_shared);
8277 ReportOriginalDSA(*this, DSAStack, D, DVar);
8281 DeclRefExpr *Ref = nullptr;
8282 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
8283 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8284 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
8285 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8286 ? RefExpr->IgnoreParens()
8293 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8297 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8301 bool VisitDeclRefExpr(DeclRefExpr *E) {
8302 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
8303 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
8304 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8306 if (DVar.CKind != OMPC_unknown)
8308 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8309 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8311 if (DVarPrivate.CKind != OMPC_unknown)
8317 bool VisitStmt(Stmt *S) {
8318 for (auto Child : S->children()) {
8319 if (Child && Visit(Child))
8324 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
8329 // Transform MemberExpression for specified FieldDecl of current class to
8330 // DeclRefExpr to specified OMPCapturedExprDecl.
8331 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8332 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8334 DeclRefExpr *CapturedExpr;
8337 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8338 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8340 ExprResult TransformMemberExpr(MemberExpr *E) {
8341 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8342 E->getMemberDecl() == Field) {
8343 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
8344 return CapturedExpr;
8346 return BaseTransform::TransformMemberExpr(E);
8348 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8352 template <typename T>
8353 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8354 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8355 for (auto &Set : Lookups) {
8356 for (auto *D : Set) {
8357 if (auto Res = Gen(cast<ValueDecl>(D)))
8365 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8366 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8367 const DeclarationNameInfo &ReductionId, QualType Ty,
8368 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8369 if (ReductionIdScopeSpec.isInvalid())
8371 SmallVector<UnresolvedSet<8>, 4> Lookups;
8373 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8374 Lookup.suppressDiagnostics();
8375 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8376 auto *D = Lookup.getRepresentativeDecl();
8379 } while (S && !S->isDeclScope(D));
8382 Lookups.push_back(UnresolvedSet<8>());
8383 Lookups.back().append(Lookup.begin(), Lookup.end());
8386 } else if (auto *ULE =
8387 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8388 Lookups.push_back(UnresolvedSet<8>());
8389 Decl *PrevD = nullptr;
8390 for (auto *D : ULE->decls()) {
8392 Lookups.push_back(UnresolvedSet<8>());
8393 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8394 Lookups.back().addDecl(DRD);
8398 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8399 Ty->containsUnexpandedParameterPack() ||
8400 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8401 return !D->isInvalidDecl() &&
8402 (D->getType()->isDependentType() ||
8403 D->getType()->isInstantiationDependentType() ||
8404 D->getType()->containsUnexpandedParameterPack());
8406 UnresolvedSet<8> ResSet;
8407 for (auto &Set : Lookups) {
8408 ResSet.append(Set.begin(), Set.end());
8409 // The last item marks the end of all declarations at the specified scope.
8410 ResSet.addDecl(Set[Set.size() - 1]);
8412 return UnresolvedLookupExpr::Create(
8413 SemaRef.Context, /*NamingClass=*/nullptr,
8414 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8415 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8417 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8418 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8419 if (!D->isInvalidDecl() &&
8420 SemaRef.Context.hasSameType(D->getType(), Ty))
8424 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8425 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8426 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8427 if (!D->isInvalidDecl() &&
8428 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8429 !Ty.isMoreQualifiedThan(D->getType()))
8433 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8434 /*DetectVirtual=*/false);
8435 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8436 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8437 VD->getType().getUnqualifiedType()))) {
8438 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8440 Sema::AR_inaccessible) {
8441 SemaRef.BuildBasePathArray(Paths, BasePath);
8442 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8447 if (ReductionIdScopeSpec.isSet()) {
8448 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8454 OMPClause *Sema::ActOnOpenMPReductionClause(
8455 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8456 SourceLocation ColonLoc, SourceLocation EndLoc,
8457 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8458 ArrayRef<Expr *> UnresolvedReductions) {
8459 auto DN = ReductionId.getName();
8460 auto OOK = DN.getCXXOverloadedOperator();
8461 BinaryOperatorKind BOK = BO_Comma;
8463 // OpenMP [2.14.3.6, reduction clause]
8465 // reduction-identifier is either an identifier or one of the following
8466 // operators: +, -, *, &, |, ^, && and ||
8468 // reduction-identifier is either an id-expression or one of the following
8469 // operators: +, -, *, &, |, ^, && and ||
8470 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8497 case OO_Array_Delete:
8506 case OO_GreaterEqual:
8511 case OO_PercentEqual:
8516 case OO_GreaterGreater:
8517 case OO_LessLessEqual:
8518 case OO_GreaterGreaterEqual:
8520 case OO_ExclaimEqual:
8528 case OO_Conditional:
8530 case NUM_OVERLOADED_OPERATORS:
8531 llvm_unreachable("Unexpected reduction identifier");
8533 if (auto II = DN.getAsIdentifierInfo()) {
8534 if (II->isStr("max"))
8536 else if (II->isStr("min"))
8541 SourceRange ReductionIdRange;
8542 if (ReductionIdScopeSpec.isValid())
8543 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
8544 ReductionIdRange.setEnd(ReductionId.getEndLoc());
8546 SmallVector<Expr *, 8> Vars;
8547 SmallVector<Expr *, 8> Privates;
8548 SmallVector<Expr *, 8> LHSs;
8549 SmallVector<Expr *, 8> RHSs;
8550 SmallVector<Expr *, 8> ReductionOps;
8551 SmallVector<Decl *, 4> ExprCaptures;
8552 SmallVector<Expr *, 4> ExprPostUpdates;
8553 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8554 bool FirstIter = true;
8555 for (auto RefExpr : VarList) {
8556 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
8557 // OpenMP [2.1, C/C++]
8558 // A list item is a variable or array section, subject to the restrictions
8559 // specified in Section 2.4 on page 42 and in each of the sections
8560 // describing clauses and directives for which a list appears.
8561 // OpenMP [2.14.3.3, Restrictions, p.1]
8562 // A variable that is part of another variable (as an array or
8563 // structure element) cannot appear in a private clause.
8564 if (!FirstIter && IR != ER)
8567 SourceLocation ELoc;
8569 Expr *SimpleRefExpr = RefExpr;
8570 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8571 /*AllowArraySection=*/true);
8573 // It will be analyzed later.
8574 Vars.push_back(RefExpr);
8575 Privates.push_back(nullptr);
8576 LHSs.push_back(nullptr);
8577 RHSs.push_back(nullptr);
8578 // Try to find 'declare reduction' corresponding construct before using
8579 // builtin/overloaded operators.
8580 QualType Type = Context.DependentTy;
8581 CXXCastPath BasePath;
8582 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8583 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8584 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8585 if (CurContext->isDependentContext() &&
8586 (DeclareReductionRef.isUnset() ||
8587 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8588 ReductionOps.push_back(DeclareReductionRef.get());
8590 ReductionOps.push_back(nullptr);
8592 ValueDecl *D = Res.first;
8597 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8598 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8600 Type = ASE->getType().getNonReferenceType();
8602 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8603 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8604 Type = ATy->getElementType();
8606 Type = BaseType->getPointeeType();
8607 Type = Type.getNonReferenceType();
8609 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8610 auto *VD = dyn_cast<VarDecl>(D);
8612 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8613 // A variable that appears in a private clause must not have an incomplete
8614 // type or a reference type.
8615 if (RequireCompleteType(ELoc, Type,
8616 diag::err_omp_reduction_incomplete_type))
8618 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8619 // A list item that appears in a reduction clause must not be
8621 if (Type.getNonReferenceType().isConstant(Context)) {
8622 Diag(ELoc, diag::err_omp_const_reduction_list_item)
8623 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
8624 if (!ASE && !OASE) {
8625 bool IsDecl = !VD ||
8626 VD->isThisDeclarationADefinition(Context) ==
8627 VarDecl::DeclarationOnly;
8628 Diag(D->getLocation(),
8629 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8634 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8635 // If a list-item is a reference type then it must bind to the same object
8636 // for all threads of the team.
8637 if (!ASE && !OASE && VD) {
8638 VarDecl *VDDef = VD->getDefinition();
8639 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
8640 DSARefChecker Check(DSAStack);
8641 if (Check.Visit(VDDef->getInit())) {
8642 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8643 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8649 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8651 // Variables with the predetermined data-sharing attributes may not be
8652 // listed in data-sharing attributes clauses, except for the cases
8653 // listed below. For these exceptions only, listing a predetermined
8654 // variable in a data-sharing attribute clause is allowed and overrides
8655 // the variable's predetermined data-sharing attributes.
8656 // OpenMP [2.14.3.6, Restrictions, p.3]
8657 // Any number of reduction clauses can be specified on the directive,
8658 // but a list item can appear only once in the reduction clauses for that
8660 DSAStackTy::DSAVarData DVar;
8661 DVar = DSAStack->getTopDSA(D, false);
8662 if (DVar.CKind == OMPC_reduction) {
8663 Diag(ELoc, diag::err_omp_once_referenced)
8664 << getOpenMPClauseName(OMPC_reduction);
8666 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
8667 } else if (DVar.CKind != OMPC_unknown) {
8668 Diag(ELoc, diag::err_omp_wrong_dsa)
8669 << getOpenMPClauseName(DVar.CKind)
8670 << getOpenMPClauseName(OMPC_reduction);
8671 ReportOriginalDSA(*this, DSAStack, D, DVar);
8675 // OpenMP [2.14.3.6, Restrictions, p.1]
8676 // A list item that appears in a reduction clause of a worksharing
8677 // construct must be shared in the parallel regions to which any of the
8678 // worksharing regions arising from the worksharing construct bind.
8679 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8680 if (isOpenMPWorksharingDirective(CurrDir) &&
8681 !isOpenMPParallelDirective(CurrDir) &&
8682 !isOpenMPTeamsDirective(CurrDir)) {
8683 DVar = DSAStack->getImplicitDSA(D, true);
8684 if (DVar.CKind != OMPC_shared) {
8685 Diag(ELoc, diag::err_omp_required_access)
8686 << getOpenMPClauseName(OMPC_reduction)
8687 << getOpenMPClauseName(OMPC_shared);
8688 ReportOriginalDSA(*this, DSAStack, D, DVar);
8693 // Try to find 'declare reduction' corresponding construct before using
8694 // builtin/overloaded operators.
8695 CXXCastPath BasePath;
8696 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8697 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8698 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8699 if (DeclareReductionRef.isInvalid())
8701 if (CurContext->isDependentContext() &&
8702 (DeclareReductionRef.isUnset() ||
8703 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8704 Vars.push_back(RefExpr);
8705 Privates.push_back(nullptr);
8706 LHSs.push_back(nullptr);
8707 RHSs.push_back(nullptr);
8708 ReductionOps.push_back(DeclareReductionRef.get());
8711 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8712 // Not allowed reduction identifier is found.
8713 Diag(ReductionId.getLocStart(),
8714 diag::err_omp_unknown_reduction_identifier)
8715 << Type << ReductionIdRange;
8719 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8720 // The type of a list item that appears in a reduction clause must be valid
8721 // for the reduction-identifier. For a max or min reduction in C, the type
8722 // of the list item must be an allowed arithmetic data type: char, int,
8723 // float, double, or _Bool, possibly modified with long, short, signed, or
8724 // unsigned. For a max or min reduction in C++, the type of the list item
8725 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8726 // double, or bool, possibly modified with long, short, signed, or unsigned.
8727 if (DeclareReductionRef.isUnset()) {
8728 if ((BOK == BO_GT || BOK == BO_LT) &&
8729 !(Type->isScalarType() ||
8730 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8731 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8732 << getLangOpts().CPlusPlus;
8733 if (!ASE && !OASE) {
8734 bool IsDecl = !VD ||
8735 VD->isThisDeclarationADefinition(Context) ==
8736 VarDecl::DeclarationOnly;
8737 Diag(D->getLocation(),
8738 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8743 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8744 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8745 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8746 if (!ASE && !OASE) {
8747 bool IsDecl = !VD ||
8748 VD->isThisDeclarationADefinition(Context) ==
8749 VarDecl::DeclarationOnly;
8750 Diag(D->getLocation(),
8751 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8758 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
8759 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
8760 D->hasAttrs() ? &D->getAttrs() : nullptr);
8761 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8762 D->hasAttrs() ? &D->getAttrs() : nullptr);
8763 auto PrivateTy = Type;
8766 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
8767 // For arrays/array sections only:
8768 // Create pseudo array type for private copy. The size for this array will
8769 // be generated during codegen.
8770 // For array subscripts or single variables Private Ty is the same as Type
8771 // (type of the variable or single array element).
8772 PrivateTy = Context.getVariableArrayType(
8773 Type, new (Context) OpaqueValueExpr(SourceLocation(),
8774 Context.getSizeType(), VK_RValue),
8775 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
8776 } else if (!ASE && !OASE &&
8777 Context.getAsArrayType(D->getType().getNonReferenceType()))
8778 PrivateTy = D->getType().getNonReferenceType();
8780 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8781 D->hasAttrs() ? &D->getAttrs() : nullptr);
8782 // Add initializer for private variable.
8783 Expr *Init = nullptr;
8784 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8785 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8786 if (DeclareReductionRef.isUsable()) {
8787 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8788 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8789 if (DRD->getInitializer()) {
8791 RHSVD->setInit(DRDRef);
8792 RHSVD->setInitStyle(VarDecl::CallInit);
8800 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8801 if (Type->isScalarType() || Type->isAnyComplexType())
8802 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8806 if (Type->isScalarType() || Type->isAnyComplexType()) {
8807 // '*' and '&&' reduction ops - initializer is '1'.
8808 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
8812 // '&' reduction op - initializer is '~0'.
8813 QualType OrigType = Type;
8814 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8815 Type = ComplexTy->getElementType();
8816 if (Type->isRealFloatingType()) {
8817 llvm::APFloat InitValue =
8818 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8820 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8822 } else if (Type->isScalarType()) {
8823 auto Size = Context.getTypeSize(Type);
8824 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8825 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8826 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8828 if (Init && OrigType->isAnyComplexType()) {
8829 // Init = 0xFFFF + 0xFFFFi;
8830 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8831 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8838 // 'min' reduction op - initializer is 'Largest representable number in
8839 // the reduction list item type'.
8840 // 'max' reduction op - initializer is 'Least representable number in
8841 // the reduction list item type'.
8842 if (Type->isIntegerType() || Type->isPointerType()) {
8843 bool IsSigned = Type->hasSignedIntegerRepresentation();
8844 auto Size = Context.getTypeSize(Type);
8846 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8847 llvm::APInt InitValue =
8849 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8850 : llvm::APInt::getMinValue(Size)
8851 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8852 : llvm::APInt::getMaxValue(Size);
8853 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8854 if (Type->isPointerType()) {
8855 // Cast to pointer type.
8856 auto CastExpr = BuildCStyleCastExpr(
8857 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8858 SourceLocation(), Init);
8859 if (CastExpr.isInvalid())
8861 Init = CastExpr.get();
8863 } else if (Type->isRealFloatingType()) {
8864 llvm::APFloat InitValue = llvm::APFloat::getLargest(
8865 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8866 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8894 llvm_unreachable("Unexpected reduction operation");
8897 if (Init && DeclareReductionRef.isUnset()) {
8898 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
8900 ActOnUninitializedDecl(RHSVD);
8901 if (RHSVD->isInvalidDecl())
8903 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
8904 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8905 << ReductionIdRange;
8908 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8909 Diag(D->getLocation(),
8910 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8914 // Store initializer for single element in private copy. Will be used during
8916 PrivateVD->setInit(RHSVD->getInit());
8917 PrivateVD->setInitStyle(RHSVD->getInitStyle());
8918 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
8919 ExprResult ReductionOp;
8920 if (DeclareReductionRef.isUsable()) {
8921 QualType RedTy = DeclareReductionRef.get()->getType();
8922 QualType PtrRedTy = Context.getPointerType(RedTy);
8923 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
8924 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
8925 if (!BasePath.empty()) {
8926 LHS = DefaultLvalueConversion(LHS.get());
8927 RHS = DefaultLvalueConversion(RHS.get());
8928 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8929 CK_UncheckedDerivedToBase, LHS.get(),
8930 &BasePath, LHS.get()->getValueKind());
8931 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8932 CK_UncheckedDerivedToBase, RHS.get(),
8933 &BasePath, RHS.get()->getValueKind());
8935 FunctionProtoType::ExtProtoInfo EPI;
8936 QualType Params[] = {PtrRedTy, PtrRedTy};
8937 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
8938 auto *OVE = new (Context) OpaqueValueExpr(
8939 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
8940 DefaultLvalueConversion(DeclareReductionRef.get()).get());
8941 Expr *Args[] = {LHS.get(), RHS.get()};
8942 ReductionOp = new (Context)
8943 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
8945 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
8946 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
8947 if (ReductionOp.isUsable()) {
8948 if (BOK != BO_LT && BOK != BO_GT) {
8950 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8951 BO_Assign, LHSDRE, ReductionOp.get());
8953 auto *ConditionalOp = new (Context) ConditionalOperator(
8954 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
8955 RHSDRE, Type, VK_LValue, OK_Ordinary);
8957 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8958 BO_Assign, LHSDRE, ConditionalOp);
8960 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
8962 if (ReductionOp.isInvalid())
8966 DeclRefExpr *Ref = nullptr;
8967 Expr *VarsExpr = RefExpr->IgnoreParens();
8968 if (!VD && !CurContext->isDependentContext()) {
8970 TransformExprToCaptures RebuildToCapture(*this, D);
8972 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
8973 Ref = RebuildToCapture.getCapturedExpr();
8976 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8978 if (!IsOpenMPCapturedDecl(D)) {
8979 ExprCaptures.push_back(Ref->getDecl());
8980 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8981 ExprResult RefRes = DefaultLvalueConversion(Ref);
8982 if (!RefRes.isUsable())
8984 ExprResult PostUpdateRes =
8985 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8986 SimpleRefExpr, RefRes.get());
8987 if (!PostUpdateRes.isUsable())
8989 ExprPostUpdates.push_back(
8990 IgnoredValueConversions(PostUpdateRes.get()).get());
8994 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
8995 Vars.push_back(VarsExpr);
8996 Privates.push_back(PrivateDRE);
8997 LHSs.push_back(LHSDRE);
8998 RHSs.push_back(RHSDRE);
8999 ReductionOps.push_back(ReductionOp.get());
9005 return OMPReductionClause::Create(
9006 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
9007 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
9008 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
9009 buildPostUpdate(*this, ExprPostUpdates));
9012 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9013 SourceLocation LinLoc) {
9014 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9015 LinKind == OMPC_LINEAR_unknown) {
9016 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9022 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9023 OpenMPLinearClauseKind LinKind,
9025 auto *VD = dyn_cast_or_null<VarDecl>(D);
9026 // A variable must not have an incomplete type or a reference type.
9027 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9029 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9030 !Type->isReferenceType()) {
9031 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9032 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9035 Type = Type.getNonReferenceType();
9037 // A list item must not be const-qualified.
9038 if (Type.isConstant(Context)) {
9039 Diag(ELoc, diag::err_omp_const_variable)
9040 << getOpenMPClauseName(OMPC_linear);
9044 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9045 Diag(D->getLocation(),
9046 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9052 // A list item must be of integral or pointer type.
9053 Type = Type.getUnqualifiedType().getCanonicalType();
9054 const auto *Ty = Type.getTypePtrOrNull();
9055 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9056 !Ty->isPointerType())) {
9057 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9061 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9062 Diag(D->getLocation(),
9063 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9071 OMPClause *Sema::ActOnOpenMPLinearClause(
9072 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9073 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9074 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9075 SmallVector<Expr *, 8> Vars;
9076 SmallVector<Expr *, 8> Privates;
9077 SmallVector<Expr *, 8> Inits;
9078 SmallVector<Decl *, 4> ExprCaptures;
9079 SmallVector<Expr *, 4> ExprPostUpdates;
9080 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
9081 LinKind = OMPC_LINEAR_val;
9082 for (auto &RefExpr : VarList) {
9083 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9084 SourceLocation ELoc;
9086 Expr *SimpleRefExpr = RefExpr;
9087 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9088 /*AllowArraySection=*/false);
9090 // It will be analyzed later.
9091 Vars.push_back(RefExpr);
9092 Privates.push_back(nullptr);
9093 Inits.push_back(nullptr);
9095 ValueDecl *D = Res.first;
9099 QualType Type = D->getType();
9100 auto *VD = dyn_cast<VarDecl>(D);
9102 // OpenMP [2.14.3.7, linear clause]
9103 // A list-item cannot appear in more than one linear clause.
9104 // A list-item that appears in a linear clause cannot appear in any
9105 // other data-sharing attribute clause.
9106 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
9108 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9109 << getOpenMPClauseName(OMPC_linear);
9110 ReportOriginalDSA(*this, DSAStack, D, DVar);
9114 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
9116 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
9118 // Build private copy of original var.
9119 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9120 D->hasAttrs() ? &D->getAttrs() : nullptr);
9121 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
9122 // Build var to save initial value.
9123 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
9125 DeclRefExpr *Ref = nullptr;
9126 if (!VD && !CurContext->isDependentContext()) {
9127 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9128 if (!IsOpenMPCapturedDecl(D)) {
9129 ExprCaptures.push_back(Ref->getDecl());
9130 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9131 ExprResult RefRes = DefaultLvalueConversion(Ref);
9132 if (!RefRes.isUsable())
9134 ExprResult PostUpdateRes =
9135 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9136 SimpleRefExpr, RefRes.get());
9137 if (!PostUpdateRes.isUsable())
9139 ExprPostUpdates.push_back(
9140 IgnoredValueConversions(PostUpdateRes.get()).get());
9144 if (LinKind == OMPC_LINEAR_uval)
9145 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
9147 InitExpr = VD ? SimpleRefExpr : Ref;
9148 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
9149 /*DirectInit=*/false);
9150 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9152 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
9153 Vars.push_back((VD || CurContext->isDependentContext())
9154 ? RefExpr->IgnoreParens()
9156 Privates.push_back(PrivateRef);
9157 Inits.push_back(InitRef);
9163 Expr *StepExpr = Step;
9164 Expr *CalcStepExpr = nullptr;
9165 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9166 !Step->isInstantiationDependent() &&
9167 !Step->containsUnexpandedParameterPack()) {
9168 SourceLocation StepLoc = Step->getLocStart();
9169 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
9170 if (Val.isInvalid())
9172 StepExpr = Val.get();
9174 // Build var to save the step value.
9176 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
9177 ExprResult SaveRef =
9178 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
9179 ExprResult CalcStep =
9180 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
9181 CalcStep = ActOnFinishFullExpr(CalcStep.get());
9183 // Warn about zero linear step (it would be probably better specified as
9184 // making corresponding variables 'const').
9185 llvm::APSInt Result;
9186 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9187 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
9188 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9189 << (Vars.size() > 1);
9190 if (!IsConstant && CalcStep.isUsable()) {
9191 // Calculate the step beforehand instead of doing this on each iteration.
9192 // (This is not used if the number of iterations may be kfold-ed).
9193 CalcStepExpr = CalcStep.get();
9197 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9198 ColonLoc, EndLoc, Vars, Privates, Inits,
9199 StepExpr, CalcStepExpr,
9200 buildPreInits(Context, ExprCaptures),
9201 buildPostUpdate(*this, ExprPostUpdates));
9204 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9205 Expr *NumIterations, Sema &SemaRef,
9206 Scope *S, DSAStackTy *Stack) {
9207 // Walk the vars and build update/final expressions for the CodeGen.
9208 SmallVector<Expr *, 8> Updates;
9209 SmallVector<Expr *, 8> Finals;
9210 Expr *Step = Clause.getStep();
9211 Expr *CalcStep = Clause.getCalcStep();
9212 // OpenMP [2.14.3.7, linear clause]
9213 // If linear-step is not specified it is assumed to be 1.
9214 if (Step == nullptr)
9215 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
9216 else if (CalcStep) {
9217 Step = cast<BinaryOperator>(CalcStep)->getLHS();
9219 bool HasErrors = false;
9220 auto CurInit = Clause.inits().begin();
9221 auto CurPrivate = Clause.privates().begin();
9222 auto LinKind = Clause.getModifier();
9223 for (auto &RefExpr : Clause.varlists()) {
9224 SourceLocation ELoc;
9226 Expr *SimpleRefExpr = RefExpr;
9227 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9228 /*AllowArraySection=*/false);
9229 ValueDecl *D = Res.first;
9230 if (Res.second || !D) {
9231 Updates.push_back(nullptr);
9232 Finals.push_back(nullptr);
9236 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9237 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9240 auto &&Info = Stack->isLoopControlVariable(D);
9241 Expr *InitExpr = *CurInit;
9243 // Build privatized reference to the current linear var.
9244 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
9246 if (LinKind == OMPC_LINEAR_uval)
9247 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9250 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9251 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9252 /*RefersToCapture=*/true);
9254 // Build update: Var = InitExpr + IV * Step
9258 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9259 InitExpr, IV, Step, /* Subtract */ false);
9261 Update = *CurPrivate;
9262 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9263 /*DiscardedValue=*/true);
9265 // Build final: Var = InitExpr + NumIterations * Step
9268 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9269 InitExpr, NumIterations, Step,
9270 /* Subtract */ false);
9272 Final = *CurPrivate;
9273 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9274 /*DiscardedValue=*/true);
9276 if (!Update.isUsable() || !Final.isUsable()) {
9277 Updates.push_back(nullptr);
9278 Finals.push_back(nullptr);
9281 Updates.push_back(Update.get());
9282 Finals.push_back(Final.get());
9287 Clause.setUpdates(Updates);
9288 Clause.setFinals(Finals);
9292 OMPClause *Sema::ActOnOpenMPAlignedClause(
9293 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9294 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9296 SmallVector<Expr *, 8> Vars;
9297 for (auto &RefExpr : VarList) {
9298 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9299 SourceLocation ELoc;
9301 Expr *SimpleRefExpr = RefExpr;
9302 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9303 /*AllowArraySection=*/false);
9305 // It will be analyzed later.
9306 Vars.push_back(RefExpr);
9308 ValueDecl *D = Res.first;
9312 QualType QType = D->getType();
9313 auto *VD = dyn_cast<VarDecl>(D);
9315 // OpenMP [2.8.1, simd construct, Restrictions]
9316 // The type of list items appearing in the aligned clause must be
9317 // array, pointer, reference to array, or reference to pointer.
9318 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
9319 const Type *Ty = QType.getTypePtrOrNull();
9320 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
9321 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
9322 << QType << getLangOpts().CPlusPlus << ERange;
9325 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9326 Diag(D->getLocation(),
9327 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9332 // OpenMP [2.8.1, simd construct, Restrictions]
9333 // A list-item cannot appear in more than one aligned clause.
9334 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
9335 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
9336 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9337 << getOpenMPClauseName(OMPC_aligned);
9341 DeclRefExpr *Ref = nullptr;
9342 if (!VD && IsOpenMPCapturedDecl(D))
9343 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9344 Vars.push_back(DefaultFunctionArrayConversion(
9345 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9349 // OpenMP [2.8.1, simd construct, Description]
9350 // The parameter of the aligned clause, alignment, must be a constant
9351 // positive integer expression.
9352 // If no optional parameter is specified, implementation-defined default
9353 // alignments for SIMD instructions on the target platforms are assumed.
9354 if (Alignment != nullptr) {
9355 ExprResult AlignResult =
9356 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9357 if (AlignResult.isInvalid())
9359 Alignment = AlignResult.get();
9364 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9365 EndLoc, Vars, Alignment);
9368 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9369 SourceLocation StartLoc,
9370 SourceLocation LParenLoc,
9371 SourceLocation EndLoc) {
9372 SmallVector<Expr *, 8> Vars;
9373 SmallVector<Expr *, 8> SrcExprs;
9374 SmallVector<Expr *, 8> DstExprs;
9375 SmallVector<Expr *, 8> AssignmentOps;
9376 for (auto &RefExpr : VarList) {
9377 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9378 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
9379 // It will be analyzed later.
9380 Vars.push_back(RefExpr);
9381 SrcExprs.push_back(nullptr);
9382 DstExprs.push_back(nullptr);
9383 AssignmentOps.push_back(nullptr);
9387 SourceLocation ELoc = RefExpr->getExprLoc();
9388 // OpenMP [2.1, C/C++]
9389 // A list item is a variable name.
9390 // OpenMP [2.14.4.1, Restrictions, p.1]
9391 // A list item that appears in a copyin clause must be threadprivate.
9392 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
9393 if (!DE || !isa<VarDecl>(DE->getDecl())) {
9394 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9395 << 0 << RefExpr->getSourceRange();
9399 Decl *D = DE->getDecl();
9400 VarDecl *VD = cast<VarDecl>(D);
9402 QualType Type = VD->getType();
9403 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9404 // It will be analyzed later.
9406 SrcExprs.push_back(nullptr);
9407 DstExprs.push_back(nullptr);
9408 AssignmentOps.push_back(nullptr);
9412 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9413 // A list item that appears in a copyin clause must be threadprivate.
9414 if (!DSAStack->isThreadPrivate(VD)) {
9415 Diag(ELoc, diag::err_omp_required_access)
9416 << getOpenMPClauseName(OMPC_copyin)
9417 << getOpenMPDirectiveName(OMPD_threadprivate);
9421 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9422 // A variable of class type (or array thereof) that appears in a
9423 // copyin clause requires an accessible, unambiguous copy assignment
9424 // operator for the class type.
9425 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
9427 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9428 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
9429 auto *PseudoSrcExpr = buildDeclRefExpr(
9430 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9432 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9433 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
9434 auto *PseudoDstExpr =
9435 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
9436 // For arrays generate assignment operation for single element and replace
9437 // it by the original array element in CodeGen.
9438 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9439 PseudoDstExpr, PseudoSrcExpr);
9440 if (AssignmentOp.isInvalid())
9442 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9443 /*DiscardedValue=*/true);
9444 if (AssignmentOp.isInvalid())
9447 DSAStack->addDSA(VD, DE, OMPC_copyin);
9449 SrcExprs.push_back(PseudoSrcExpr);
9450 DstExprs.push_back(PseudoDstExpr);
9451 AssignmentOps.push_back(AssignmentOp.get());
9457 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9458 SrcExprs, DstExprs, AssignmentOps);
9461 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9462 SourceLocation StartLoc,
9463 SourceLocation LParenLoc,
9464 SourceLocation EndLoc) {
9465 SmallVector<Expr *, 8> Vars;
9466 SmallVector<Expr *, 8> SrcExprs;
9467 SmallVector<Expr *, 8> DstExprs;
9468 SmallVector<Expr *, 8> AssignmentOps;
9469 for (auto &RefExpr : VarList) {
9470 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9471 SourceLocation ELoc;
9473 Expr *SimpleRefExpr = RefExpr;
9474 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9475 /*AllowArraySection=*/false);
9477 // It will be analyzed later.
9478 Vars.push_back(RefExpr);
9479 SrcExprs.push_back(nullptr);
9480 DstExprs.push_back(nullptr);
9481 AssignmentOps.push_back(nullptr);
9483 ValueDecl *D = Res.first;
9487 QualType Type = D->getType();
9488 auto *VD = dyn_cast<VarDecl>(D);
9490 // OpenMP [2.14.4.2, Restrictions, p.2]
9491 // A list item that appears in a copyprivate clause may not appear in a
9492 // private or firstprivate clause on the single construct.
9493 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9494 auto DVar = DSAStack->getTopDSA(D, false);
9495 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9497 Diag(ELoc, diag::err_omp_wrong_dsa)
9498 << getOpenMPClauseName(DVar.CKind)
9499 << getOpenMPClauseName(OMPC_copyprivate);
9500 ReportOriginalDSA(*this, DSAStack, D, DVar);
9504 // OpenMP [2.11.4.2, Restrictions, p.1]
9505 // All list items that appear in a copyprivate clause must be either
9506 // threadprivate or private in the enclosing context.
9507 if (DVar.CKind == OMPC_unknown) {
9508 DVar = DSAStack->getImplicitDSA(D, false);
9509 if (DVar.CKind == OMPC_shared) {
9510 Diag(ELoc, diag::err_omp_required_access)
9511 << getOpenMPClauseName(OMPC_copyprivate)
9512 << "threadprivate or private in the enclosing context";
9513 ReportOriginalDSA(*this, DSAStack, D, DVar);
9519 // Variably modified types are not supported.
9520 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
9521 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9522 << getOpenMPClauseName(OMPC_copyprivate) << Type
9523 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9526 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9527 Diag(D->getLocation(),
9528 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9533 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9534 // A variable of class type (or array thereof) that appears in a
9535 // copyin clause requires an accessible, unambiguous copy assignment
9536 // operator for the class type.
9537 Type = Context.getBaseElementType(Type.getNonReferenceType())
9538 .getUnqualifiedType();
9540 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9541 D->hasAttrs() ? &D->getAttrs() : nullptr);
9542 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
9544 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9545 D->hasAttrs() ? &D->getAttrs() : nullptr);
9546 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
9547 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9548 PseudoDstExpr, PseudoSrcExpr);
9549 if (AssignmentOp.isInvalid())
9551 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
9552 /*DiscardedValue=*/true);
9553 if (AssignmentOp.isInvalid())
9556 // No need to mark vars as copyprivate, they are already threadprivate or
9557 // implicitly private.
9558 assert(VD || IsOpenMPCapturedDecl(D));
9560 VD ? RefExpr->IgnoreParens()
9561 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
9562 SrcExprs.push_back(PseudoSrcExpr);
9563 DstExprs.push_back(PseudoDstExpr);
9564 AssignmentOps.push_back(AssignmentOp.get());
9570 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9571 Vars, SrcExprs, DstExprs, AssignmentOps);
9574 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9575 SourceLocation StartLoc,
9576 SourceLocation LParenLoc,
9577 SourceLocation EndLoc) {
9578 if (VarList.empty())
9581 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9585 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9586 SourceLocation DepLoc, SourceLocation ColonLoc,
9587 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9588 SourceLocation LParenLoc, SourceLocation EndLoc) {
9589 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
9590 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
9591 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
9592 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
9595 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
9596 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9597 DepKind == OMPC_DEPEND_sink)) {
9598 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
9599 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
9600 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9601 /*Last=*/OMPC_DEPEND_unknown, Except)
9602 << getOpenMPClauseName(OMPC_depend);
9605 SmallVector<Expr *, 8> Vars;
9606 DSAStackTy::OperatorOffsetTy OpsOffs;
9607 llvm::APSInt DepCounter(/*BitWidth=*/32);
9608 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9609 if (DepKind == OMPC_DEPEND_sink) {
9610 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9611 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9612 TotalDepCount.setIsUnsigned(/*Val=*/true);
9615 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9616 DSAStack->getParentOrderedRegionParam()) {
9617 for (auto &RefExpr : VarList) {
9618 assert(RefExpr && "NULL expr in OpenMP shared clause.");
9619 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
9620 // It will be analyzed later.
9621 Vars.push_back(RefExpr);
9625 SourceLocation ELoc = RefExpr->getExprLoc();
9626 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9627 if (DepKind == OMPC_DEPEND_sink) {
9628 if (DepCounter >= TotalDepCount) {
9629 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9633 // OpenMP [2.13.9, Summary]
9634 // depend(dependence-type : vec), where dependence-type is:
9635 // 'sink' and where vec is the iteration vector, which has the form:
9636 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9637 // where n is the value specified by the ordered clause in the loop
9638 // directive, xi denotes the loop iteration variable of the i-th nested
9639 // loop associated with the loop directive, and di is a constant
9640 // non-negative integer.
9641 if (CurContext->isDependentContext()) {
9642 // It will be analyzed later.
9643 Vars.push_back(RefExpr);
9646 SimpleExpr = SimpleExpr->IgnoreImplicit();
9647 OverloadedOperatorKind OOK = OO_None;
9648 SourceLocation OOLoc;
9649 Expr *LHS = SimpleExpr;
9650 Expr *RHS = nullptr;
9651 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9652 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9653 OOLoc = BO->getOperatorLoc();
9654 LHS = BO->getLHS()->IgnoreParenImpCasts();
9655 RHS = BO->getRHS()->IgnoreParenImpCasts();
9656 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9657 OOK = OCE->getOperator();
9658 OOLoc = OCE->getOperatorLoc();
9659 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9660 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9661 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9662 OOK = MCE->getMethodDecl()
9665 .getCXXOverloadedOperator();
9666 OOLoc = MCE->getCallee()->getExprLoc();
9667 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9668 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9670 SourceLocation ELoc;
9672 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9673 /*AllowArraySection=*/false);
9675 // It will be analyzed later.
9676 Vars.push_back(RefExpr);
9678 ValueDecl *D = Res.first;
9682 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9683 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9687 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9688 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9689 if (RHSRes.isInvalid())
9692 if (!CurContext->isDependentContext() &&
9693 DSAStack->getParentOrderedRegionParam() &&
9694 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9695 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9696 << DSAStack->getParentLoopControlVariable(
9697 DepCounter.getZExtValue());
9700 OpsOffs.push_back({RHS, OOK});
9702 // OpenMP [2.11.1.1, Restrictions, p.3]
9703 // A variable that is part of another variable (such as a field of a
9704 // structure) but is not an array element or an array section cannot
9705 // appear in a depend clause.
9706 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9707 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9708 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9709 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9710 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
9714 .getNonReferenceType()
9715 ->isPointerType() &&
9716 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
9717 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9718 << 0 << RefExpr->getSourceRange();
9722 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9725 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9726 TotalDepCount > VarList.size() &&
9727 DSAStack->getParentOrderedRegionParam()) {
9728 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9729 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9731 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9735 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9736 DepKind, DepLoc, ColonLoc, Vars);
9737 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9738 DSAStack->addDoacrossDependClause(C, OpsOffs);
9742 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9743 SourceLocation LParenLoc,
9744 SourceLocation EndLoc) {
9745 Expr *ValExpr = Device;
9747 // OpenMP [2.9.1, Restrictions]
9748 // The device expression must evaluate to a non-negative integer value.
9749 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9750 /*StrictlyPositive=*/false))
9753 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9756 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9757 DSAStackTy *Stack, CXXRecordDecl *RD) {
9758 if (!RD || RD->isInvalidDecl())
9761 auto QTy = SemaRef.Context.getRecordType(RD);
9762 if (RD->isDynamicClass()) {
9763 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9764 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9768 bool IsCorrect = true;
9769 for (auto *I : DC->decls()) {
9771 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9772 if (MD->isStatic()) {
9773 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9774 SemaRef.Diag(MD->getLocation(),
9775 diag::note_omp_static_member_in_target);
9778 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9779 if (VD->isStaticDataMember()) {
9780 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9781 SemaRef.Diag(VD->getLocation(),
9782 diag::note_omp_static_member_in_target);
9789 for (auto &I : RD->bases()) {
9790 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9791 I.getType()->getAsCXXRecordDecl()))
9797 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9798 DSAStackTy *Stack, QualType QTy) {
9800 if (QTy->isIncompleteType(&ND)) {
9801 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9803 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
9804 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
9810 /// \brief Return true if it can be proven that the provided array expression
9811 /// (array section or array subscript) does NOT specify the whole size of the
9812 /// array whose base type is \a BaseQTy.
9813 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9816 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9818 // If this is an array subscript, it refers to the whole size if the size of
9819 // the dimension is constant and equals 1. Also, an array section assumes the
9820 // format of an array subscript if no colon is used.
9821 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9822 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9823 return ATy->getSize().getSExtValue() != 1;
9824 // Size can't be evaluated statically.
9828 assert(OASE && "Expecting array section if not an array subscript.");
9829 auto *LowerBound = OASE->getLowerBound();
9830 auto *Length = OASE->getLength();
9832 // If there is a lower bound that does not evaluates to zero, we are not
9833 // covering the whole dimension.
9835 llvm::APSInt ConstLowerBound;
9836 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9837 return false; // Can't get the integer value as a constant.
9838 if (ConstLowerBound.getSExtValue())
9842 // If we don't have a length we covering the whole dimension.
9846 // If the base is a pointer, we don't have a way to get the size of the
9848 if (BaseQTy->isPointerType())
9851 // We can only check if the length is the same as the size of the dimension
9852 // if we have a constant array.
9853 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9857 llvm::APSInt ConstLength;
9858 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9859 return false; // Can't get the integer value as a constant.
9861 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
9864 // Return true if it can be proven that the provided array expression (array
9865 // section or array subscript) does NOT specify a single element of the array
9866 // whose base type is \a BaseQTy.
9867 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
9870 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9872 // An array subscript always refer to a single element. Also, an array section
9873 // assumes the format of an array subscript if no colon is used.
9874 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
9877 assert(OASE && "Expecting array section if not an array subscript.");
9878 auto *Length = OASE->getLength();
9880 // If we don't have a length we have to check if the array has unitary size
9881 // for this dimension. Also, we should always expect a length if the base type
9884 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9885 return ATy->getSize().getSExtValue() != 1;
9886 // We cannot assume anything.
9890 // Check if the length evaluates to 1.
9891 llvm::APSInt ConstLength;
9892 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9893 return false; // Can't get the integer value as a constant.
9895 return ConstLength.getSExtValue() != 1;
9898 // Return the expression of the base of the mappable expression or null if it
9899 // cannot be determined and do all the necessary checks to see if the expression
9900 // is valid as a standalone mappable expression. In the process, record all the
9901 // components of the expression.
9902 static Expr *CheckMapClauseExpressionBase(
9903 Sema &SemaRef, Expr *E,
9904 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
9905 OpenMPClauseKind CKind) {
9906 SourceLocation ELoc = E->getExprLoc();
9907 SourceRange ERange = E->getSourceRange();
9909 // The base of elements of list in a map clause have to be either:
9910 // - a reference to variable or field.
9911 // - a member expression.
9912 // - an array expression.
9914 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9915 // reference to 'r'.
9922 // #pragma omp target map (S.Arr[:12]);
9926 // We want to retrieve the member expression 'this->S';
9928 Expr *RelevantExpr = nullptr;
9930 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
9931 // If a list item is an array section, it must specify contiguous storage.
9933 // For this restriction it is sufficient that we make sure only references
9934 // to variables or fields and array expressions, and that no array sections
9935 // exist except in the rightmost expression (unless they cover the whole
9936 // dimension of the array). E.g. these would be invalid:
9938 // r.ArrS[3:5].Arr[6:7]
9942 // but these would be valid:
9943 // r.ArrS[3].Arr[6:7]
9947 bool AllowUnitySizeArraySection = true;
9948 bool AllowWholeSizeArraySection = true;
9950 while (!RelevantExpr) {
9951 E = E->IgnoreParenImpCasts();
9953 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9954 if (!isa<VarDecl>(CurE->getDecl()))
9957 RelevantExpr = CurE;
9959 // If we got a reference to a declaration, we should not expect any array
9960 // section before that.
9961 AllowUnitySizeArraySection = false;
9962 AllowWholeSizeArraySection = false;
9964 // Record the component.
9965 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
9966 CurE, CurE->getDecl()));
9970 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
9971 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9973 if (isa<CXXThisExpr>(BaseE))
9974 // We found a base expression: this->Val.
9975 RelevantExpr = CurE;
9979 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
9980 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
9981 << CurE->getSourceRange();
9985 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
9987 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
9988 // A bit-field cannot appear in a map clause.
9990 if (FD->isBitField()) {
9991 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
9992 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
9996 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9997 // If the type of a list item is a reference to a type T then the type
9998 // will be considered to be T for all purposes of this clause.
9999 QualType CurType = BaseE->getType().getNonReferenceType();
10001 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10002 // A list item cannot be a variable that is a member of a structure with
10005 if (auto *RT = CurType->getAs<RecordType>())
10006 if (RT->isUnionType()) {
10007 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10008 << CurE->getSourceRange();
10012 // If we got a member expression, we should not expect any array section
10015 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10016 // If a list item is an element of a structure, only the rightmost symbol
10017 // of the variable reference can be an array section.
10019 AllowUnitySizeArraySection = false;
10020 AllowWholeSizeArraySection = false;
10022 // Record the component.
10023 CurComponents.push_back(
10024 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
10028 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10029 E = CurE->getBase()->IgnoreParenImpCasts();
10031 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10032 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10033 << 0 << CurE->getSourceRange();
10037 // If we got an array subscript that express the whole dimension we
10038 // can have any array expressions before. If it only expressing part of
10039 // the dimension, we can only have unitary-size array expressions.
10040 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10042 AllowWholeSizeArraySection = false;
10044 // Record the component - we don't have any declaration associated.
10045 CurComponents.push_back(
10046 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
10050 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
10051 E = CurE->getBase()->IgnoreParenImpCasts();
10054 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10056 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10057 // If the type of a list item is a reference to a type T then the type
10058 // will be considered to be T for all purposes of this clause.
10059 if (CurType->isReferenceType())
10060 CurType = CurType->getPointeeType();
10062 bool IsPointer = CurType->isAnyPointerType();
10064 if (!IsPointer && !CurType->isArrayType()) {
10065 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10066 << 0 << CurE->getSourceRange();
10071 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10073 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10075 if (AllowWholeSizeArraySection) {
10076 // Any array section is currently allowed. Allowing a whole size array
10077 // section implies allowing a unity array section as well.
10079 // If this array section refers to the whole dimension we can still
10080 // accept other array sections before this one, except if the base is a
10081 // pointer. Otherwise, only unitary sections are accepted.
10082 if (NotWhole || IsPointer)
10083 AllowWholeSizeArraySection = false;
10084 } else if (AllowUnitySizeArraySection && NotUnity) {
10085 // A unity or whole array section is not allowed and that is not
10086 // compatible with the properties of the current array section.
10088 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10089 << CurE->getSourceRange();
10093 // Record the component - we don't have any declaration associated.
10094 CurComponents.push_back(
10095 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
10099 // If nothing else worked, this is not a valid map clause expression.
10101 diag::err_omp_expected_named_var_member_or_array_expression)
10106 return RelevantExpr;
10109 // Return true if expression E associated with value VD has conflicts with other
10110 // map information.
10111 static bool CheckMapConflicts(
10112 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10113 bool CurrentRegionOnly,
10114 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10115 OpenMPClauseKind CKind) {
10117 SourceLocation ELoc = E->getExprLoc();
10118 SourceRange ERange = E->getSourceRange();
10120 // In order to easily check the conflicts we need to match each component of
10121 // the expression under test with the components of the expressions that are
10122 // already in the stack.
10124 assert(!CurComponents.empty() && "Map clause expression with no components!");
10125 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
10126 "Map clause expression with unexpected base!");
10128 // Variables to help detecting enclosing problems in data environment nests.
10129 bool IsEnclosedByDataEnvironmentExpr = false;
10130 const Expr *EnclosingExpr = nullptr;
10132 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10133 VD, CurrentRegionOnly,
10134 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
10136 OpenMPClauseKind) -> bool {
10138 assert(!StackComponents.empty() &&
10139 "Map clause expression with no components!");
10140 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
10141 "Map clause expression with unexpected base!");
10143 // The whole expression in the stack.
10144 auto *RE = StackComponents.front().getAssociatedExpression();
10146 // Expressions must start from the same base. Here we detect at which
10147 // point both expressions diverge from each other and see if we can
10148 // detect if the memory referred to both expressions is contiguous and
10150 auto CI = CurComponents.rbegin();
10151 auto CE = CurComponents.rend();
10152 auto SI = StackComponents.rbegin();
10153 auto SE = StackComponents.rend();
10154 for (; CI != CE && SI != SE; ++CI, ++SI) {
10156 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10157 // At most one list item can be an array item derived from a given
10158 // variable in map clauses of the same construct.
10159 if (CurrentRegionOnly &&
10160 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10161 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10162 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10163 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10164 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
10165 diag::err_omp_multiple_array_items_in_map_clause)
10166 << CI->getAssociatedExpression()->getSourceRange();
10167 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10168 diag::note_used_here)
10169 << SI->getAssociatedExpression()->getSourceRange();
10173 // Do both expressions have the same kind?
10174 if (CI->getAssociatedExpression()->getStmtClass() !=
10175 SI->getAssociatedExpression()->getStmtClass())
10178 // Are we dealing with different variables/fields?
10179 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
10182 // Check if the extra components of the expressions in the enclosing
10183 // data environment are redundant for the current base declaration.
10184 // If they are, the maps completely overlap, which is legal.
10185 for (; SI != SE; ++SI) {
10188 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
10189 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
10190 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10191 SI->getAssociatedExpression())) {
10192 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10194 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10196 if (Type.isNull() || Type->isAnyPointerType() ||
10197 CheckArrayExpressionDoesNotReferToWholeSize(
10198 SemaRef, SI->getAssociatedExpression(), Type))
10202 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10203 // List items of map clauses in the same construct must not share
10204 // original storage.
10206 // If the expressions are exactly the same or one is a subset of the
10207 // other, it means they are sharing storage.
10208 if (CI == CE && SI == SE) {
10209 if (CurrentRegionOnly) {
10210 if (CKind == OMPC_map)
10211 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10213 assert(CKind == OMPC_to || CKind == OMPC_from);
10214 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10217 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10218 << RE->getSourceRange();
10221 // If we find the same expression in the enclosing data environment,
10223 IsEnclosedByDataEnvironmentExpr = true;
10228 QualType DerivedType =
10229 std::prev(CI)->getAssociatedDeclaration()->getType();
10230 SourceLocation DerivedLoc =
10231 std::prev(CI)->getAssociatedExpression()->getExprLoc();
10233 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10234 // If the type of a list item is a reference to a type T then the type
10235 // will be considered to be T for all purposes of this clause.
10236 DerivedType = DerivedType.getNonReferenceType();
10238 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10239 // A variable for which the type is pointer and an array section
10240 // derived from that variable must not appear as list items of map
10241 // clauses of the same construct.
10243 // Also, cover one of the cases in:
10244 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10245 // If any part of the original storage of a list item has corresponding
10246 // storage in the device data environment, all of the original storage
10247 // must have corresponding storage in the device data environment.
10249 if (DerivedType->isAnyPointerType()) {
10250 if (CI == CE || SI == SE) {
10253 diag::err_omp_pointer_mapped_along_with_derived_section)
10256 assert(CI != CE && SI != SE);
10257 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10260 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10261 << RE->getSourceRange();
10265 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10266 // List items of map clauses in the same construct must not share
10267 // original storage.
10269 // An expression is a subset of the other.
10270 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
10271 if (CKind == OMPC_map)
10272 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10274 assert(CKind == OMPC_to || CKind == OMPC_from);
10275 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10278 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10279 << RE->getSourceRange();
10283 // The current expression uses the same base as other expression in the
10284 // data environment but does not contain it completely.
10285 if (!CurrentRegionOnly && SI != SE)
10286 EnclosingExpr = RE;
10288 // The current expression is a subset of the expression in the data
10290 IsEnclosedByDataEnvironmentExpr |=
10291 (!CurrentRegionOnly && CI != CE && SI == SE);
10296 if (CurrentRegionOnly)
10299 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10300 // If any part of the original storage of a list item has corresponding
10301 // storage in the device data environment, all of the original storage must
10302 // have corresponding storage in the device data environment.
10303 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10304 // If a list item is an element of a structure, and a different element of
10305 // the structure has a corresponding list item in the device data environment
10306 // prior to a task encountering the construct associated with the map clause,
10307 // then the list item must also have a corresponding list item in the device
10308 // data environment prior to the task encountering the construct.
10310 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10312 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10314 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10315 << EnclosingExpr->getSourceRange();
10323 // Utility struct that gathers all the related lists associated with a mappable
10325 struct MappableVarListInfo final {
10326 // The list of expressions.
10327 ArrayRef<Expr *> VarList;
10328 // The list of processed expressions.
10329 SmallVector<Expr *, 16> ProcessedVarList;
10330 // The mappble components for each expression.
10331 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10332 // The base declaration of the variable.
10333 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10335 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10336 // We have a list of components and base declarations for each entry in the
10338 VarComponents.reserve(VarList.size());
10339 VarBaseDeclarations.reserve(VarList.size());
10344 // Check the validity of the provided variable list for the provided clause kind
10345 // \a CKind. In the check process the valid expressions, and mappable expression
10346 // components and variables are extracted and used to fill \a Vars,
10347 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10348 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10350 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10351 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10352 SourceLocation StartLoc,
10353 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10354 bool IsMapTypeImplicit = false) {
10355 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10356 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
10357 "Unexpected clause kind with mappable expressions!");
10359 // Keep track of the mappable components and base declarations in this clause.
10360 // Each entry in the list is going to have a list of components associated. We
10361 // record each set of the components so that we can build the clause later on.
10362 // In the end we should have the same amount of declarations and component
10365 for (auto &RE : MVLI.VarList) {
10366 assert(RE && "Null expr in omp to/from/map clause");
10367 SourceLocation ELoc = RE->getExprLoc();
10369 auto *VE = RE->IgnoreParenLValueCasts();
10371 if (VE->isValueDependent() || VE->isTypeDependent() ||
10372 VE->isInstantiationDependent() ||
10373 VE->containsUnexpandedParameterPack()) {
10374 // We can only analyze this information once the missing information is
10376 MVLI.ProcessedVarList.push_back(RE);
10380 auto *SimpleExpr = RE->IgnoreParenCasts();
10382 if (!RE->IgnoreParenImpCasts()->isLValue()) {
10384 diag::err_omp_expected_named_var_member_or_array_expression)
10385 << RE->getSourceRange();
10389 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10390 ValueDecl *CurDeclaration = nullptr;
10392 // Obtain the array or member expression bases if required. Also, fill the
10393 // components array with all the components identified in the process.
10395 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
10399 assert(!CurComponents.empty() &&
10400 "Invalid mappable expression information.");
10402 // For the following checks, we rely on the base declaration which is
10403 // expected to be associated with the last component. The declaration is
10404 // expected to be a variable or a field (if 'this' is being mapped).
10405 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10406 assert(CurDeclaration && "Null decl on map clause.");
10408 CurDeclaration->isCanonicalDecl() &&
10409 "Expecting components to have associated only canonical declarations.");
10411 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10412 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
10414 assert((VD || FD) && "Only variables or fields are expected here!");
10417 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
10418 // threadprivate variables cannot appear in a map clause.
10419 // OpenMP 4.5 [2.10.5, target update Construct]
10420 // threadprivate variables cannot appear in a from clause.
10421 if (VD && DSAS->isThreadPrivate(VD)) {
10422 auto DVar = DSAS->getTopDSA(VD, false);
10423 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10424 << getOpenMPClauseName(CKind);
10425 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
10429 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10430 // A list item cannot appear in both a map clause and a data-sharing
10431 // attribute clause on the same construct.
10433 // Check conflicts with other map clause expressions. We check the conflicts
10434 // with the current construct separately from the enclosing data
10435 // environment, because the restrictions are different. We only have to
10436 // check conflicts across regions for the map clauses.
10437 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10438 /*CurrentRegionOnly=*/true, CurComponents, CKind))
10440 if (CKind == OMPC_map &&
10441 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10442 /*CurrentRegionOnly=*/false, CurComponents, CKind))
10445 // OpenMP 4.5 [2.10.5, target update Construct]
10446 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10447 // If the type of a list item is a reference to a type T then the type will
10448 // be considered to be T for all purposes of this clause.
10449 QualType Type = CurDeclaration->getType().getNonReferenceType();
10451 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10452 // A list item in a to or from clause must have a mappable type.
10453 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10454 // A list item must have a mappable type.
10455 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10459 if (CKind == OMPC_map) {
10460 // target enter data
10461 // OpenMP [2.10.2, Restrictions, p. 99]
10462 // A map-type must be specified in all map clauses and must be either
10464 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10465 if (DKind == OMPD_target_enter_data &&
10466 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10467 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10468 << (IsMapTypeImplicit ? 1 : 0)
10469 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10470 << getOpenMPDirectiveName(DKind);
10474 // target exit_data
10475 // OpenMP [2.10.3, Restrictions, p. 102]
10476 // A map-type must be specified in all map clauses and must be either
10477 // from, release, or delete.
10478 if (DKind == OMPD_target_exit_data &&
10479 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10480 MapType == OMPC_MAP_delete)) {
10481 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10482 << (IsMapTypeImplicit ? 1 : 0)
10483 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10484 << getOpenMPDirectiveName(DKind);
10488 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10489 // A list item cannot appear in both a map clause and a data-sharing
10490 // attribute clause on the same construct
10491 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
10492 DKind == OMPD_target_teams_distribute ||
10493 DKind == OMPD_target_teams_distribute_parallel_for ||
10494 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
10495 DKind == OMPD_target_teams_distribute_simd) && VD) {
10496 auto DVar = DSAS->getTopDSA(VD, false);
10497 if (isOpenMPPrivate(DVar.CKind)) {
10498 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10499 << getOpenMPClauseName(DVar.CKind)
10500 << getOpenMPClauseName(OMPC_map)
10501 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10502 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10508 // Save the current expression.
10509 MVLI.ProcessedVarList.push_back(RE);
10511 // Store the components in the stack so that they can be used to check
10512 // against other clauses later on.
10513 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10514 /*WhereFoundClauseKind=*/OMPC_map);
10516 // Save the components and declaration to create the clause. For purposes of
10517 // the clause creation, any component list that has has base 'this' uses
10518 // null as base declaration.
10519 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10520 MVLI.VarComponents.back().append(CurComponents.begin(),
10521 CurComponents.end());
10522 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10528 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10529 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10530 SourceLocation MapLoc, SourceLocation ColonLoc,
10531 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10532 SourceLocation LParenLoc, SourceLocation EndLoc) {
10533 MappableVarListInfo MVLI(VarList);
10534 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10535 MapType, IsMapTypeImplicit);
10537 // We need to produce a map clause even if we don't have variables so that
10538 // other diagnostics related with non-existing map clauses are accurate.
10539 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10540 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10541 MVLI.VarComponents, MapTypeModifier, MapType,
10542 IsMapTypeImplicit, MapLoc);
10545 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10546 TypeResult ParsedType) {
10547 assert(ParsedType.isUsable());
10549 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10550 if (ReductionType.isNull())
10553 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10554 // A type name in a declare reduction directive cannot be a function type, an
10555 // array type, a reference type, or a type qualified with const, volatile or
10557 if (ReductionType.hasQualifiers()) {
10558 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10562 if (ReductionType->isFunctionType()) {
10563 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10566 if (ReductionType->isReferenceType()) {
10567 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10570 if (ReductionType->isArrayType()) {
10571 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10574 return ReductionType;
10577 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10578 Scope *S, DeclContext *DC, DeclarationName Name,
10579 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10580 AccessSpecifier AS, Decl *PrevDeclInScope) {
10581 SmallVector<Decl *, 8> Decls;
10582 Decls.reserve(ReductionTypes.size());
10584 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10586 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10587 // A reduction-identifier may not be re-declared in the current scope for the
10588 // same type or for a type that is compatible according to the base language
10590 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10591 OMPDeclareReductionDecl *PrevDRD = nullptr;
10592 bool InCompoundScope = true;
10593 if (S != nullptr) {
10594 // Find previous declaration with the same name not referenced in other
10596 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10598 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10599 LookupName(Lookup, S);
10600 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10601 /*AllowInlineNamespace=*/false);
10602 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10603 auto Filter = Lookup.makeFilter();
10604 while (Filter.hasNext()) {
10605 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10606 if (InCompoundScope) {
10607 auto I = UsedAsPrevious.find(PrevDecl);
10608 if (I == UsedAsPrevious.end())
10609 UsedAsPrevious[PrevDecl] = false;
10610 if (auto *D = PrevDecl->getPrevDeclInScope())
10611 UsedAsPrevious[D] = true;
10613 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10614 PrevDecl->getLocation();
10617 if (InCompoundScope) {
10618 for (auto &PrevData : UsedAsPrevious) {
10619 if (!PrevData.second) {
10620 PrevDRD = PrevData.first;
10625 } else if (PrevDeclInScope != nullptr) {
10626 auto *PrevDRDInScope = PrevDRD =
10627 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10629 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10630 PrevDRDInScope->getLocation();
10631 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10632 } while (PrevDRDInScope != nullptr);
10634 for (auto &TyData : ReductionTypes) {
10635 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10636 bool Invalid = false;
10637 if (I != PreviousRedeclTypes.end()) {
10638 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10640 Diag(I->second, diag::note_previous_definition);
10643 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10644 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10645 Name, TyData.first, PrevDRD);
10647 DRD->setAccess(AS);
10648 Decls.push_back(DRD);
10650 DRD->setInvalidDecl();
10655 return DeclGroupPtrTy::make(
10656 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10659 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10660 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10662 // Enter new function scope.
10663 PushFunctionScope();
10664 getCurFunction()->setHasBranchProtectedScope();
10665 getCurFunction()->setHasOMPDeclareReductionCombiner();
10668 PushDeclContext(S, DRD);
10672 PushExpressionEvaluationContext(PotentiallyEvaluated);
10674 QualType ReductionType = DRD->getType();
10675 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10676 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10677 // uses semantics of argument handles by value, but it should be passed by
10678 // reference. C lang does not support references, so pass all parameters as
10680 // Create 'T omp_in;' variable.
10682 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
10683 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10684 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10685 // uses semantics of argument handles by value, but it should be passed by
10686 // reference. C lang does not support references, so pass all parameters as
10688 // Create 'T omp_out;' variable.
10690 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10691 if (S != nullptr) {
10692 PushOnScopeChains(OmpInParm, S);
10693 PushOnScopeChains(OmpOutParm, S);
10695 DRD->addDecl(OmpInParm);
10696 DRD->addDecl(OmpOutParm);
10700 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10701 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10702 DiscardCleanupsInEvaluationContext();
10703 PopExpressionEvaluationContext();
10706 PopFunctionScopeInfo();
10708 if (Combiner != nullptr)
10709 DRD->setCombiner(Combiner);
10711 DRD->setInvalidDecl();
10714 void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10715 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10717 // Enter new function scope.
10718 PushFunctionScope();
10719 getCurFunction()->setHasBranchProtectedScope();
10722 PushDeclContext(S, DRD);
10726 PushExpressionEvaluationContext(PotentiallyEvaluated);
10728 QualType ReductionType = DRD->getType();
10729 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10730 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10731 // uses semantics of argument handles by value, but it should be passed by
10732 // reference. C lang does not support references, so pass all parameters as
10734 // Create 'T omp_priv;' variable.
10735 auto *OmpPrivParm =
10736 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
10737 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10738 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10739 // uses semantics of argument handles by value, but it should be passed by
10740 // reference. C lang does not support references, so pass all parameters as
10742 // Create 'T omp_orig;' variable.
10743 auto *OmpOrigParm =
10744 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
10745 if (S != nullptr) {
10746 PushOnScopeChains(OmpPrivParm, S);
10747 PushOnScopeChains(OmpOrigParm, S);
10749 DRD->addDecl(OmpPrivParm);
10750 DRD->addDecl(OmpOrigParm);
10754 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10755 Expr *Initializer) {
10756 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10757 DiscardCleanupsInEvaluationContext();
10758 PopExpressionEvaluationContext();
10761 PopFunctionScopeInfo();
10763 if (Initializer != nullptr)
10764 DRD->setInitializer(Initializer);
10766 DRD->setInvalidDecl();
10769 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10770 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10771 for (auto *D : DeclReductions.get()) {
10773 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10775 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10777 D->setInvalidDecl();
10779 return DeclReductions;
10782 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
10783 SourceLocation StartLoc,
10784 SourceLocation LParenLoc,
10785 SourceLocation EndLoc) {
10786 Expr *ValExpr = NumTeams;
10788 // OpenMP [teams Constrcut, Restrictions]
10789 // The num_teams expression must evaluate to a positive integer value.
10790 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10791 /*StrictlyPositive=*/true))
10794 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10797 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10798 SourceLocation StartLoc,
10799 SourceLocation LParenLoc,
10800 SourceLocation EndLoc) {
10801 Expr *ValExpr = ThreadLimit;
10803 // OpenMP [teams Constrcut, Restrictions]
10804 // The thread_limit expression must evaluate to a positive integer value.
10805 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10806 /*StrictlyPositive=*/true))
10809 return new (Context)
10810 OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10813 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10814 SourceLocation StartLoc,
10815 SourceLocation LParenLoc,
10816 SourceLocation EndLoc) {
10817 Expr *ValExpr = Priority;
10819 // OpenMP [2.9.1, task Constrcut]
10820 // The priority-value is a non-negative numerical scalar expression.
10821 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10822 /*StrictlyPositive=*/false))
10825 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10828 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10829 SourceLocation StartLoc,
10830 SourceLocation LParenLoc,
10831 SourceLocation EndLoc) {
10832 Expr *ValExpr = Grainsize;
10834 // OpenMP [2.9.2, taskloop Constrcut]
10835 // The parameter of the grainsize clause must be a positive integer
10837 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10838 /*StrictlyPositive=*/true))
10841 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10844 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10845 SourceLocation StartLoc,
10846 SourceLocation LParenLoc,
10847 SourceLocation EndLoc) {
10848 Expr *ValExpr = NumTasks;
10850 // OpenMP [2.9.2, taskloop Constrcut]
10851 // The parameter of the num_tasks clause must be a positive integer
10853 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
10854 /*StrictlyPositive=*/true))
10857 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10860 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10861 SourceLocation LParenLoc,
10862 SourceLocation EndLoc) {
10863 // OpenMP [2.13.2, critical construct, Description]
10864 // ... where hint-expression is an integer constant expression that evaluates
10865 // to a valid lock hint.
10866 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
10867 if (HintExpr.isInvalid())
10869 return new (Context)
10870 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
10873 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
10874 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10875 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
10876 SourceLocation EndLoc) {
10877 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
10878 std::string Values;
10880 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
10882 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10883 << Values << getOpenMPClauseName(OMPC_dist_schedule);
10886 Expr *ValExpr = ChunkSize;
10887 Stmt *HelperValStmt = nullptr;
10889 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10890 !ChunkSize->isInstantiationDependent() &&
10891 !ChunkSize->containsUnexpandedParameterPack()) {
10892 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
10894 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10895 if (Val.isInvalid())
10898 ValExpr = Val.get();
10900 // OpenMP [2.7.1, Restrictions]
10901 // chunk_size must be a loop invariant integer expression with a positive
10903 llvm::APSInt Result;
10904 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10905 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10906 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10907 << "dist_schedule" << ChunkSize->getSourceRange();
10910 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
10911 !CurContext->isDependentContext()) {
10912 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10913 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10914 HelperValStmt = buildPreInits(Context, Captures);
10919 return new (Context)
10920 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
10921 Kind, ValExpr, HelperValStmt);
10924 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
10925 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10926 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10927 SourceLocation KindLoc, SourceLocation EndLoc) {
10928 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
10929 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
10931 SourceLocation Loc;
10933 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
10934 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
10935 OMPC_DEFAULTMAP_MODIFIER_tofrom);
10938 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
10939 OMPC_DEFAULTMAP_scalar);
10943 Diag(Loc, diag::err_omp_unexpected_clause_value)
10944 << Value << getOpenMPClauseName(OMPC_defaultmap);
10948 return new (Context)
10949 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
10952 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
10953 DeclContext *CurLexicalContext = getCurLexicalContext();
10954 if (!CurLexicalContext->isFileContext() &&
10955 !CurLexicalContext->isExternCContext() &&
10956 !CurLexicalContext->isExternCXXContext()) {
10957 Diag(Loc, diag::err_omp_region_not_file_context);
10960 if (IsInOpenMPDeclareTargetContext) {
10961 Diag(Loc, diag::err_omp_enclosed_declare_target);
10965 IsInOpenMPDeclareTargetContext = true;
10969 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
10970 assert(IsInOpenMPDeclareTargetContext &&
10971 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
10973 IsInOpenMPDeclareTargetContext = false;
10976 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
10977 CXXScopeSpec &ScopeSpec,
10978 const DeclarationNameInfo &Id,
10979 OMPDeclareTargetDeclAttr::MapTypeTy MT,
10980 NamedDeclSetType &SameDirectiveDecls) {
10981 LookupResult Lookup(*this, Id, LookupOrdinaryName);
10982 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
10984 if (Lookup.isAmbiguous())
10986 Lookup.suppressDiagnostics();
10988 if (!Lookup.isSingleResult()) {
10989 if (TypoCorrection Corrected =
10990 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
10991 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
10992 CTK_ErrorRecovery)) {
10993 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
10995 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
10999 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11003 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11004 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11005 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11006 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11008 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11009 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11011 if (ASTMutationListener *ML = Context.getASTMutationListener())
11012 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11013 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11014 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11015 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11019 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11022 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11023 Sema &SemaRef, Decl *D) {
11026 Decl *LD = nullptr;
11027 if (isa<TagDecl>(D)) {
11028 LD = cast<TagDecl>(D)->getDefinition();
11029 } else if (isa<VarDecl>(D)) {
11030 LD = cast<VarDecl>(D)->getDefinition();
11032 // If this is an implicit variable that is legal and we do not need to do
11034 if (cast<VarDecl>(D)->isImplicit()) {
11035 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11036 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11038 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
11039 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11043 } else if (isa<FunctionDecl>(D)) {
11044 const FunctionDecl *FD = nullptr;
11045 if (cast<FunctionDecl>(D)->hasBody(FD))
11046 LD = const_cast<FunctionDecl *>(FD);
11048 // If the definition is associated with the current declaration in the
11049 // target region (it can be e.g. a lambda) that is legal and we do not need
11050 // to do anything else.
11052 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11053 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11055 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
11056 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11062 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11063 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11064 // Outlined declaration is not declared target.
11065 if (LD->isOutOfLine()) {
11066 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11067 SemaRef.Diag(SL, diag::note_used_here) << SR;
11069 DeclContext *DC = LD->getDeclContext();
11071 if (isa<FunctionDecl>(DC) &&
11072 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11074 DC = DC->getParent();
11079 // Is not declared in target context.
11080 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11081 SemaRef.Diag(SL, diag::note_used_here) << SR;
11083 // Mark decl as declared target to prevent further diagnostic.
11084 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11085 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11087 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
11088 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11092 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11093 Sema &SemaRef, DSAStackTy *Stack,
11095 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11097 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11102 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11103 if (!D || D->isInvalidDecl())
11105 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11106 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11107 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11108 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11109 if (DSAStack->isThreadPrivate(VD)) {
11110 Diag(SL, diag::err_omp_threadprivate_in_target);
11111 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11115 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11116 // Problem if any with var declared with incomplete type will be reported
11117 // as normal, so no need to check it here.
11118 if ((E || !VD->getType()->isIncompleteType()) &&
11119 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11120 // Mark decl as declared target to prevent further diagnostic.
11121 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
11122 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11123 Context, OMPDeclareTargetDeclAttr::MT_To);
11125 if (ASTMutationListener *ML = Context.getASTMutationListener())
11126 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
11132 // Checking declaration inside declare target region.
11133 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11134 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
11135 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11136 Context, OMPDeclareTargetDeclAttr::MT_To);
11138 if (ASTMutationListener *ML = Context.getASTMutationListener())
11139 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11143 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11146 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11147 SourceLocation StartLoc,
11148 SourceLocation LParenLoc,
11149 SourceLocation EndLoc) {
11150 MappableVarListInfo MVLI(VarList);
11151 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11152 if (MVLI.ProcessedVarList.empty())
11155 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11156 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11157 MVLI.VarComponents);
11160 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11161 SourceLocation StartLoc,
11162 SourceLocation LParenLoc,
11163 SourceLocation EndLoc) {
11164 MappableVarListInfo MVLI(VarList);
11165 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11166 if (MVLI.ProcessedVarList.empty())
11169 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11170 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11171 MVLI.VarComponents);
11174 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11175 SourceLocation StartLoc,
11176 SourceLocation LParenLoc,
11177 SourceLocation EndLoc) {
11178 MappableVarListInfo MVLI(VarList);
11179 SmallVector<Expr *, 8> PrivateCopies;
11180 SmallVector<Expr *, 8> Inits;
11182 for (auto &RefExpr : VarList) {
11183 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11184 SourceLocation ELoc;
11185 SourceRange ERange;
11186 Expr *SimpleRefExpr = RefExpr;
11187 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11189 // It will be analyzed later.
11190 MVLI.ProcessedVarList.push_back(RefExpr);
11191 PrivateCopies.push_back(nullptr);
11192 Inits.push_back(nullptr);
11194 ValueDecl *D = Res.first;
11198 QualType Type = D->getType();
11199 Type = Type.getNonReferenceType().getUnqualifiedType();
11201 auto *VD = dyn_cast<VarDecl>(D);
11203 // Item should be a pointer or reference to pointer.
11204 if (!Type->isPointerType()) {
11205 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
11206 << 0 << RefExpr->getSourceRange();
11210 // Build the private variable and the expression that refers to it.
11211 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
11212 D->hasAttrs() ? &D->getAttrs() : nullptr);
11213 if (VDPrivate->isInvalidDecl())
11216 CurContext->addDecl(VDPrivate);
11217 auto VDPrivateRefExpr = buildDeclRefExpr(
11218 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11220 // Add temporary variable to initialize the private copy of the pointer.
11222 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11223 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11224 RefExpr->getExprLoc());
11225 AddInitializerToDecl(VDPrivate,
11226 DefaultLvalueConversion(VDInitRefExpr).get(),
11227 /*DirectInit=*/false);
11229 // If required, build a capture to implement the privatization initialized
11230 // with the current list item value.
11231 DeclRefExpr *Ref = nullptr;
11233 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11234 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11235 PrivateCopies.push_back(VDPrivateRefExpr);
11236 Inits.push_back(VDInitRefExpr);
11238 // We need to add a data sharing attribute for this variable to make sure it
11239 // is correctly captured. A variable that shows up in a use_device_ptr has
11240 // similar properties of a first private variable.
11241 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11243 // Create a mappable component for the list item. List items in this clause
11244 // only need a component.
11245 MVLI.VarBaseDeclarations.push_back(D);
11246 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11247 MVLI.VarComponents.back().push_back(
11248 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
11251 if (MVLI.ProcessedVarList.empty())
11254 return OMPUseDevicePtrClause::Create(
11255 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11256 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
11259 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11260 SourceLocation StartLoc,
11261 SourceLocation LParenLoc,
11262 SourceLocation EndLoc) {
11263 MappableVarListInfo MVLI(VarList);
11264 for (auto &RefExpr : VarList) {
11265 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
11266 SourceLocation ELoc;
11267 SourceRange ERange;
11268 Expr *SimpleRefExpr = RefExpr;
11269 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11271 // It will be analyzed later.
11272 MVLI.ProcessedVarList.push_back(RefExpr);
11274 ValueDecl *D = Res.first;
11278 QualType Type = D->getType();
11279 // item should be a pointer or array or reference to pointer or array
11280 if (!Type.getNonReferenceType()->isPointerType() &&
11281 !Type.getNonReferenceType()->isArrayType()) {
11282 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11283 << 0 << RefExpr->getSourceRange();
11287 // Check if the declaration in the clause does not show up in any data
11288 // sharing attribute.
11289 auto DVar = DSAStack->getTopDSA(D, false);
11290 if (isOpenMPPrivate(DVar.CKind)) {
11291 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11292 << getOpenMPClauseName(DVar.CKind)
11293 << getOpenMPClauseName(OMPC_is_device_ptr)
11294 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11295 ReportOriginalDSA(*this, DSAStack, D, DVar);
11299 Expr *ConflictExpr;
11300 if (DSAStack->checkMappableExprComponentListsForDecl(
11301 D, /*CurrentRegionOnly=*/true,
11303 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
11304 OpenMPClauseKind) -> bool {
11305 ConflictExpr = R.front().getAssociatedExpression();
11308 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
11309 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
11310 << ConflictExpr->getSourceRange();
11314 // Store the components in the stack so that they can be used to check
11315 // against other clauses later on.
11316 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11317 DSAStack->addMappableExpressionComponents(
11318 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11320 // Record the expression we've just processed.
11321 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11323 // Create a mappable component for the list item. List items in this clause
11324 // only need a component. We use a null declaration to signal fields in
11326 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11327 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11328 "Unexpected device pointer expression!");
11329 MVLI.VarBaseDeclarations.push_back(
11330 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11331 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11332 MVLI.VarComponents.back().push_back(MC);
11335 if (MVLI.ProcessedVarList.empty())
11338 return OMPIsDevicePtrClause::Create(
11339 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11340 MVLI.VarBaseDeclarations, MVLI.VarComponents);