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(
1054 ExpressionEvaluationContext::PotentiallyEvaluated);
1057 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1058 DSAStack->setClauseParsingMode(K);
1061 void Sema::EndOpenMPClause() {
1062 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1065 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1066 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1067 // A variable of class type (or array thereof) that appears in a lastprivate
1068 // clause requires an accessible, unambiguous default constructor for the
1069 // class type, unless the list item is also specified in a firstprivate
1071 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1072 for (auto *C : D->clauses()) {
1073 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1074 SmallVector<Expr *, 8> PrivateCopies;
1075 for (auto *DE : Clause->varlists()) {
1076 if (DE->isValueDependent() || DE->isTypeDependent()) {
1077 PrivateCopies.push_back(nullptr);
1080 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1081 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1082 QualType Type = VD->getType().getNonReferenceType();
1083 auto DVar = DSAStack->getTopDSA(VD, false);
1084 if (DVar.CKind == OMPC_lastprivate) {
1085 // Generate helper private variable and initialize it with the
1086 // default value. The address of the original variable is replaced
1087 // by the address of the new private variable in CodeGen. This new
1088 // variable is not added to IdResolver, so the code in the OpenMP
1089 // region uses original variable for proper diagnostics.
1090 auto *VDPrivate = buildVarDecl(
1091 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1092 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
1093 ActOnUninitializedDecl(VDPrivate);
1094 if (VDPrivate->isInvalidDecl())
1096 PrivateCopies.push_back(buildDeclRefExpr(
1097 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1099 // The variable is also a firstprivate, so initialization sequence
1100 // for private copy is generated already.
1101 PrivateCopies.push_back(nullptr);
1104 // Set initializers to private copies if no errors were found.
1105 if (PrivateCopies.size() == Clause->varlist_size())
1106 Clause->setPrivateCopies(PrivateCopies);
1112 DiscardCleanupsInEvaluationContext();
1113 PopExpressionEvaluationContext();
1116 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1117 Expr *NumIterations, Sema &SemaRef,
1118 Scope *S, DSAStackTy *Stack);
1122 class VarDeclFilterCCC : public CorrectionCandidateCallback {
1127 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1128 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1129 NamedDecl *ND = Candidate.getCorrectionDecl();
1130 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1131 return VD->hasGlobalStorage() &&
1132 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1133 SemaRef.getCurScope());
1139 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1144 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1145 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1146 NamedDecl *ND = Candidate.getCorrectionDecl();
1147 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1148 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1149 SemaRef.getCurScope());
1157 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1158 CXXScopeSpec &ScopeSpec,
1159 const DeclarationNameInfo &Id) {
1160 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1161 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1163 if (Lookup.isAmbiguous())
1167 if (!Lookup.isSingleResult()) {
1168 if (TypoCorrection Corrected = CorrectTypo(
1169 Id, LookupOrdinaryName, CurScope, nullptr,
1170 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1171 diagnoseTypo(Corrected,
1172 PDiag(Lookup.empty()
1173 ? diag::err_undeclared_var_use_suggest
1174 : diag::err_omp_expected_var_arg_suggest)
1176 VD = Corrected.getCorrectionDeclAs<VarDecl>();
1178 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1179 : diag::err_omp_expected_var_arg)
1184 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1185 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1186 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1190 Lookup.suppressDiagnostics();
1192 // OpenMP [2.9.2, Syntax, C/C++]
1193 // Variables must be file-scope, namespace-scope, or static block-scope.
1194 if (!VD->hasGlobalStorage()) {
1195 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1196 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1198 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1199 Diag(VD->getLocation(),
1200 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1205 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1206 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
1207 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1208 // A threadprivate directive for file-scope variables must appear outside
1209 // any definition or declaration.
1210 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1211 !getCurLexicalContext()->isTranslationUnit()) {
1212 Diag(Id.getLoc(), diag::err_omp_var_scope)
1213 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1215 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1216 Diag(VD->getLocation(),
1217 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1221 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1222 // A threadprivate directive for static class member variables must appear
1223 // in the class definition, in the same scope in which the member
1224 // variables are declared.
1225 if (CanonicalVD->isStaticDataMember() &&
1226 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1227 Diag(Id.getLoc(), diag::err_omp_var_scope)
1228 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1230 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1231 Diag(VD->getLocation(),
1232 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1236 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1237 // A threadprivate directive for namespace-scope variables must appear
1238 // outside any definition or declaration other than the namespace
1239 // definition itself.
1240 if (CanonicalVD->getDeclContext()->isNamespace() &&
1241 (!getCurLexicalContext()->isFileContext() ||
1242 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1243 Diag(Id.getLoc(), diag::err_omp_var_scope)
1244 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1246 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1247 Diag(VD->getLocation(),
1248 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1252 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1253 // A threadprivate directive for static block-scope variables must appear
1254 // in the scope of the variable and not in a nested scope.
1255 if (CanonicalVD->isStaticLocal() && CurScope &&
1256 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1257 Diag(Id.getLoc(), diag::err_omp_var_scope)
1258 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1260 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1261 Diag(VD->getLocation(),
1262 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1267 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1268 // A threadprivate directive must lexically precede all references to any
1269 // of the variables in its list.
1270 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1271 Diag(Id.getLoc(), diag::err_omp_var_used)
1272 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1276 QualType ExprType = VD->getType().getNonReferenceType();
1277 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1278 SourceLocation(), VD,
1279 /*RefersToEnclosingVariableOrCapture=*/false,
1280 Id.getLoc(), ExprType, VK_LValue);
1283 Sema::DeclGroupPtrTy
1284 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1285 ArrayRef<Expr *> VarList) {
1286 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1287 CurContext->addDecl(D);
1288 return DeclGroupPtrTy::make(DeclGroupRef(D));
1294 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1298 bool VisitDeclRefExpr(const DeclRefExpr *E) {
1299 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1300 if (VD->hasLocalStorage()) {
1301 SemaRef.Diag(E->getLocStart(),
1302 diag::err_omp_local_var_in_threadprivate_init)
1303 << E->getSourceRange();
1304 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1305 << VD << VD->getSourceRange();
1311 bool VisitStmt(const Stmt *S) {
1312 for (auto Child : S->children()) {
1313 if (Child && Visit(Child))
1318 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1322 OMPThreadPrivateDecl *
1323 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1324 SmallVector<Expr *, 8> Vars;
1325 for (auto &RefExpr : VarList) {
1326 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
1327 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1328 SourceLocation ILoc = DE->getExprLoc();
1330 // Mark variable as used.
1331 VD->setReferenced();
1332 VD->markUsed(Context);
1334 QualType QType = VD->getType();
1335 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1336 // It will be analyzed later.
1341 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1342 // A threadprivate variable must not have an incomplete type.
1343 if (RequireCompleteType(ILoc, VD->getType(),
1344 diag::err_omp_threadprivate_incomplete_type)) {
1348 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1349 // A threadprivate variable must not have a reference type.
1350 if (VD->getType()->isReferenceType()) {
1351 Diag(ILoc, diag::err_omp_ref_type_arg)
1352 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1354 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1355 Diag(VD->getLocation(),
1356 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1361 // Check if this is a TLS variable. If TLS is not being supported, produce
1362 // the corresponding diagnostic.
1363 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1364 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1365 getLangOpts().OpenMPUseTLS &&
1366 getASTContext().getTargetInfo().isTLSSupported())) ||
1367 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1368 !VD->isLocalVarDecl())) {
1369 Diag(ILoc, diag::err_omp_var_thread_local)
1370 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1372 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1373 Diag(VD->getLocation(),
1374 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1379 // Check if initial value of threadprivate variable reference variable with
1380 // local storage (it is not supported by runtime).
1381 if (auto Init = VD->getAnyInitializer()) {
1382 LocalVarRefChecker Checker(*this);
1383 if (Checker.Visit(Init))
1387 Vars.push_back(RefExpr);
1388 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1389 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1390 Context, SourceRange(Loc, Loc)));
1391 if (auto *ML = Context.getASTMutationListener())
1392 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1394 OMPThreadPrivateDecl *D = nullptr;
1395 if (!Vars.empty()) {
1396 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1398 D->setAccess(AS_public);
1403 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1404 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
1405 bool IsLoopIterVar = false) {
1407 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1408 << getOpenMPClauseName(DVar.CKind);
1412 PDSA_StaticMemberShared,
1413 PDSA_StaticLocalVarShared,
1414 PDSA_LoopIterVarPrivate,
1415 PDSA_LoopIterVarLinear,
1416 PDSA_LoopIterVarLastprivate,
1417 PDSA_ConstVarShared,
1418 PDSA_GlobalVarShared,
1419 PDSA_TaskVarFirstprivate,
1420 PDSA_LocalVarPrivate,
1422 } Reason = PDSA_Implicit;
1423 bool ReportHint = false;
1424 auto ReportLoc = D->getLocation();
1425 auto *VD = dyn_cast<VarDecl>(D);
1426 if (IsLoopIterVar) {
1427 if (DVar.CKind == OMPC_private)
1428 Reason = PDSA_LoopIterVarPrivate;
1429 else if (DVar.CKind == OMPC_lastprivate)
1430 Reason = PDSA_LoopIterVarLastprivate;
1432 Reason = PDSA_LoopIterVarLinear;
1433 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1434 DVar.CKind == OMPC_firstprivate) {
1435 Reason = PDSA_TaskVarFirstprivate;
1436 ReportLoc = DVar.ImplicitDSALoc;
1437 } else if (VD && VD->isStaticLocal())
1438 Reason = PDSA_StaticLocalVarShared;
1439 else if (VD && VD->isStaticDataMember())
1440 Reason = PDSA_StaticMemberShared;
1441 else if (VD && VD->isFileVarDecl())
1442 Reason = PDSA_GlobalVarShared;
1443 else if (D->getType().isConstant(SemaRef.getASTContext()))
1444 Reason = PDSA_ConstVarShared;
1445 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1447 Reason = PDSA_LocalVarPrivate;
1449 if (Reason != PDSA_Implicit) {
1450 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1451 << Reason << ReportHint
1452 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1453 } else if (DVar.ImplicitDSALoc.isValid()) {
1454 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1455 << getOpenMPClauseName(DVar.CKind);
1460 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1465 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1466 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
1469 void VisitDeclRefExpr(DeclRefExpr *E) {
1470 if (E->isTypeDependent() || E->isValueDependent() ||
1471 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1473 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1474 // Skip internally declared variables.
1475 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1478 auto DVar = Stack->getTopDSA(VD, false);
1479 // Check if the variable has explicit DSA set and stop analysis if it so.
1483 auto ELoc = E->getExprLoc();
1484 auto DKind = Stack->getCurrentDirective();
1485 // The default(none) clause requires that each variable that is referenced
1486 // in the construct, and does not have a predetermined data-sharing
1487 // attribute, must have its data-sharing attribute explicitly determined
1488 // by being listed in a data-sharing attribute clause.
1489 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1490 isParallelOrTaskRegion(DKind) &&
1491 VarsWithInheritedDSA.count(VD) == 0) {
1492 VarsWithInheritedDSA[VD] = E;
1496 // OpenMP [2.9.3.6, Restrictions, p.2]
1497 // A list item that appears in a reduction clause of the innermost
1498 // enclosing worksharing or parallel construct may not be accessed in an
1500 DVar = Stack->hasInnermostDSA(
1501 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1502 [](OpenMPDirectiveKind K) -> bool {
1503 return isOpenMPParallelDirective(K) ||
1504 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1507 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1509 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1510 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1514 // Define implicit data-sharing attributes for task.
1515 DVar = Stack->getImplicitDSA(VD, false);
1516 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1517 !Stack->isLoopControlVariable(VD).first)
1518 ImplicitFirstprivate.push_back(E);
1521 void VisitMemberExpr(MemberExpr *E) {
1522 if (E->isTypeDependent() || E->isValueDependent() ||
1523 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1525 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1526 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1527 auto DVar = Stack->getTopDSA(FD, false);
1528 // Check if the variable has explicit DSA set and stop analysis if it
1533 auto ELoc = E->getExprLoc();
1534 auto DKind = Stack->getCurrentDirective();
1535 // OpenMP [2.9.3.6, Restrictions, p.2]
1536 // A list item that appears in a reduction clause of the innermost
1537 // enclosing worksharing or parallel construct may not be accessed in
1538 // an explicit task.
1539 DVar = Stack->hasInnermostDSA(
1540 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1541 [](OpenMPDirectiveKind K) -> bool {
1542 return isOpenMPParallelDirective(K) ||
1543 isOpenMPWorksharingDirective(K) ||
1544 isOpenMPTeamsDirective(K);
1547 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1549 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1550 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1554 // Define implicit data-sharing attributes for task.
1555 DVar = Stack->getImplicitDSA(FD, false);
1556 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1557 !Stack->isLoopControlVariable(FD).first)
1558 ImplicitFirstprivate.push_back(E);
1561 Visit(E->getBase());
1563 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
1564 for (auto *C : S->clauses()) {
1565 // Skip analysis of arguments of implicitly defined firstprivate clause
1566 // for task directives.
1567 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1568 for (auto *CC : C->children()) {
1574 void VisitStmt(Stmt *S) {
1575 for (auto *C : S->children()) {
1576 if (C && !isa<OMPExecutableDirective>(C))
1581 bool isErrorFound() { return ErrorFound; }
1582 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
1583 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
1584 return VarsWithInheritedDSA;
1587 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1588 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1592 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1595 case OMPD_parallel_for:
1596 case OMPD_parallel_for_simd:
1597 case OMPD_parallel_sections:
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_teams:
1612 case OMPD_target_parallel: {
1613 Sema::CapturedParamNameType ParamsTarget[] = {
1614 std::make_pair(StringRef(), QualType()) // __context with shared vars
1616 // Start a captured region for 'target' with no implicit parameters.
1617 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1619 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1620 QualType KmpInt32PtrTy =
1621 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1622 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
1623 std::make_pair(".global_tid.", KmpInt32PtrTy),
1624 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1625 std::make_pair(StringRef(), QualType()) // __context with shared vars
1627 // Start a captured region for 'teams' or 'parallel'. Both regions have
1628 // the same implicit parameters.
1629 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1630 ParamsTeamsOrParallel);
1641 case OMPD_taskgroup:
1642 case OMPD_distribute:
1645 case OMPD_target_data:
1647 case OMPD_target_parallel_for:
1648 case OMPD_target_parallel_for_simd:
1649 case OMPD_target_simd: {
1650 Sema::CapturedParamNameType Params[] = {
1651 std::make_pair(StringRef(), QualType()) // __context with shared vars
1653 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1658 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1659 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1660 FunctionProtoType::ExtProtoInfo EPI;
1661 EPI.Variadic = true;
1662 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1663 Sema::CapturedParamNameType Params[] = {
1664 std::make_pair(".global_tid.", KmpInt32Ty),
1665 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1666 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1667 std::make_pair(".copy_fn.",
1668 Context.getPointerType(CopyFnType).withConst()),
1669 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1670 std::make_pair(StringRef(), QualType()) // __context with shared vars
1672 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1674 // Mark this captured region as inlined, because we don't use outlined
1675 // function directly.
1676 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1677 AlwaysInlineAttr::CreateImplicit(
1678 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1682 case OMPD_taskloop_simd: {
1683 QualType KmpInt32Ty =
1684 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1685 QualType KmpUInt64Ty =
1686 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1687 QualType KmpInt64Ty =
1688 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1689 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1690 FunctionProtoType::ExtProtoInfo EPI;
1691 EPI.Variadic = true;
1692 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1693 Sema::CapturedParamNameType Params[] = {
1694 std::make_pair(".global_tid.", KmpInt32Ty),
1695 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1696 std::make_pair(".privates.",
1697 Context.VoidPtrTy.withConst().withRestrict()),
1700 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1701 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1702 std::make_pair(".lb.", KmpUInt64Ty),
1703 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1704 std::make_pair(".liter.", KmpInt32Ty),
1705 std::make_pair(StringRef(), QualType()) // __context with shared vars
1707 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1709 // Mark this captured region as inlined, because we don't use outlined
1710 // function directly.
1711 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1712 AlwaysInlineAttr::CreateImplicit(
1713 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1716 case OMPD_distribute_parallel_for_simd:
1717 case OMPD_distribute_simd:
1718 case OMPD_distribute_parallel_for:
1719 case OMPD_teams_distribute:
1720 case OMPD_teams_distribute_simd:
1721 case OMPD_teams_distribute_parallel_for_simd:
1722 case OMPD_teams_distribute_parallel_for:
1723 case OMPD_target_teams_distribute:
1724 case OMPD_target_teams_distribute_parallel_for:
1725 case OMPD_target_teams_distribute_parallel_for_simd:
1726 case OMPD_target_teams_distribute_simd: {
1727 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1728 QualType KmpInt32PtrTy =
1729 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1730 Sema::CapturedParamNameType Params[] = {
1731 std::make_pair(".global_tid.", KmpInt32PtrTy),
1732 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1733 std::make_pair(".previous.lb.", Context.getSizeType()),
1734 std::make_pair(".previous.ub.", Context.getSizeType()),
1735 std::make_pair(StringRef(), QualType()) // __context with shared vars
1737 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1741 case OMPD_threadprivate:
1742 case OMPD_taskyield:
1745 case OMPD_cancellation_point:
1748 case OMPD_target_enter_data:
1749 case OMPD_target_exit_data:
1750 case OMPD_declare_reduction:
1751 case OMPD_declare_simd:
1752 case OMPD_declare_target:
1753 case OMPD_end_declare_target:
1754 case OMPD_target_update:
1755 llvm_unreachable("OpenMP Directive is not allowed");
1757 llvm_unreachable("Unknown OpenMP directive");
1761 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
1762 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1763 getOpenMPCaptureRegions(CaptureRegions, DKind);
1764 return CaptureRegions.size();
1767 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
1768 Expr *CaptureExpr, bool WithInit,
1769 bool AsExpression) {
1770 assert(CaptureExpr);
1771 ASTContext &C = S.getASTContext();
1772 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
1773 QualType Ty = Init->getType();
1774 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1775 if (S.getLangOpts().CPlusPlus)
1776 Ty = C.getLValueReferenceType(Ty);
1778 Ty = C.getPointerType(Ty);
1780 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1781 if (!Res.isUsable())
1787 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1788 CaptureExpr->getLocStart());
1790 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
1791 S.CurContext->addHiddenDecl(CED);
1792 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
1796 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1798 OMPCapturedExprDecl *CD;
1799 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1800 CD = cast<OMPCapturedExprDecl>(VD);
1802 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1803 /*AsExpression=*/false);
1804 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1805 CaptureExpr->getExprLoc());
1808 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1811 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1812 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1813 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1814 CaptureExpr->getExprLoc());
1816 ExprResult Res = Ref;
1817 if (!S.getLangOpts().CPlusPlus &&
1818 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1819 Ref->getType()->isPointerType())
1820 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1821 if (!Res.isUsable())
1823 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
1827 // OpenMP directives parsed in this section are represented as a
1828 // CapturedStatement with an associated statement. If a syntax error
1829 // is detected during the parsing of the associated statement, the
1830 // compiler must abort processing and close the CapturedStatement.
1832 // Combined directives such as 'target parallel' have more than one
1833 // nested CapturedStatements. This RAII ensures that we unwind out
1834 // of all the nested CapturedStatements when an error is found.
1835 class CaptureRegionUnwinderRAII {
1839 OpenMPDirectiveKind DKind;
1842 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
1843 OpenMPDirectiveKind DKind)
1844 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
1845 ~CaptureRegionUnwinderRAII() {
1847 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
1848 while (--ThisCaptureLevel >= 0)
1849 S.ActOnCapturedRegionError();
1855 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1856 ArrayRef<OMPClause *> Clauses) {
1857 bool ErrorFound = false;
1858 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
1859 *this, ErrorFound, DSAStack->getCurrentDirective());
1860 if (!S.isUsable()) {
1865 OMPOrderedClause *OC = nullptr;
1866 OMPScheduleClause *SC = nullptr;
1867 SmallVector<OMPLinearClause *, 4> LCs;
1868 SmallVector<OMPClauseWithPreInit *, 8> PICs;
1869 // This is required for proper codegen.
1870 for (auto *Clause : Clauses) {
1871 if (isOpenMPPrivate(Clause->getClauseKind()) ||
1872 Clause->getClauseKind() == OMPC_copyprivate ||
1873 (getLangOpts().OpenMPUseTLS &&
1874 getASTContext().getTargetInfo().isTLSSupported() &&
1875 Clause->getClauseKind() == OMPC_copyin)) {
1876 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
1877 // Mark all variables in private list clauses as used in inner region.
1878 for (auto *VarRef : Clause->children()) {
1879 if (auto *E = cast_or_null<Expr>(VarRef)) {
1880 MarkDeclarationsReferencedInExpr(E);
1883 DSAStack->setForceVarCapturing(/*V=*/false);
1884 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
1885 if (auto *C = OMPClauseWithPreInit::get(Clause))
1887 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1888 if (auto *E = C->getPostUpdateExpr())
1889 MarkDeclarationsReferencedInExpr(E);
1892 if (Clause->getClauseKind() == OMPC_schedule)
1893 SC = cast<OMPScheduleClause>(Clause);
1894 else if (Clause->getClauseKind() == OMPC_ordered)
1895 OC = cast<OMPOrderedClause>(Clause);
1896 else if (Clause->getClauseKind() == OMPC_linear)
1897 LCs.push_back(cast<OMPLinearClause>(Clause));
1899 // OpenMP, 2.7.1 Loop Construct, Restrictions
1900 // The nonmonotonic modifier cannot be specified if an ordered clause is
1903 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1904 SC->getSecondScheduleModifier() ==
1905 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1907 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1908 ? SC->getFirstScheduleModifierLoc()
1909 : SC->getSecondScheduleModifierLoc(),
1910 diag::err_omp_schedule_nonmonotonic_ordered)
1911 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1914 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1915 for (auto *C : LCs) {
1916 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1917 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1921 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1922 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1923 OC->getNumForLoops()) {
1924 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1925 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1932 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1933 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
1934 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
1935 // Mark all variables in private list clauses as used in inner region.
1936 // Required for proper codegen of combined directives.
1937 // TODO: add processing for other clauses.
1938 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
1939 for (auto *C : PICs) {
1940 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
1941 // Find the particular capture region for the clause if the
1942 // directive is a combined one with multiple capture regions.
1943 // If the directive is not a combined one, the capture region
1944 // associated with the clause is OMPD_unknown and is generated
1946 if (CaptureRegion == ThisCaptureRegion ||
1947 CaptureRegion == OMPD_unknown) {
1948 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1949 for (auto *D : DS->decls())
1950 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1955 SR = ActOnCapturedRegionEnd(SR.get());
1960 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
1961 OpenMPDirectiveKind CancelRegion,
1962 SourceLocation StartLoc) {
1963 // CancelRegion is only needed for cancel and cancellation_point.
1964 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
1967 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
1968 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
1971 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
1972 << getOpenMPDirectiveName(CancelRegion);
1976 static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1977 OpenMPDirectiveKind CurrentRegion,
1978 const DeclarationNameInfo &CurrentName,
1979 OpenMPDirectiveKind CancelRegion,
1980 SourceLocation StartLoc) {
1981 if (Stack->getCurScope()) {
1982 auto ParentRegion = Stack->getParentDirective();
1983 auto OffendingRegion = ParentRegion;
1984 bool NestingProhibited = false;
1985 bool CloseNesting = true;
1986 bool OrphanSeen = false;
1989 ShouldBeInParallelRegion,
1990 ShouldBeInOrderedRegion,
1991 ShouldBeInTargetRegion,
1992 ShouldBeInTeamsRegion
1993 } Recommend = NoRecommend;
1994 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
1995 // OpenMP [2.16, Nesting of Regions]
1996 // OpenMP constructs may not be nested inside a simd region.
1997 // OpenMP [2.8.1,simd Construct, Restrictions]
1998 // An ordered construct with the simd clause is the only OpenMP
1999 // construct that can appear in the simd region.
2000 // Allowing a SIMD construct nested in another SIMD construct is an
2001 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2003 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2004 ? diag::err_omp_prohibited_region_simd
2005 : diag::warn_omp_nesting_simd);
2006 return CurrentRegion != OMPD_simd;
2008 if (ParentRegion == OMPD_atomic) {
2009 // OpenMP [2.16, Nesting of Regions]
2010 // OpenMP constructs may not be nested inside an atomic region.
2011 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2014 if (CurrentRegion == OMPD_section) {
2015 // OpenMP [2.7.2, sections Construct, Restrictions]
2016 // Orphaned section directives are prohibited. That is, the section
2017 // directives must appear within the sections construct and must not be
2018 // encountered elsewhere in the sections region.
2019 if (ParentRegion != OMPD_sections &&
2020 ParentRegion != OMPD_parallel_sections) {
2021 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2022 << (ParentRegion != OMPD_unknown)
2023 << getOpenMPDirectiveName(ParentRegion);
2028 // Allow some constructs (except teams) to be orphaned (they could be
2029 // used in functions, called from OpenMP regions with the required
2031 if (ParentRegion == OMPD_unknown &&
2032 !isOpenMPNestingTeamsDirective(CurrentRegion))
2034 if (CurrentRegion == OMPD_cancellation_point ||
2035 CurrentRegion == OMPD_cancel) {
2036 // OpenMP [2.16, Nesting of Regions]
2037 // A cancellation point construct for which construct-type-clause is
2038 // taskgroup must be nested inside a task construct. A cancellation
2039 // point construct for which construct-type-clause is not taskgroup must
2040 // be closely nested inside an OpenMP construct that matches the type
2041 // specified in construct-type-clause.
2042 // A cancel construct for which construct-type-clause is taskgroup must be
2043 // nested inside a task construct. A cancel construct for which
2044 // construct-type-clause is not taskgroup must be closely nested inside an
2045 // OpenMP construct that matches the type specified in
2046 // construct-type-clause.
2048 !((CancelRegion == OMPD_parallel &&
2049 (ParentRegion == OMPD_parallel ||
2050 ParentRegion == OMPD_target_parallel)) ||
2051 (CancelRegion == OMPD_for &&
2052 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2053 ParentRegion == OMPD_target_parallel_for)) ||
2054 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2055 (CancelRegion == OMPD_sections &&
2056 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2057 ParentRegion == OMPD_parallel_sections)));
2058 } else if (CurrentRegion == OMPD_master) {
2059 // OpenMP [2.16, Nesting of Regions]
2060 // A master region may not be closely nested inside a worksharing,
2061 // atomic, or explicit task region.
2062 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2063 isOpenMPTaskingDirective(ParentRegion);
2064 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2065 // OpenMP [2.16, Nesting of Regions]
2066 // A critical region may not be nested (closely or otherwise) inside a
2067 // critical region with the same name. Note that this restriction is not
2068 // sufficient to prevent deadlock.
2069 SourceLocation PreviousCriticalLoc;
2070 bool DeadLock = Stack->hasDirective(
2071 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2072 const DeclarationNameInfo &DNI,
2073 SourceLocation Loc) -> bool {
2074 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2075 PreviousCriticalLoc = Loc;
2080 false /* skip top directive */);
2082 SemaRef.Diag(StartLoc,
2083 diag::err_omp_prohibited_region_critical_same_name)
2084 << CurrentName.getName();
2085 if (PreviousCriticalLoc.isValid())
2086 SemaRef.Diag(PreviousCriticalLoc,
2087 diag::note_omp_previous_critical_region);
2090 } else if (CurrentRegion == OMPD_barrier) {
2091 // OpenMP [2.16, Nesting of Regions]
2092 // A barrier region may not be closely nested inside a worksharing,
2093 // explicit task, critical, ordered, atomic, or master region.
2094 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2095 isOpenMPTaskingDirective(ParentRegion) ||
2096 ParentRegion == OMPD_master ||
2097 ParentRegion == OMPD_critical ||
2098 ParentRegion == OMPD_ordered;
2099 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
2100 !isOpenMPParallelDirective(CurrentRegion) &&
2101 !isOpenMPTeamsDirective(CurrentRegion)) {
2102 // OpenMP [2.16, Nesting of Regions]
2103 // A worksharing region may not be closely nested inside a worksharing,
2104 // explicit task, critical, ordered, atomic, or master region.
2105 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2106 isOpenMPTaskingDirective(ParentRegion) ||
2107 ParentRegion == OMPD_master ||
2108 ParentRegion == OMPD_critical ||
2109 ParentRegion == OMPD_ordered;
2110 Recommend = ShouldBeInParallelRegion;
2111 } else if (CurrentRegion == OMPD_ordered) {
2112 // OpenMP [2.16, Nesting of Regions]
2113 // An ordered region may not be closely nested inside a critical,
2114 // atomic, or explicit task region.
2115 // An ordered region must be closely nested inside a loop region (or
2116 // parallel loop region) with an ordered clause.
2117 // OpenMP [2.8.1,simd Construct, Restrictions]
2118 // An ordered construct with the simd clause is the only OpenMP construct
2119 // that can appear in the simd region.
2120 NestingProhibited = ParentRegion == OMPD_critical ||
2121 isOpenMPTaskingDirective(ParentRegion) ||
2122 !(isOpenMPSimdDirective(ParentRegion) ||
2123 Stack->isParentOrderedRegion());
2124 Recommend = ShouldBeInOrderedRegion;
2125 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
2126 // OpenMP [2.16, Nesting of Regions]
2127 // If specified, a teams construct must be contained within a target
2129 NestingProhibited = ParentRegion != OMPD_target;
2130 OrphanSeen = ParentRegion == OMPD_unknown;
2131 Recommend = ShouldBeInTargetRegion;
2132 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2134 if (!NestingProhibited &&
2135 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2136 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2137 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
2138 // OpenMP [2.16, Nesting of Regions]
2139 // distribute, parallel, parallel sections, parallel workshare, and the
2140 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2141 // constructs that can be closely nested in the teams region.
2142 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2143 !isOpenMPDistributeDirective(CurrentRegion);
2144 Recommend = ShouldBeInParallelRegion;
2146 if (!NestingProhibited &&
2147 isOpenMPNestingDistributeDirective(CurrentRegion)) {
2148 // OpenMP 4.5 [2.17 Nesting of Regions]
2149 // The region associated with the distribute construct must be strictly
2150 // nested inside a teams region
2152 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
2153 Recommend = ShouldBeInTeamsRegion;
2155 if (!NestingProhibited &&
2156 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2157 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2158 // OpenMP 4.5 [2.17 Nesting of Regions]
2159 // If a target, target update, target data, target enter data, or
2160 // target exit data construct is encountered during execution of a
2161 // target region, the behavior is unspecified.
2162 NestingProhibited = Stack->hasDirective(
2163 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2164 SourceLocation) -> bool {
2165 if (isOpenMPTargetExecutionDirective(K)) {
2166 OffendingRegion = K;
2171 false /* don't skip top directive */);
2172 CloseNesting = false;
2174 if (NestingProhibited) {
2176 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2177 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2179 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2180 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2181 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2189 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2190 ArrayRef<OMPClause *> Clauses,
2191 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2192 bool ErrorFound = false;
2193 unsigned NamedModifiersNumber = 0;
2194 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2196 SmallVector<SourceLocation, 4> NameModifierLoc;
2197 for (const auto *C : Clauses) {
2198 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2199 // At most one if clause without a directive-name-modifier can appear on
2201 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2202 if (FoundNameModifiers[CurNM]) {
2203 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2204 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2205 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2207 } else if (CurNM != OMPD_unknown) {
2208 NameModifierLoc.push_back(IC->getNameModifierLoc());
2209 ++NamedModifiersNumber;
2211 FoundNameModifiers[CurNM] = IC;
2212 if (CurNM == OMPD_unknown)
2214 // Check if the specified name modifier is allowed for the current
2216 // At most one if clause with the particular directive-name-modifier can
2217 // appear on the directive.
2218 bool MatchFound = false;
2219 for (auto NM : AllowedNameModifiers) {
2226 S.Diag(IC->getNameModifierLoc(),
2227 diag::err_omp_wrong_if_directive_name_modifier)
2228 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2233 // If any if clause on the directive includes a directive-name-modifier then
2234 // all if clauses on the directive must include a directive-name-modifier.
2235 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2236 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2237 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2238 diag::err_omp_no_more_if_clause);
2241 std::string Sep(", ");
2242 unsigned AllowedCnt = 0;
2243 unsigned TotalAllowedNum =
2244 AllowedNameModifiers.size() - NamedModifiersNumber;
2245 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2247 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2248 if (!FoundNameModifiers[NM]) {
2250 Values += getOpenMPDirectiveName(NM);
2252 if (AllowedCnt + 2 == TotalAllowedNum)
2254 else if (AllowedCnt + 1 != TotalAllowedNum)
2259 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2260 diag::err_omp_unnamed_if_clause)
2261 << (TotalAllowedNum > 1) << Values;
2263 for (auto Loc : NameModifierLoc) {
2264 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2271 StmtResult Sema::ActOnOpenMPExecutableDirective(
2272 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2273 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2274 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
2275 StmtResult Res = StmtError();
2276 // First check CancelRegion which is then used in checkNestingOfRegions.
2277 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2278 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2282 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
2283 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
2284 bool ErrorFound = false;
2285 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
2287 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2289 // Check default data sharing attributes for referenced variables.
2290 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2291 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2293 while (--ThisCaptureLevel >= 0)
2294 S = cast<CapturedStmt>(S)->getCapturedStmt();
2295 DSAChecker.Visit(S);
2296 if (DSAChecker.isErrorFound())
2298 // Generate list of implicitly defined firstprivate variables.
2299 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
2301 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2302 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2303 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2304 SourceLocation(), SourceLocation())) {
2305 ClausesWithImplicit.push_back(Implicit);
2306 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2307 DSAChecker.getImplicitFirstprivate().size();
2313 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
2316 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2318 AllowedNameModifiers.push_back(OMPD_parallel);
2321 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2322 VarsWithInheritedDSA);
2325 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2326 VarsWithInheritedDSA);
2329 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2330 EndLoc, VarsWithInheritedDSA);
2333 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2337 assert(ClausesWithImplicit.empty() &&
2338 "No clauses are allowed for 'omp section' directive");
2339 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2342 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2346 assert(ClausesWithImplicit.empty() &&
2347 "No clauses are allowed for 'omp master' directive");
2348 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2351 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2354 case OMPD_parallel_for:
2355 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2356 EndLoc, VarsWithInheritedDSA);
2357 AllowedNameModifiers.push_back(OMPD_parallel);
2359 case OMPD_parallel_for_simd:
2360 Res = ActOnOpenMPParallelForSimdDirective(
2361 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2362 AllowedNameModifiers.push_back(OMPD_parallel);
2364 case OMPD_parallel_sections:
2365 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2367 AllowedNameModifiers.push_back(OMPD_parallel);
2371 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2372 AllowedNameModifiers.push_back(OMPD_task);
2374 case OMPD_taskyield:
2375 assert(ClausesWithImplicit.empty() &&
2376 "No clauses are allowed for 'omp taskyield' directive");
2377 assert(AStmt == nullptr &&
2378 "No associated statement allowed for 'omp taskyield' directive");
2379 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2382 assert(ClausesWithImplicit.empty() &&
2383 "No clauses are allowed for 'omp barrier' directive");
2384 assert(AStmt == nullptr &&
2385 "No associated statement allowed for 'omp barrier' directive");
2386 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2389 assert(ClausesWithImplicit.empty() &&
2390 "No clauses are allowed for 'omp taskwait' directive");
2391 assert(AStmt == nullptr &&
2392 "No associated statement allowed for 'omp taskwait' directive");
2393 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2395 case OMPD_taskgroup:
2396 assert(ClausesWithImplicit.empty() &&
2397 "No clauses are allowed for 'omp taskgroup' directive");
2398 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2401 assert(AStmt == nullptr &&
2402 "No associated statement allowed for 'omp flush' directive");
2403 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2406 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2410 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2415 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2418 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2420 AllowedNameModifiers.push_back(OMPD_target);
2422 case OMPD_target_parallel:
2423 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2425 AllowedNameModifiers.push_back(OMPD_target);
2426 AllowedNameModifiers.push_back(OMPD_parallel);
2428 case OMPD_target_parallel_for:
2429 Res = ActOnOpenMPTargetParallelForDirective(
2430 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2431 AllowedNameModifiers.push_back(OMPD_target);
2432 AllowedNameModifiers.push_back(OMPD_parallel);
2434 case OMPD_cancellation_point:
2435 assert(ClausesWithImplicit.empty() &&
2436 "No clauses are allowed for 'omp cancellation point' directive");
2437 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2438 "cancellation point' directive");
2439 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2442 assert(AStmt == nullptr &&
2443 "No associated statement allowed for 'omp cancel' directive");
2444 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2446 AllowedNameModifiers.push_back(OMPD_cancel);
2448 case OMPD_target_data:
2449 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2451 AllowedNameModifiers.push_back(OMPD_target_data);
2453 case OMPD_target_enter_data:
2454 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2456 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2458 case OMPD_target_exit_data:
2459 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2461 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2464 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2465 EndLoc, VarsWithInheritedDSA);
2466 AllowedNameModifiers.push_back(OMPD_taskloop);
2468 case OMPD_taskloop_simd:
2469 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2470 EndLoc, VarsWithInheritedDSA);
2471 AllowedNameModifiers.push_back(OMPD_taskloop);
2473 case OMPD_distribute:
2474 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2475 EndLoc, VarsWithInheritedDSA);
2477 case OMPD_target_update:
2478 assert(!AStmt && "Statement is not allowed for target update");
2480 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2481 AllowedNameModifiers.push_back(OMPD_target_update);
2483 case OMPD_distribute_parallel_for:
2484 Res = ActOnOpenMPDistributeParallelForDirective(
2485 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2486 AllowedNameModifiers.push_back(OMPD_parallel);
2488 case OMPD_distribute_parallel_for_simd:
2489 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2490 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2491 AllowedNameModifiers.push_back(OMPD_parallel);
2493 case OMPD_distribute_simd:
2494 Res = ActOnOpenMPDistributeSimdDirective(
2495 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2497 case OMPD_target_parallel_for_simd:
2498 Res = ActOnOpenMPTargetParallelForSimdDirective(
2499 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2500 AllowedNameModifiers.push_back(OMPD_target);
2501 AllowedNameModifiers.push_back(OMPD_parallel);
2503 case OMPD_target_simd:
2504 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2505 EndLoc, VarsWithInheritedDSA);
2506 AllowedNameModifiers.push_back(OMPD_target);
2508 case OMPD_teams_distribute:
2509 Res = ActOnOpenMPTeamsDistributeDirective(
2510 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2512 case OMPD_teams_distribute_simd:
2513 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2514 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2516 case OMPD_teams_distribute_parallel_for_simd:
2517 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2518 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2519 AllowedNameModifiers.push_back(OMPD_parallel);
2521 case OMPD_teams_distribute_parallel_for:
2522 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2523 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2524 AllowedNameModifiers.push_back(OMPD_parallel);
2526 case OMPD_target_teams:
2527 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2529 AllowedNameModifiers.push_back(OMPD_target);
2531 case OMPD_target_teams_distribute:
2532 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2533 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2534 AllowedNameModifiers.push_back(OMPD_target);
2536 case OMPD_target_teams_distribute_parallel_for:
2537 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2538 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2539 AllowedNameModifiers.push_back(OMPD_target);
2540 AllowedNameModifiers.push_back(OMPD_parallel);
2542 case OMPD_target_teams_distribute_parallel_for_simd:
2543 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2544 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2545 AllowedNameModifiers.push_back(OMPD_target);
2546 AllowedNameModifiers.push_back(OMPD_parallel);
2548 case OMPD_target_teams_distribute_simd:
2549 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2550 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2551 AllowedNameModifiers.push_back(OMPD_target);
2553 case OMPD_declare_target:
2554 case OMPD_end_declare_target:
2555 case OMPD_threadprivate:
2556 case OMPD_declare_reduction:
2557 case OMPD_declare_simd:
2558 llvm_unreachable("OpenMP Directive is not allowed");
2560 llvm_unreachable("Unknown OpenMP directive");
2563 for (auto P : VarsWithInheritedDSA) {
2564 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2565 << P.first << P.second->getSourceRange();
2567 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2569 if (!AllowedNameModifiers.empty())
2570 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2578 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2579 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
2580 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
2581 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2582 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
2583 assert(Aligneds.size() == Alignments.size());
2584 assert(Linears.size() == LinModifiers.size());
2585 assert(Linears.size() == Steps.size());
2586 if (!DG || DG.get().isNull())
2587 return DeclGroupPtrTy();
2589 if (!DG.get().isSingleDecl()) {
2590 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
2593 auto *ADecl = DG.get().getSingleDecl();
2594 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2595 ADecl = FTD->getTemplatedDecl();
2597 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2599 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
2600 return DeclGroupPtrTy();
2603 // OpenMP [2.8.2, declare simd construct, Description]
2604 // The parameter of the simdlen clause must be a constant positive integer
2608 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
2609 // OpenMP [2.8.2, declare simd construct, Description]
2610 // The special this pointer can be used as if was one of the arguments to the
2611 // function in any of the linear, aligned, or uniform clauses.
2612 // The uniform clause declares one or more arguments to have an invariant
2613 // value for all concurrent invocations of the function in the execution of a
2614 // single SIMD loop.
2615 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2616 Expr *UniformedLinearThis = nullptr;
2617 for (auto *E : Uniforms) {
2618 E = E->IgnoreParenImpCasts();
2619 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2620 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2621 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2622 FD->getParamDecl(PVD->getFunctionScopeIndex())
2623 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2624 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
2627 if (isa<CXXThisExpr>(E)) {
2628 UniformedLinearThis = E;
2631 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2632 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2634 // OpenMP [2.8.2, declare simd construct, Description]
2635 // The aligned clause declares that the object to which each list item points
2636 // is aligned to the number of bytes expressed in the optional parameter of
2637 // the aligned clause.
2638 // The special this pointer can be used as if was one of the arguments to the
2639 // function in any of the linear, aligned, or uniform clauses.
2640 // The type of list items appearing in the aligned clause must be array,
2641 // pointer, reference to array, or reference to pointer.
2642 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2643 Expr *AlignedThis = nullptr;
2644 for (auto *E : Aligneds) {
2645 E = E->IgnoreParenImpCasts();
2646 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2647 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2648 auto *CanonPVD = PVD->getCanonicalDecl();
2649 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2650 FD->getParamDecl(PVD->getFunctionScopeIndex())
2651 ->getCanonicalDecl() == CanonPVD) {
2652 // OpenMP [2.8.1, simd construct, Restrictions]
2653 // A list-item cannot appear in more than one aligned clause.
2654 if (AlignedArgs.count(CanonPVD) > 0) {
2655 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2656 << 1 << E->getSourceRange();
2657 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2658 diag::note_omp_explicit_dsa)
2659 << getOpenMPClauseName(OMPC_aligned);
2662 AlignedArgs[CanonPVD] = E;
2663 QualType QTy = PVD->getType()
2664 .getNonReferenceType()
2665 .getUnqualifiedType()
2666 .getCanonicalType();
2667 const Type *Ty = QTy.getTypePtrOrNull();
2668 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2669 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2670 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2671 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2676 if (isa<CXXThisExpr>(E)) {
2678 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2679 << 2 << E->getSourceRange();
2680 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2681 << getOpenMPClauseName(OMPC_aligned);
2686 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2687 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2689 // The optional parameter of the aligned clause, alignment, must be a constant
2690 // positive integer expression. If no optional parameter is specified,
2691 // implementation-defined default alignments for SIMD instructions on the
2692 // target platforms are assumed.
2693 SmallVector<Expr *, 4> NewAligns;
2694 for (auto *E : Alignments) {
2697 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2698 NewAligns.push_back(Align.get());
2700 // OpenMP [2.8.2, declare simd construct, Description]
2701 // The linear clause declares one or more list items to be private to a SIMD
2702 // lane and to have a linear relationship with respect to the iteration space
2704 // The special this pointer can be used as if was one of the arguments to the
2705 // function in any of the linear, aligned, or uniform clauses.
2706 // When a linear-step expression is specified in a linear clause it must be
2707 // either a constant integer expression or an integer-typed parameter that is
2708 // specified in a uniform clause on the directive.
2709 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2710 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2711 auto MI = LinModifiers.begin();
2712 for (auto *E : Linears) {
2713 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2715 E = E->IgnoreParenImpCasts();
2716 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2717 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2718 auto *CanonPVD = PVD->getCanonicalDecl();
2719 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2720 FD->getParamDecl(PVD->getFunctionScopeIndex())
2721 ->getCanonicalDecl() == CanonPVD) {
2722 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2723 // A list-item cannot appear in more than one linear clause.
2724 if (LinearArgs.count(CanonPVD) > 0) {
2725 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2726 << getOpenMPClauseName(OMPC_linear)
2727 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2728 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2729 diag::note_omp_explicit_dsa)
2730 << getOpenMPClauseName(OMPC_linear);
2733 // Each argument can appear in at most one uniform or linear clause.
2734 if (UniformedArgs.count(CanonPVD) > 0) {
2735 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2736 << getOpenMPClauseName(OMPC_linear)
2737 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2738 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2739 diag::note_omp_explicit_dsa)
2740 << getOpenMPClauseName(OMPC_uniform);
2743 LinearArgs[CanonPVD] = E;
2744 if (E->isValueDependent() || E->isTypeDependent() ||
2745 E->isInstantiationDependent() ||
2746 E->containsUnexpandedParameterPack())
2748 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2749 PVD->getOriginalType());
2753 if (isa<CXXThisExpr>(E)) {
2754 if (UniformedLinearThis) {
2755 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2756 << getOpenMPClauseName(OMPC_linear)
2757 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2758 << E->getSourceRange();
2759 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2760 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2764 UniformedLinearThis = E;
2765 if (E->isValueDependent() || E->isTypeDependent() ||
2766 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2768 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2772 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2773 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2775 Expr *Step = nullptr;
2776 Expr *NewStep = nullptr;
2777 SmallVector<Expr *, 4> NewSteps;
2778 for (auto *E : Steps) {
2779 // Skip the same step expression, it was checked already.
2780 if (Step == E || !E) {
2781 NewSteps.push_back(E ? NewStep : nullptr);
2785 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2786 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2787 auto *CanonPVD = PVD->getCanonicalDecl();
2788 if (UniformedArgs.count(CanonPVD) == 0) {
2789 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2790 << Step->getSourceRange();
2791 } else if (E->isValueDependent() || E->isTypeDependent() ||
2792 E->isInstantiationDependent() ||
2793 E->containsUnexpandedParameterPack() ||
2794 CanonPVD->getType()->hasIntegerRepresentation())
2795 NewSteps.push_back(Step);
2797 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2798 << Step->getSourceRange();
2803 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2804 !Step->isInstantiationDependent() &&
2805 !Step->containsUnexpandedParameterPack()) {
2806 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2809 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2811 NewSteps.push_back(NewStep);
2813 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2814 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
2815 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
2816 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2817 const_cast<Expr **>(Linears.data()), Linears.size(),
2818 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2819 NewSteps.data(), NewSteps.size(), SR);
2820 ADecl->addAttr(NewAttr);
2821 return ConvertDeclToDeclGroup(ADecl);
2824 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2826 SourceLocation StartLoc,
2827 SourceLocation EndLoc) {
2831 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2832 // 1.2.2 OpenMP Language Terminology
2833 // Structured block - An executable statement with a single entry at the
2834 // top and a single exit at the bottom.
2835 // The point of exit cannot be a branch out of the structured block.
2836 // longjmp() and throw() must not violate the entry/exit criteria.
2837 CS->getCapturedDecl()->setNothrow();
2839 getCurFunction()->setHasBranchProtectedScope();
2841 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2842 DSAStack->isCancelRegion());
2846 /// \brief Helper class for checking canonical form of the OpenMP loops and
2847 /// extracting iteration space of each loop in the loop nest, that will be used
2848 /// for IR generation.
2849 class OpenMPIterationSpaceChecker {
2850 /// \brief Reference to Sema.
2852 /// \brief A location for diagnostics (when there is no some better location).
2853 SourceLocation DefaultLoc;
2854 /// \brief A location for diagnostics (when increment is not compatible).
2855 SourceLocation ConditionLoc;
2856 /// \brief A source location for referring to loop init later.
2857 SourceRange InitSrcRange;
2858 /// \brief A source location for referring to condition later.
2859 SourceRange ConditionSrcRange;
2860 /// \brief A source location for referring to increment later.
2861 SourceRange IncrementSrcRange;
2862 /// \brief Loop variable.
2863 ValueDecl *LCDecl = nullptr;
2864 /// \brief Reference to loop variable.
2865 Expr *LCRef = nullptr;
2866 /// \brief Lower bound (initializer for the var).
2868 /// \brief Upper bound.
2870 /// \brief Loop step (increment).
2871 Expr *Step = nullptr;
2872 /// \brief This flag is true when condition is one of:
2877 bool TestIsLessOp = false;
2878 /// \brief This flag is true when condition is strict ( < or > ).
2879 bool TestIsStrictOp = false;
2880 /// \brief This flag is true when step is subtracted on each iteration.
2881 bool SubtractStep = false;
2884 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2885 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
2886 /// \brief Check init-expr for canonical loop form and save loop counter
2887 /// variable - #Var and its initialization value - #LB.
2888 bool CheckInit(Stmt *S, bool EmitDiags = true);
2889 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2890 /// for less/greater and for strict/non-strict comparison.
2891 bool CheckCond(Expr *S);
2892 /// \brief Check incr-expr for canonical loop form and return true if it
2893 /// does not conform, otherwise save loop step (#Step).
2894 bool CheckInc(Expr *S);
2895 /// \brief Return the loop counter variable.
2896 ValueDecl *GetLoopDecl() const { return LCDecl; }
2897 /// \brief Return the reference expression to loop counter variable.
2898 Expr *GetLoopDeclRefExpr() const { return LCRef; }
2899 /// \brief Source range of the loop init.
2900 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2901 /// \brief Source range of the loop condition.
2902 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2903 /// \brief Source range of the loop increment.
2904 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2905 /// \brief True if the step should be subtracted.
2906 bool ShouldSubtractStep() const { return SubtractStep; }
2907 /// \brief Build the expression to calculate the number of iterations.
2909 BuildNumIterations(Scope *S, const bool LimitedType,
2910 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
2911 /// \brief Build the precondition expression for the loops.
2912 Expr *BuildPreCond(Scope *S, Expr *Cond,
2913 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
2914 /// \brief Build reference expression to the counter be used for codegen.
2915 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2916 DSAStackTy &DSA) const;
2917 /// \brief Build reference expression to the private counter be used for
2919 Expr *BuildPrivateCounterVar() const;
2920 /// \brief Build initialization of the counter be used for codegen.
2921 Expr *BuildCounterInit() const;
2922 /// \brief Build step of the counter be used for codegen.
2923 Expr *BuildCounterStep() const;
2924 /// \brief Return true if any expression is dependent.
2925 bool Dependent() const;
2928 /// \brief Check the right-hand side of an assignment in the increment
2930 bool CheckIncRHS(Expr *RHS);
2931 /// \brief Helper to set loop counter variable and its initializer.
2932 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
2933 /// \brief Helper to set upper bound.
2934 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
2936 /// \brief Helper to set loop increment.
2937 bool SetStep(Expr *NewStep, bool Subtract);
2940 bool OpenMPIterationSpaceChecker::Dependent() const {
2942 assert(!LB && !UB && !Step);
2945 return LCDecl->getType()->isDependentType() ||
2946 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2947 (Step && Step->isValueDependent());
2950 static Expr *getExprAsWritten(Expr *E) {
2951 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2952 E = ExprTemp->getSubExpr();
2954 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2955 E = MTE->GetTemporaryExpr();
2957 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2958 E = Binder->getSubExpr();
2960 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2961 E = ICE->getSubExprAsWritten();
2962 return E->IgnoreParens();
2965 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2968 // State consistency checking to ensure correct usage.
2969 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
2970 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2971 if (!NewLCDecl || !NewLB)
2973 LCDecl = getCanonicalDecl(NewLCDecl);
2974 LCRef = NewLCRefExpr;
2975 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2976 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2977 if ((Ctor->isCopyOrMoveConstructor() ||
2978 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2979 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
2980 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
2985 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2986 SourceRange SR, SourceLocation SL) {
2987 // State consistency checking to ensure correct usage.
2988 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2989 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2993 TestIsLessOp = LessOp;
2994 TestIsStrictOp = StrictOp;
2995 ConditionSrcRange = SR;
3000 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3001 // State consistency checking to ensure correct usage.
3002 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
3005 if (!NewStep->isValueDependent()) {
3006 // Check that the step is integer expression.
3007 SourceLocation StepLoc = NewStep->getLocStart();
3009 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
3010 if (Val.isInvalid())
3012 NewStep = Val.get();
3014 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3015 // If test-expr is of form var relational-op b and relational-op is < or
3016 // <= then incr-expr must cause var to increase on each iteration of the
3017 // loop. If test-expr is of form var relational-op b and relational-op is
3018 // > or >= then incr-expr must cause var to decrease on each iteration of
3020 // If test-expr is of form b relational-op var and relational-op is < or
3021 // <= then incr-expr must cause var to decrease on each iteration of the
3022 // loop. If test-expr is of form b relational-op var and relational-op is
3023 // > or >= then incr-expr must cause var to increase on each iteration of
3025 llvm::APSInt Result;
3026 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3027 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3029 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
3031 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
3032 bool IsConstZero = IsConstant && !Result.getBoolValue();
3033 if (UB && (IsConstZero ||
3034 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
3035 : (IsConstPos || (IsUnsigned && !Subtract))))) {
3036 SemaRef.Diag(NewStep->getExprLoc(),
3037 diag::err_omp_loop_incr_not_compatible)
3038 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
3039 SemaRef.Diag(ConditionLoc,
3040 diag::note_omp_loop_cond_requres_compatible_incr)
3041 << TestIsLessOp << ConditionSrcRange;
3044 if (TestIsLessOp == Subtract) {
3046 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3048 Subtract = !Subtract;
3053 SubtractStep = Subtract;
3057 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
3058 // Check init-expr for canonical loop form and save loop counter
3059 // variable - #Var and its initialization value - #LB.
3060 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3062 // integer-type var = lb
3063 // random-access-iterator-type var = lb
3064 // pointer-type var = lb
3068 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3072 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3073 if (!ExprTemp->cleanupsHaveSideEffects())
3074 S = ExprTemp->getSubExpr();
3076 InitSrcRange = S->getSourceRange();
3077 if (Expr *E = dyn_cast<Expr>(S))
3078 S = E->IgnoreParens();
3079 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3080 if (BO->getOpcode() == BO_Assign) {
3081 auto *LHS = BO->getLHS()->IgnoreParens();
3082 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3083 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3084 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3085 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3086 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3088 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3089 if (ME->isArrow() &&
3090 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3091 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3094 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
3095 if (DS->isSingleDecl()) {
3096 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
3097 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
3098 // Accept non-canonical init form here but emit ext. warning.
3099 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
3100 SemaRef.Diag(S->getLocStart(),
3101 diag::ext_omp_loop_not_canonical_init)
3102 << S->getSourceRange();
3103 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
3107 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3108 if (CE->getOperator() == OO_Equal) {
3109 auto *LHS = CE->getArg(0);
3110 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3111 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3112 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3113 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3114 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3116 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3117 if (ME->isArrow() &&
3118 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3119 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3124 if (Dependent() || SemaRef.CurContext->isDependentContext())
3127 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3128 << S->getSourceRange();
3133 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
3134 /// variable (which may be the loop variable) if possible.
3135 static const ValueDecl *GetInitLCDecl(Expr *E) {
3138 E = getExprAsWritten(E);
3139 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3140 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3141 if ((Ctor->isCopyOrMoveConstructor() ||
3142 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3143 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3144 E = CE->getArg(0)->IgnoreParenImpCasts();
3145 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3146 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3147 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3148 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3149 return getCanonicalDecl(ME->getMemberDecl());
3150 return getCanonicalDecl(VD);
3153 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3154 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3155 return getCanonicalDecl(ME->getMemberDecl());
3159 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3160 // Check test-expr for canonical form, save upper-bound UB, flags for
3161 // less/greater and for strict/non-strict comparison.
3162 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3163 // var relational-op b
3164 // b relational-op var
3167 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
3170 S = getExprAsWritten(S);
3171 SourceLocation CondLoc = S->getLocStart();
3172 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3173 if (BO->isRelationalOp()) {
3174 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3175 return SetUB(BO->getRHS(),
3176 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3177 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3178 BO->getSourceRange(), BO->getOperatorLoc());
3179 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
3180 return SetUB(BO->getLHS(),
3181 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3182 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3183 BO->getSourceRange(), BO->getOperatorLoc());
3185 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3186 if (CE->getNumArgs() == 2) {
3187 auto Op = CE->getOperator();
3190 case OO_GreaterEqual:
3193 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3194 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3195 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3196 CE->getOperatorLoc());
3197 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
3198 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3199 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3200 CE->getOperatorLoc());
3207 if (Dependent() || SemaRef.CurContext->isDependentContext())
3209 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
3210 << S->getSourceRange() << LCDecl;
3214 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3215 // RHS of canonical loop form increment can be:
3220 RHS = RHS->IgnoreParenImpCasts();
3221 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
3222 if (BO->isAdditiveOp()) {
3223 bool IsAdd = BO->getOpcode() == BO_Add;
3224 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3225 return SetStep(BO->getRHS(), !IsAdd);
3226 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
3227 return SetStep(BO->getLHS(), false);
3229 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
3230 bool IsAdd = CE->getOperator() == OO_Plus;
3231 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
3232 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3233 return SetStep(CE->getArg(1), !IsAdd);
3234 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
3235 return SetStep(CE->getArg(0), false);
3238 if (Dependent() || SemaRef.CurContext->isDependentContext())
3240 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3241 << RHS->getSourceRange() << LCDecl;
3245 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3246 // Check incr-expr for canonical loop form and return true if it
3247 // does not conform.
3248 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3260 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
3263 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3264 if (!ExprTemp->cleanupsHaveSideEffects())
3265 S = ExprTemp->getSubExpr();
3267 IncrementSrcRange = S->getSourceRange();
3268 S = S->IgnoreParens();
3269 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
3270 if (UO->isIncrementDecrementOp() &&
3271 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
3272 return SetStep(SemaRef
3273 .ActOnIntegerConstant(UO->getLocStart(),
3274 (UO->isDecrementOp() ? -1 : 1))
3277 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3278 switch (BO->getOpcode()) {
3281 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3282 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3285 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3286 return CheckIncRHS(BO->getRHS());
3291 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3292 switch (CE->getOperator()) {
3295 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3296 return SetStep(SemaRef
3297 .ActOnIntegerConstant(
3299 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3305 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3306 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3309 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3310 return CheckIncRHS(CE->getArg(1));
3316 if (Dependent() || SemaRef.CurContext->isDependentContext())
3318 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3319 << S->getSourceRange() << LCDecl;
3324 tryBuildCapture(Sema &SemaRef, Expr *Capture,
3325 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3326 if (SemaRef.CurContext->isDependentContext())
3327 return ExprResult(Capture);
3328 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3329 return SemaRef.PerformImplicitConversion(
3330 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3331 /*AllowExplicit=*/true);
3332 auto I = Captures.find(Capture);
3333 if (I != Captures.end())
3334 return buildCapture(SemaRef, Capture, I->second);
3335 DeclRefExpr *Ref = nullptr;
3336 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3337 Captures[Capture] = Ref;
3341 /// \brief Build the expression to calculate the number of iterations.
3342 Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3343 Scope *S, const bool LimitedType,
3344 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3346 auto VarType = LCDecl->getType().getNonReferenceType();
3347 if (VarType->isIntegerType() || VarType->isPointerType() ||
3348 SemaRef.getLangOpts().CPlusPlus) {
3350 auto *UBExpr = TestIsLessOp ? UB : LB;
3351 auto *LBExpr = TestIsLessOp ? LB : UB;
3352 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3353 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
3354 if (!Upper || !Lower)
3357 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3359 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
3360 // BuildBinOp already emitted error, this one is to point user to upper
3361 // and lower bound, and to tell what is passed to 'operator-'.
3362 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3363 << Upper->getSourceRange() << Lower->getSourceRange();
3368 if (!Diff.isUsable())
3371 // Upper - Lower [- 1]
3373 Diff = SemaRef.BuildBinOp(
3374 S, DefaultLoc, BO_Sub, Diff.get(),
3375 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3376 if (!Diff.isUsable())
3379 // Upper - Lower [- 1] + Step
3380 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3381 if (!NewStep.isUsable())
3383 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
3384 if (!Diff.isUsable())
3387 // Parentheses (for dumping/debugging purposes only).
3388 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3389 if (!Diff.isUsable())
3392 // (Upper - Lower [- 1] + Step) / Step
3393 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
3394 if (!Diff.isUsable())
3397 // OpenMP runtime requires 32-bit or 64-bit loop variables.
3398 QualType Type = Diff.get()->getType();
3399 auto &C = SemaRef.Context;
3400 bool UseVarType = VarType->hasIntegerRepresentation() &&
3401 C.getTypeSize(Type) > C.getTypeSize(VarType);
3402 if (!Type->isIntegerType() || UseVarType) {
3404 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3405 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3406 : Type->hasSignedIntegerRepresentation();
3407 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
3408 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3409 Diff = SemaRef.PerformImplicitConversion(
3410 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3411 if (!Diff.isUsable())
3416 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3417 if (NewSize != C.getTypeSize(Type)) {
3418 if (NewSize < C.getTypeSize(Type)) {
3419 assert(NewSize == 64 && "incorrect loop var size");
3420 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3421 << InitSrcRange << ConditionSrcRange;
3423 QualType NewType = C.getIntTypeForBitwidth(
3424 NewSize, Type->hasSignedIntegerRepresentation() ||
3425 C.getTypeSize(Type) < NewSize);
3426 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3427 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3428 Sema::AA_Converting, true);
3429 if (!Diff.isUsable())
3438 Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3439 Scope *S, Expr *Cond,
3440 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3441 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3442 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3443 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3445 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3446 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3447 if (!NewLB.isUsable() || !NewUB.isUsable())
3450 auto CondExpr = SemaRef.BuildBinOp(
3451 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3452 : (TestIsStrictOp ? BO_GT : BO_GE),
3453 NewLB.get(), NewUB.get());
3454 if (CondExpr.isUsable()) {
3455 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3456 SemaRef.Context.BoolTy))
3457 CondExpr = SemaRef.PerformImplicitConversion(
3458 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3459 /*AllowExplicit=*/true);
3461 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3462 // Otherwise use original loop conditon and evaluate it in runtime.
3463 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3466 /// \brief Build reference expression to the counter be used for codegen.
3467 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
3468 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
3469 auto *VD = dyn_cast<VarDecl>(LCDecl);
3471 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3472 auto *Ref = buildDeclRefExpr(
3473 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
3474 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3475 // If the loop control decl is explicitly marked as private, do not mark it
3476 // as captured again.
3477 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3478 Captures.insert(std::make_pair(LCRef, Ref));
3481 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
3485 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
3486 if (LCDecl && !LCDecl->isInvalidDecl()) {
3487 auto Type = LCDecl->getType().getNonReferenceType();
3489 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3490 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
3491 if (PrivateVar->isInvalidDecl())
3493 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3498 /// \brief Build initialization of the counter to be used for codegen.
3499 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3501 /// \brief Build step of the counter be used for codegen.
3502 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3504 /// \brief Iteration space of a single for loop.
3505 struct LoopIterationSpace final {
3506 /// \brief Condition of the loop.
3507 Expr *PreCond = nullptr;
3508 /// \brief This expression calculates the number of iterations in the loop.
3509 /// It is always possible to calculate it before starting the loop.
3510 Expr *NumIterations = nullptr;
3511 /// \brief The loop counter variable.
3512 Expr *CounterVar = nullptr;
3513 /// \brief Private loop counter variable.
3514 Expr *PrivateCounterVar = nullptr;
3515 /// \brief This is initializer for the initial value of #CounterVar.
3516 Expr *CounterInit = nullptr;
3517 /// \brief This is step for the #CounterVar used to generate its update:
3518 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
3519 Expr *CounterStep = nullptr;
3520 /// \brief Should step be subtracted?
3521 bool Subtract = false;
3522 /// \brief Source range of the loop init.
3523 SourceRange InitSrcRange;
3524 /// \brief Source range of the loop condition.
3525 SourceRange CondSrcRange;
3526 /// \brief Source range of the loop increment.
3527 SourceRange IncSrcRange;
3532 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3533 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3534 assert(Init && "Expected loop in canonical form.");
3535 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3536 if (AssociatedLoops > 0 &&
3537 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3538 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
3539 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3540 if (auto *D = ISC.GetLoopDecl()) {
3541 auto *VD = dyn_cast<VarDecl>(D);
3543 if (auto *Private = IsOpenMPCapturedDecl(D))
3546 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3547 /*WithInit=*/false);
3548 VD = cast<VarDecl>(Ref->getDecl());
3551 DSAStack->addLoopControlVariable(D, VD);
3554 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
3558 /// \brief Called on a for stmt to check and extract its iteration space
3559 /// for further processing (such as collapsing).
3560 static bool CheckOpenMPIterationSpace(
3561 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3562 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
3563 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
3564 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
3565 LoopIterationSpace &ResultIterSpace,
3566 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3567 // OpenMP [2.6, Canonical Loop Form]
3568 // for (init-expr; test-expr; incr-expr) structured-block
3569 auto *For = dyn_cast_or_null<ForStmt>(S);
3571 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
3572 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3573 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3574 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3575 if (NestedLoopCount > 1) {
3576 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3577 SemaRef.Diag(DSA.getConstructLoc(),
3578 diag::note_omp_collapse_ordered_expr)
3579 << 2 << CollapseLoopCountExpr->getSourceRange()
3580 << OrderedLoopCountExpr->getSourceRange();
3581 else if (CollapseLoopCountExpr)
3582 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3583 diag::note_omp_collapse_ordered_expr)
3584 << 0 << CollapseLoopCountExpr->getSourceRange();
3586 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3587 diag::note_omp_collapse_ordered_expr)
3588 << 1 << OrderedLoopCountExpr->getSourceRange();
3592 assert(For->getBody());
3594 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3597 auto Init = For->getInit();
3598 if (ISC.CheckInit(Init))
3601 bool HasErrors = false;
3603 // Check loop variable's type.
3604 if (auto *LCDecl = ISC.GetLoopDecl()) {
3605 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
3607 // OpenMP [2.6, Canonical Loop Form]
3608 // Var is one of the following:
3609 // A variable of signed or unsigned integer type.
3610 // For C++, a variable of a random access iterator type.
3611 // For C, a variable of a pointer type.
3612 auto VarType = LCDecl->getType().getNonReferenceType();
3613 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3614 !VarType->isPointerType() &&
3615 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3616 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3617 << SemaRef.getLangOpts().CPlusPlus;
3621 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3623 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3624 // parallel for construct is (are) private.
3625 // The loop iteration variable in the associated for-loop of a simd
3626 // construct with just one associated for-loop is linear with a
3627 // constant-linear-step that is the increment of the associated for-loop.
3628 // Exclude loop var from the list of variables with implicitly defined data
3629 // sharing attributes.
3630 VarsWithImplicitDSA.erase(LCDecl);
3632 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3633 // in a Construct, C/C++].
3634 // The loop iteration variable in the associated for-loop of a simd
3635 // construct with just one associated for-loop may be listed in a linear
3636 // clause with a constant-linear-step that is the increment of the
3637 // associated for-loop.
3638 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3639 // parallel for construct may be listed in a private or lastprivate clause.
3640 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3641 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3642 // declared in the loop and it is predetermined as a private.
3643 auto PredeterminedCKind =
3644 isOpenMPSimdDirective(DKind)
3645 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3647 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3648 DVar.CKind != PredeterminedCKind) ||
3649 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3650 isOpenMPDistributeDirective(DKind)) &&
3651 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3652 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3653 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3654 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3655 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3656 << getOpenMPClauseName(PredeterminedCKind);
3657 if (DVar.RefExpr == nullptr)
3658 DVar.CKind = PredeterminedCKind;
3659 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3661 } else if (LoopDeclRefExpr != nullptr) {
3662 // Make the loop iteration variable private (for worksharing constructs),
3663 // linear (for simd directives with the only one associated loop) or
3664 // lastprivate (for simd directives with several collapsed or ordered
3666 if (DVar.CKind == OMPC_unknown)
3667 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3668 [](OpenMPDirectiveKind) -> bool { return true; },
3669 /*FromParent=*/false);
3670 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3673 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3676 HasErrors |= ISC.CheckCond(For->getCond());
3679 HasErrors |= ISC.CheckInc(For->getInc());
3682 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
3685 // Build the loop's iteration space representation.
3686 ResultIterSpace.PreCond =
3687 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
3688 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
3690 (isOpenMPWorksharingDirective(DKind) ||
3691 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3693 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
3694 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
3695 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3696 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3697 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3698 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3699 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3700 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3702 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3703 ResultIterSpace.NumIterations == nullptr ||
3704 ResultIterSpace.CounterVar == nullptr ||
3705 ResultIterSpace.PrivateCounterVar == nullptr ||
3706 ResultIterSpace.CounterInit == nullptr ||
3707 ResultIterSpace.CounterStep == nullptr);
3712 /// \brief Build 'VarRef = Start.
3714 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3716 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3717 // Build 'VarRef = Start.
3718 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3719 if (!NewStart.isUsable())
3721 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
3722 VarRef.get()->getType())) {
3723 NewStart = SemaRef.PerformImplicitConversion(
3724 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3725 /*AllowExplicit=*/true);
3726 if (!NewStart.isUsable())
3731 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3735 /// \brief Build 'VarRef = Start + Iter * Step'.
3737 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3738 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3739 ExprResult Step, bool Subtract,
3740 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
3741 // Add parentheses (for debugging purposes only).
3742 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3743 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3747 ExprResult NewStep = Step;
3749 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
3750 if (NewStep.isInvalid())
3753 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
3754 if (!Update.isUsable())
3757 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3758 // 'VarRef = Start (+|-) Iter * Step'.
3759 ExprResult NewStart = Start;
3761 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
3762 if (NewStart.isInvalid())
3765 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3766 ExprResult SavedUpdate = Update;
3767 ExprResult UpdateVal;
3768 if (VarRef.get()->getType()->isOverloadableType() ||
3769 NewStart.get()->getType()->isOverloadableType() ||
3770 Update.get()->getType()->isOverloadableType()) {
3771 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3772 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3774 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3775 if (Update.isUsable()) {
3777 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3778 VarRef.get(), SavedUpdate.get());
3779 if (UpdateVal.isUsable()) {
3780 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3784 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3787 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3788 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3789 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3790 NewStart.get(), SavedUpdate.get());
3791 if (!Update.isUsable())
3794 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3795 VarRef.get()->getType())) {
3796 Update = SemaRef.PerformImplicitConversion(
3797 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3798 if (!Update.isUsable())
3802 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3807 /// \brief Convert integer expression \a E to make it have at least \a Bits
3809 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
3812 auto &C = SemaRef.Context;
3813 QualType OldType = E->getType();
3814 unsigned HasBits = C.getTypeSize(OldType);
3815 if (HasBits >= Bits)
3816 return ExprResult(E);
3817 // OK to convert to signed, because new type has more bits than old.
3818 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3819 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3823 /// \brief Check if the given expression \a E is a constant integer that fits
3824 /// into \a Bits bits.
3825 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3828 llvm::APSInt Result;
3829 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3830 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3834 /// Build preinits statement for the given declarations.
3835 static Stmt *buildPreInits(ASTContext &Context,
3836 SmallVectorImpl<Decl *> &PreInits) {
3837 if (!PreInits.empty()) {
3838 return new (Context) DeclStmt(
3839 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3840 SourceLocation(), SourceLocation());
3845 /// Build preinits statement for the given declarations.
3846 static Stmt *buildPreInits(ASTContext &Context,
3847 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3848 if (!Captures.empty()) {
3849 SmallVector<Decl *, 16> PreInits;
3850 for (auto &Pair : Captures)
3851 PreInits.push_back(Pair.second->getDecl());
3852 return buildPreInits(Context, PreInits);
3857 /// Build postupdate expression for the given list of postupdates expressions.
3858 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3859 Expr *PostUpdate = nullptr;
3860 if (!PostUpdates.empty()) {
3861 for (auto *E : PostUpdates) {
3862 Expr *ConvE = S.BuildCStyleCastExpr(
3864 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3867 PostUpdate = PostUpdate
3868 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3877 /// \brief Called on a for stmt to check itself and nested loops (if any).
3878 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3879 /// number of collapsed loops otherwise.
3881 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3882 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3884 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
3885 OMPLoopDirective::HelperExprs &Built) {
3886 unsigned NestedLoopCount = 1;
3887 if (CollapseLoopCountExpr) {
3888 // Found 'collapse' clause - calculate collapse number.
3889 llvm::APSInt Result;
3890 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
3891 NestedLoopCount = Result.getLimitedValue();
3893 if (OrderedLoopCountExpr) {
3894 // Found 'ordered' clause - calculate collapse number.
3895 llvm::APSInt Result;
3896 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3897 if (Result.getLimitedValue() < NestedLoopCount) {
3898 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3899 diag::err_omp_wrong_ordered_loop_count)
3900 << OrderedLoopCountExpr->getSourceRange();
3901 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3902 diag::note_collapse_loop_count)
3903 << CollapseLoopCountExpr->getSourceRange();
3905 NestedLoopCount = Result.getLimitedValue();
3908 // This is helper routine for loop directives (e.g., 'for', 'simd',
3909 // 'for simd', etc.).
3910 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
3911 SmallVector<LoopIterationSpace, 4> IterSpaces;
3912 IterSpaces.resize(NestedLoopCount);
3913 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
3914 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
3915 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
3916 NestedLoopCount, CollapseLoopCountExpr,
3917 OrderedLoopCountExpr, VarsWithImplicitDSA,
3918 IterSpaces[Cnt], Captures))
3920 // Move on to the next nested for loop, or to the loop body.
3921 // OpenMP [2.8.1, simd construct, Restrictions]
3922 // All loops associated with the construct must be perfectly nested; that
3923 // is, there must be no intervening code nor any OpenMP directive between
3925 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
3928 Built.clear(/* size */ NestedLoopCount);
3930 if (SemaRef.CurContext->isDependentContext())
3931 return NestedLoopCount;
3933 // An example of what is generated for the following code:
3935 // #pragma omp simd collapse(2) ordered(2)
3936 // for (i = 0; i < NI; ++i)
3937 // for (k = 0; k < NK; ++k)
3938 // for (j = J0; j < NJ; j+=2) {
3942 // We generate the code below.
3943 // Note: the loop body may be outlined in CodeGen.
3944 // Note: some counters may be C++ classes, operator- is used to find number of
3945 // iterations and operator+= to calculate counter value.
3946 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3947 // or i64 is currently supported).
3949 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3950 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3951 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3952 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3953 // // similar updates for vars in clauses (e.g. 'linear')
3954 // <loop body (using local i and j)>
3956 // i = NI; // assign final values of counters
3960 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3961 // the iteration counts of the collapsed for loops.
3962 // Precondition tests if there is at least one iteration (all conditions are
3964 auto PreCond = ExprResult(IterSpaces[0].PreCond);
3965 auto N0 = IterSpaces[0].NumIterations;
3966 ExprResult LastIteration32 = WidenIterationCount(
3967 32 /* Bits */, SemaRef
3968 .PerformImplicitConversion(
3969 N0->IgnoreImpCasts(), N0->getType(),
3970 Sema::AA_Converting, /*AllowExplicit=*/true)
3973 ExprResult LastIteration64 = WidenIterationCount(
3974 64 /* Bits */, SemaRef
3975 .PerformImplicitConversion(
3976 N0->IgnoreImpCasts(), N0->getType(),
3977 Sema::AA_Converting, /*AllowExplicit=*/true)
3981 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3982 return NestedLoopCount;
3984 auto &C = SemaRef.Context;
3985 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3987 Scope *CurScope = DSA.getCurScope();
3988 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
3989 if (PreCond.isUsable()) {
3991 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
3992 PreCond.get(), IterSpaces[Cnt].PreCond);
3994 auto N = IterSpaces[Cnt].NumIterations;
3995 SourceLocation Loc = N->getExprLoc();
3996 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3997 if (LastIteration32.isUsable())
3998 LastIteration32 = SemaRef.BuildBinOp(
3999 CurScope, Loc, BO_Mul, LastIteration32.get(),
4001 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4002 Sema::AA_Converting,
4003 /*AllowExplicit=*/true)
4005 if (LastIteration64.isUsable())
4006 LastIteration64 = SemaRef.BuildBinOp(
4007 CurScope, Loc, BO_Mul, LastIteration64.get(),
4009 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4010 Sema::AA_Converting,
4011 /*AllowExplicit=*/true)
4015 // Choose either the 32-bit or 64-bit version.
4016 ExprResult LastIteration = LastIteration64;
4017 if (LastIteration32.isUsable() &&
4018 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4019 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4022 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4023 LastIteration64.get(), SemaRef)))
4024 LastIteration = LastIteration32;
4025 QualType VType = LastIteration.get()->getType();
4026 QualType RealVType = VType;
4027 QualType StrideVType = VType;
4028 if (isOpenMPTaskLoopDirective(DKind)) {
4030 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4032 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4035 if (!LastIteration.isUsable())
4038 // Save the number of iterations.
4039 ExprResult NumIterations = LastIteration;
4041 LastIteration = SemaRef.BuildBinOp(
4042 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4043 LastIteration.get(),
4044 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4045 if (!LastIteration.isUsable())
4049 // Calculate the last iteration number beforehand instead of doing this on
4050 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4051 llvm::APSInt Result;
4053 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4054 ExprResult CalcLastIteration;
4056 ExprResult SaveRef =
4057 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
4058 LastIteration = SaveRef;
4060 // Prepare SaveRef + 1.
4061 NumIterations = SemaRef.BuildBinOp(
4062 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
4063 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4064 if (!NumIterations.isUsable())
4068 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4070 // Build variables passed into runtime, necessary for worksharing directives.
4071 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
4072 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4073 isOpenMPDistributeDirective(DKind)) {
4074 // Lower bound variable, initialized with zero.
4075 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4076 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
4077 SemaRef.AddInitializerToDecl(LBDecl,
4078 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4079 /*DirectInit*/ false);
4081 // Upper bound variable, initialized with last iteration number.
4082 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4083 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
4084 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
4085 /*DirectInit*/ false);
4087 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4088 // This will be used to implement clause 'lastprivate'.
4089 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
4090 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4091 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
4092 SemaRef.AddInitializerToDecl(ILDecl,
4093 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4094 /*DirectInit*/ false);
4096 // Stride variable returned by runtime (we initialize it to 1 by default).
4098 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4099 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
4100 SemaRef.AddInitializerToDecl(STDecl,
4101 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4102 /*DirectInit*/ false);
4104 // Build expression: UB = min(UB, LastIteration)
4105 // It is necessary for CodeGen of directives with static scheduling.
4106 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4107 UB.get(), LastIteration.get());
4108 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4109 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4110 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4112 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
4114 // If we have a combined directive that combines 'distribute', 'for' or
4115 // 'simd' we need to be able to access the bounds of the schedule of the
4116 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4117 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4118 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4119 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4121 // We expect to have at least 2 more parameters than the 'parallel'
4122 // directive does - the lower and upper bounds of the previous schedule.
4123 assert(CD->getNumParams() >= 4 &&
4124 "Unexpected number of parameters in loop combined directive");
4126 // Set the proper type for the bounds given what we learned from the
4128 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4129 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4131 // Previous lower and upper bounds are obtained from the region
4134 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4136 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4140 // Build the iteration variable and its initialization before loop.
4144 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4145 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
4147 (isOpenMPWorksharingDirective(DKind) ||
4148 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4150 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4151 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4152 Init = SemaRef.ActOnFinishFullExpr(Init.get());
4155 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
4156 SourceLocation CondLoc;
4158 (isOpenMPWorksharingDirective(DKind) ||
4159 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4160 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4161 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4162 NumIterations.get());
4164 // Loop increment (IV = IV + 1)
4165 SourceLocation IncLoc;
4167 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4168 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4169 if (!Inc.isUsable())
4171 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
4172 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4173 if (!Inc.isUsable())
4176 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4177 // Used for directives with static scheduling.
4178 ExprResult NextLB, NextUB;
4179 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4180 isOpenMPDistributeDirective(DKind)) {
4182 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4183 if (!NextLB.isUsable())
4187 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4188 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4189 if (!NextLB.isUsable())
4192 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4193 if (!NextUB.isUsable())
4197 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4198 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4199 if (!NextUB.isUsable())
4203 // Create: increment expression for distribute loop when combined in a same
4204 // directive with for as IV = IV + ST; ensure upper bound expression based
4205 // on PrevUB instead of NumIterations - used to implement 'for' when found
4206 // in combination with 'distribute', like in 'distribute parallel for'
4207 SourceLocation DistIncLoc;
4208 ExprResult DistCond, DistInc, PrevEUB;
4209 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4210 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4211 assert(DistCond.isUsable() && "distribute cond expr was not built");
4214 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4215 assert(DistInc.isUsable() && "distribute inc expr was not built");
4216 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4218 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4219 assert(DistInc.isUsable() && "distribute inc expr was not built");
4221 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4223 SourceLocation DistEUBLoc;
4224 ExprResult IsUBGreater =
4225 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4226 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4227 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4228 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4230 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4233 // Build updates and final values of the loop counters.
4234 bool HasErrors = false;
4235 Built.Counters.resize(NestedLoopCount);
4236 Built.Inits.resize(NestedLoopCount);
4237 Built.Updates.resize(NestedLoopCount);
4238 Built.Finals.resize(NestedLoopCount);
4239 SmallVector<Expr *, 4> LoopMultipliers;
4242 // Go from inner nested loop to outer.
4243 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4244 LoopIterationSpace &IS = IterSpaces[Cnt];
4245 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4246 // Build: Iter = (IV / Div) % IS.NumIters
4247 // where Div is product of previous iterations' IS.NumIters.
4249 if (Div.isUsable()) {
4251 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4254 assert((Cnt == (int)NestedLoopCount - 1) &&
4255 "unusable div expected on first iteration only");
4258 if (Cnt != 0 && Iter.isUsable())
4259 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4261 if (!Iter.isUsable()) {
4266 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
4267 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4268 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4269 IS.CounterVar->getExprLoc(),
4270 /*RefersToCapture=*/true);
4271 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
4272 IS.CounterInit, Captures);
4273 if (!Init.isUsable()) {
4277 ExprResult Update = BuildCounterUpdate(
4278 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4279 IS.CounterStep, IS.Subtract, &Captures);
4280 if (!Update.isUsable()) {
4285 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4286 ExprResult Final = BuildCounterUpdate(
4287 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
4288 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
4289 if (!Final.isUsable()) {
4294 // Build Div for the next iteration: Div <- Div * IS.NumIters
4297 Div = IS.NumIterations;
4299 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4302 // Add parentheses (for debugging purposes only).
4304 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
4305 if (!Div.isUsable()) {
4309 LoopMultipliers.push_back(Div.get());
4311 if (!Update.isUsable() || !Final.isUsable()) {
4316 Built.Counters[Cnt] = IS.CounterVar;
4317 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
4318 Built.Inits[Cnt] = Init.get();
4319 Built.Updates[Cnt] = Update.get();
4320 Built.Finals[Cnt] = Final.get();
4328 Built.IterationVarRef = IV.get();
4329 Built.LastIteration = LastIteration.get();
4330 Built.NumIterations = NumIterations.get();
4331 Built.CalcLastIteration =
4332 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
4333 Built.PreCond = PreCond.get();
4334 Built.PreInits = buildPreInits(C, Captures);
4335 Built.Cond = Cond.get();
4336 Built.Init = Init.get();
4337 Built.Inc = Inc.get();
4338 Built.LB = LB.get();
4339 Built.UB = UB.get();
4340 Built.IL = IL.get();
4341 Built.ST = ST.get();
4342 Built.EUB = EUB.get();
4343 Built.NLB = NextLB.get();
4344 Built.NUB = NextUB.get();
4345 Built.PrevLB = PrevLB.get();
4346 Built.PrevUB = PrevUB.get();
4347 Built.DistInc = DistInc.get();
4348 Built.PrevEUB = PrevEUB.get();
4350 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4351 // Fill data for doacross depend clauses.
4352 for (auto Pair : DSA.getDoacrossDependClauses()) {
4353 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4354 Pair.first->setCounterValue(CounterVal);
4356 if (NestedLoopCount != Pair.second.size() ||
4357 NestedLoopCount != LoopMultipliers.size() + 1) {
4358 // Erroneous case - clause has some problems.
4359 Pair.first->setCounterValue(CounterVal);
4362 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4363 auto I = Pair.second.rbegin();
4364 auto IS = IterSpaces.rbegin();
4365 auto ILM = LoopMultipliers.rbegin();
4366 Expr *UpCounterVal = CounterVal;
4367 Expr *Multiplier = nullptr;
4368 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4370 assert(IS->CounterStep);
4371 Expr *NormalizedOffset =
4373 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4374 I->first, IS->CounterStep)
4379 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4380 NormalizedOffset, Multiplier)
4383 assert(I->second == OO_Plus || I->second == OO_Minus);
4384 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
4385 UpCounterVal = SemaRef
4386 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4387 UpCounterVal, NormalizedOffset)
4395 Pair.first->setCounterValue(UpCounterVal);
4399 return NestedLoopCount;
4402 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
4403 auto CollapseClauses =
4404 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4405 if (CollapseClauses.begin() != CollapseClauses.end())
4406 return (*CollapseClauses.begin())->getNumForLoops();
4410 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
4411 auto OrderedClauses =
4412 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4413 if (OrderedClauses.begin() != OrderedClauses.end())
4414 return (*OrderedClauses.begin())->getNumForLoops();
4418 static bool checkSimdlenSafelenSpecified(Sema &S,
4419 const ArrayRef<OMPClause *> Clauses) {
4420 OMPSafelenClause *Safelen = nullptr;
4421 OMPSimdlenClause *Simdlen = nullptr;
4423 for (auto *Clause : Clauses) {
4424 if (Clause->getClauseKind() == OMPC_safelen)
4425 Safelen = cast<OMPSafelenClause>(Clause);
4426 else if (Clause->getClauseKind() == OMPC_simdlen)
4427 Simdlen = cast<OMPSimdlenClause>(Clause);
4428 if (Safelen && Simdlen)
4432 if (Simdlen && Safelen) {
4433 llvm::APSInt SimdlenRes, SafelenRes;
4434 auto SimdlenLength = Simdlen->getSimdlen();
4435 auto SafelenLength = Safelen->getSafelen();
4436 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4437 SimdlenLength->isInstantiationDependent() ||
4438 SimdlenLength->containsUnexpandedParameterPack())
4440 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4441 SafelenLength->isInstantiationDependent() ||
4442 SafelenLength->containsUnexpandedParameterPack())
4444 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4445 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4446 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4447 // If both simdlen and safelen clauses are specified, the value of the
4448 // simdlen parameter must be less than or equal to the value of the safelen
4450 if (SimdlenRes > SafelenRes) {
4451 S.Diag(SimdlenLength->getExprLoc(),
4452 diag::err_omp_wrong_simdlen_safelen_values)
4453 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4460 StmtResult Sema::ActOnOpenMPSimdDirective(
4461 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4462 SourceLocation EndLoc,
4463 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4467 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4468 OMPLoopDirective::HelperExprs B;
4469 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4470 // define the nested loops number.
4471 unsigned NestedLoopCount = CheckOpenMPLoop(
4472 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4473 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4474 if (NestedLoopCount == 0)
4477 assert((CurContext->isDependentContext() || B.builtAll()) &&
4478 "omp simd loop exprs were not built");
4480 if (!CurContext->isDependentContext()) {
4481 // Finalize the clauses that need pre-built expressions for CodeGen.
4482 for (auto C : Clauses) {
4483 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4484 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4485 B.NumIterations, *this, CurScope,
4491 if (checkSimdlenSafelenSpecified(*this, Clauses))
4494 getCurFunction()->setHasBranchProtectedScope();
4495 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4499 StmtResult Sema::ActOnOpenMPForDirective(
4500 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4501 SourceLocation EndLoc,
4502 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4506 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4507 OMPLoopDirective::HelperExprs B;
4508 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4509 // define the nested loops number.
4510 unsigned NestedLoopCount = CheckOpenMPLoop(
4511 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4512 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4513 if (NestedLoopCount == 0)
4516 assert((CurContext->isDependentContext() || B.builtAll()) &&
4517 "omp for loop exprs were not built");
4519 if (!CurContext->isDependentContext()) {
4520 // Finalize the clauses that need pre-built expressions for CodeGen.
4521 for (auto C : Clauses) {
4522 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4523 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4524 B.NumIterations, *this, CurScope,
4530 getCurFunction()->setHasBranchProtectedScope();
4531 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4532 Clauses, AStmt, B, DSAStack->isCancelRegion());
4535 StmtResult Sema::ActOnOpenMPForSimdDirective(
4536 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4537 SourceLocation EndLoc,
4538 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4542 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4543 OMPLoopDirective::HelperExprs B;
4544 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4545 // define the nested loops number.
4546 unsigned NestedLoopCount =
4547 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4548 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4549 VarsWithImplicitDSA, B);
4550 if (NestedLoopCount == 0)
4553 assert((CurContext->isDependentContext() || B.builtAll()) &&
4554 "omp for simd loop exprs were not built");
4556 if (!CurContext->isDependentContext()) {
4557 // Finalize the clauses that need pre-built expressions for CodeGen.
4558 for (auto C : Clauses) {
4559 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4560 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4561 B.NumIterations, *this, CurScope,
4567 if (checkSimdlenSafelenSpecified(*this, Clauses))
4570 getCurFunction()->setHasBranchProtectedScope();
4571 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4575 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4577 SourceLocation StartLoc,
4578 SourceLocation EndLoc) {
4582 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4583 auto BaseStmt = AStmt;
4584 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4585 BaseStmt = CS->getCapturedStmt();
4586 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4587 auto S = C->children();
4588 if (S.begin() == S.end())
4590 // All associated statements must be '#pragma omp section' except for
4592 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4593 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4595 Diag(SectionStmt->getLocStart(),
4596 diag::err_omp_sections_substmt_not_section);
4599 cast<OMPSectionDirective>(SectionStmt)
4600 ->setHasCancel(DSAStack->isCancelRegion());
4603 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4607 getCurFunction()->setHasBranchProtectedScope();
4609 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4610 DSAStack->isCancelRegion());
4613 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4614 SourceLocation StartLoc,
4615 SourceLocation EndLoc) {
4619 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4621 getCurFunction()->setHasBranchProtectedScope();
4622 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
4624 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4625 DSAStack->isCancelRegion());
4628 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4630 SourceLocation StartLoc,
4631 SourceLocation EndLoc) {
4635 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4637 getCurFunction()->setHasBranchProtectedScope();
4639 // OpenMP [2.7.3, single Construct, Restrictions]
4640 // The copyprivate clause must not be used with the nowait clause.
4641 OMPClause *Nowait = nullptr;
4642 OMPClause *Copyprivate = nullptr;
4643 for (auto *Clause : Clauses) {
4644 if (Clause->getClauseKind() == OMPC_nowait)
4646 else if (Clause->getClauseKind() == OMPC_copyprivate)
4647 Copyprivate = Clause;
4648 if (Copyprivate && Nowait) {
4649 Diag(Copyprivate->getLocStart(),
4650 diag::err_omp_single_copyprivate_with_nowait);
4651 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4656 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4659 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4660 SourceLocation StartLoc,
4661 SourceLocation EndLoc) {
4665 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4667 getCurFunction()->setHasBranchProtectedScope();
4669 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4672 StmtResult Sema::ActOnOpenMPCriticalDirective(
4673 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4674 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
4678 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4680 bool ErrorFound = false;
4682 SourceLocation HintLoc;
4683 bool DependentHint = false;
4684 for (auto *C : Clauses) {
4685 if (C->getClauseKind() == OMPC_hint) {
4686 if (!DirName.getName()) {
4687 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4690 Expr *E = cast<OMPHintClause>(C)->getHint();
4691 if (E->isTypeDependent() || E->isValueDependent() ||
4692 E->isInstantiationDependent())
4693 DependentHint = true;
4695 Hint = E->EvaluateKnownConstInt(Context);
4696 HintLoc = C->getLocStart();
4702 auto Pair = DSAStack->getCriticalWithHint(DirName);
4703 if (Pair.first && DirName.getName() && !DependentHint) {
4704 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4705 Diag(StartLoc, diag::err_omp_critical_with_hint);
4706 if (HintLoc.isValid()) {
4707 Diag(HintLoc, diag::note_omp_critical_hint_here)
4708 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4710 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4711 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4712 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4714 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4715 /*Radix=*/10, /*Signed=*/false);
4717 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4721 getCurFunction()->setHasBranchProtectedScope();
4723 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4725 if (!Pair.first && DirName.getName() && !DependentHint)
4726 DSAStack->addCriticalWithHint(Dir, Hint);
4730 StmtResult Sema::ActOnOpenMPParallelForDirective(
4731 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4732 SourceLocation EndLoc,
4733 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4737 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4738 // 1.2.2 OpenMP Language Terminology
4739 // Structured block - An executable statement with a single entry at the
4740 // top and a single exit at the bottom.
4741 // The point of exit cannot be a branch out of the structured block.
4742 // longjmp() and throw() must not violate the entry/exit criteria.
4743 CS->getCapturedDecl()->setNothrow();
4745 OMPLoopDirective::HelperExprs B;
4746 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4747 // define the nested loops number.
4748 unsigned NestedLoopCount =
4749 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4750 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4751 VarsWithImplicitDSA, B);
4752 if (NestedLoopCount == 0)
4755 assert((CurContext->isDependentContext() || B.builtAll()) &&
4756 "omp parallel for loop exprs were not built");
4758 if (!CurContext->isDependentContext()) {
4759 // Finalize the clauses that need pre-built expressions for CodeGen.
4760 for (auto C : Clauses) {
4761 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4762 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4763 B.NumIterations, *this, CurScope,
4769 getCurFunction()->setHasBranchProtectedScope();
4770 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
4771 NestedLoopCount, Clauses, AStmt, B,
4772 DSAStack->isCancelRegion());
4775 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4776 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4777 SourceLocation EndLoc,
4778 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4782 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4783 // 1.2.2 OpenMP Language Terminology
4784 // Structured block - An executable statement with a single entry at the
4785 // top and a single exit at the bottom.
4786 // The point of exit cannot be a branch out of the structured block.
4787 // longjmp() and throw() must not violate the entry/exit criteria.
4788 CS->getCapturedDecl()->setNothrow();
4790 OMPLoopDirective::HelperExprs B;
4791 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4792 // define the nested loops number.
4793 unsigned NestedLoopCount =
4794 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4795 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4796 VarsWithImplicitDSA, B);
4797 if (NestedLoopCount == 0)
4800 if (!CurContext->isDependentContext()) {
4801 // Finalize the clauses that need pre-built expressions for CodeGen.
4802 for (auto C : Clauses) {
4803 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4804 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4805 B.NumIterations, *this, CurScope,
4811 if (checkSimdlenSafelenSpecified(*this, Clauses))
4814 getCurFunction()->setHasBranchProtectedScope();
4815 return OMPParallelForSimdDirective::Create(
4816 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
4820 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4821 Stmt *AStmt, SourceLocation StartLoc,
4822 SourceLocation EndLoc) {
4826 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4827 auto BaseStmt = AStmt;
4828 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4829 BaseStmt = CS->getCapturedStmt();
4830 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4831 auto S = C->children();
4832 if (S.begin() == S.end())
4834 // All associated statements must be '#pragma omp section' except for
4836 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4837 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4839 Diag(SectionStmt->getLocStart(),
4840 diag::err_omp_parallel_sections_substmt_not_section);
4843 cast<OMPSectionDirective>(SectionStmt)
4844 ->setHasCancel(DSAStack->isCancelRegion());
4847 Diag(AStmt->getLocStart(),
4848 diag::err_omp_parallel_sections_not_compound_stmt);
4852 getCurFunction()->setHasBranchProtectedScope();
4854 return OMPParallelSectionsDirective::Create(
4855 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
4858 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4859 Stmt *AStmt, SourceLocation StartLoc,
4860 SourceLocation EndLoc) {
4864 auto *CS = cast<CapturedStmt>(AStmt);
4865 // 1.2.2 OpenMP Language Terminology
4866 // Structured block - An executable statement with a single entry at the
4867 // top and a single exit at the bottom.
4868 // The point of exit cannot be a branch out of the structured block.
4869 // longjmp() and throw() must not violate the entry/exit criteria.
4870 CS->getCapturedDecl()->setNothrow();
4872 getCurFunction()->setHasBranchProtectedScope();
4874 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4875 DSAStack->isCancelRegion());
4878 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4879 SourceLocation EndLoc) {
4880 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4883 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4884 SourceLocation EndLoc) {
4885 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4888 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4889 SourceLocation EndLoc) {
4890 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4893 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4894 SourceLocation StartLoc,
4895 SourceLocation EndLoc) {
4899 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4901 getCurFunction()->setHasBranchProtectedScope();
4903 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4906 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4907 SourceLocation StartLoc,
4908 SourceLocation EndLoc) {
4909 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4910 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4913 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4915 SourceLocation StartLoc,
4916 SourceLocation EndLoc) {
4917 OMPClause *DependFound = nullptr;
4918 OMPClause *DependSourceClause = nullptr;
4919 OMPClause *DependSinkClause = nullptr;
4920 bool ErrorFound = false;
4921 OMPThreadsClause *TC = nullptr;
4922 OMPSIMDClause *SC = nullptr;
4923 for (auto *C : Clauses) {
4924 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4926 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4927 if (DependSourceClause) {
4928 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4929 << getOpenMPDirectiveName(OMPD_ordered)
4930 << getOpenMPClauseName(OMPC_depend) << 2;
4933 DependSourceClause = C;
4934 if (DependSinkClause) {
4935 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4939 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4940 if (DependSourceClause) {
4941 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4945 DependSinkClause = C;
4947 } else if (C->getClauseKind() == OMPC_threads)
4948 TC = cast<OMPThreadsClause>(C);
4949 else if (C->getClauseKind() == OMPC_simd)
4950 SC = cast<OMPSIMDClause>(C);
4952 if (!ErrorFound && !SC &&
4953 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
4954 // OpenMP [2.8.1,simd Construct, Restrictions]
4955 // An ordered construct with the simd clause is the only OpenMP construct
4956 // that can appear in the simd region.
4957 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
4959 } else if (DependFound && (TC || SC)) {
4960 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4961 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4963 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4964 Diag(DependFound->getLocStart(),
4965 diag::err_omp_ordered_directive_without_param);
4967 } else if (TC || Clauses.empty()) {
4968 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4969 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4970 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4972 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4976 if ((!AStmt && !DependFound) || ErrorFound)
4980 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4982 getCurFunction()->setHasBranchProtectedScope();
4985 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4989 /// \brief Helper class for checking expression in 'omp atomic [update]'
4991 class OpenMPAtomicUpdateChecker {
4992 /// \brief Error results for atomic update expressions.
4993 enum ExprAnalysisErrorCode {
4994 /// \brief A statement is not an expression statement.
4996 /// \brief Expression is not builtin binary or unary operation.
4997 NotABinaryOrUnaryExpression,
4998 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4999 NotAnUnaryIncDecExpression,
5000 /// \brief An expression is not of scalar type.
5002 /// \brief A binary operation is not an assignment operation.
5004 /// \brief RHS part of the binary operation is not a binary expression.
5005 NotABinaryExpression,
5006 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5009 /// \brief RHS binary operation does not have reference to the updated LHS
5011 NotAnUpdateExpression,
5012 /// \brief No errors is found.
5015 /// \brief Reference to Sema.
5017 /// \brief A location for note diagnostics (when error is found).
5018 SourceLocation NoteLoc;
5019 /// \brief 'x' lvalue part of the source atomic expression.
5021 /// \brief 'expr' rvalue part of the source atomic expression.
5023 /// \brief Helper expression of the form
5024 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5025 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5027 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5028 /// important for non-associative operations.
5029 bool IsXLHSInRHSPart;
5030 BinaryOperatorKind Op;
5031 SourceLocation OpLoc;
5032 /// \brief true if the source expression is a postfix unary operation, false
5033 /// if it is a prefix unary operation.
5034 bool IsPostfixUpdate;
5037 OpenMPAtomicUpdateChecker(Sema &SemaRef)
5038 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
5039 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
5040 /// \brief Check specified statement that it is suitable for 'atomic update'
5041 /// constructs and extract 'x', 'expr' and Operation from the original
5042 /// expression. If DiagId and NoteId == 0, then only check is performed
5043 /// without error notification.
5044 /// \param DiagId Diagnostic which should be emitted if error is found.
5045 /// \param NoteId Diagnostic note for the main error message.
5046 /// \return true if statement is not an update expression, false otherwise.
5047 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
5048 /// \brief Return the 'x' lvalue part of the source atomic expression.
5049 Expr *getX() const { return X; }
5050 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5051 Expr *getExpr() const { return E; }
5052 /// \brief Return the update expression used in calculation of the updated
5053 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5054 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5055 Expr *getUpdateExpr() const { return UpdateExpr; }
5056 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5057 /// false otherwise.
5058 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5060 /// \brief true if the source expression is a postfix unary operation, false
5061 /// if it is a prefix unary operation.
5062 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5065 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5066 unsigned NoteId = 0);
5070 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5071 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5072 ExprAnalysisErrorCode ErrorFound = NoError;
5073 SourceLocation ErrorLoc, NoteLoc;
5074 SourceRange ErrorRange, NoteRange;
5075 // Allowed constructs are:
5076 // x = x binop expr;
5077 // x = expr binop x;
5078 if (AtomicBinOp->getOpcode() == BO_Assign) {
5079 X = AtomicBinOp->getLHS();
5080 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5081 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5082 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5083 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5084 AtomicInnerBinOp->isBitwiseOp()) {
5085 Op = AtomicInnerBinOp->getOpcode();
5086 OpLoc = AtomicInnerBinOp->getOperatorLoc();
5087 auto *LHS = AtomicInnerBinOp->getLHS();
5088 auto *RHS = AtomicInnerBinOp->getRHS();
5089 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5090 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5091 /*Canonical=*/true);
5092 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5093 /*Canonical=*/true);
5094 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5095 /*Canonical=*/true);
5098 IsXLHSInRHSPart = true;
5099 } else if (XId == RHSId) {
5101 IsXLHSInRHSPart = false;
5103 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5104 ErrorRange = AtomicInnerBinOp->getSourceRange();
5105 NoteLoc = X->getExprLoc();
5106 NoteRange = X->getSourceRange();
5107 ErrorFound = NotAnUpdateExpression;
5110 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5111 ErrorRange = AtomicInnerBinOp->getSourceRange();
5112 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5113 NoteRange = SourceRange(NoteLoc, NoteLoc);
5114 ErrorFound = NotABinaryOperator;
5117 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5118 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5119 ErrorFound = NotABinaryExpression;
5122 ErrorLoc = AtomicBinOp->getExprLoc();
5123 ErrorRange = AtomicBinOp->getSourceRange();
5124 NoteLoc = AtomicBinOp->getOperatorLoc();
5125 NoteRange = SourceRange(NoteLoc, NoteLoc);
5126 ErrorFound = NotAnAssignmentOp;
5128 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5129 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5130 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5132 } else if (SemaRef.CurContext->isDependentContext())
5133 E = X = UpdateExpr = nullptr;
5134 return ErrorFound != NoError;
5137 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5139 ExprAnalysisErrorCode ErrorFound = NoError;
5140 SourceLocation ErrorLoc, NoteLoc;
5141 SourceRange ErrorRange, NoteRange;
5142 // Allowed constructs are:
5148 // x = x binop expr;
5149 // x = expr binop x;
5150 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5151 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5152 if (AtomicBody->getType()->isScalarType() ||
5153 AtomicBody->isInstantiationDependent()) {
5154 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5155 AtomicBody->IgnoreParenImpCasts())) {
5156 // Check for Compound Assignment Operation
5157 Op = BinaryOperator::getOpForCompoundAssignment(
5158 AtomicCompAssignOp->getOpcode());
5159 OpLoc = AtomicCompAssignOp->getOperatorLoc();
5160 E = AtomicCompAssignOp->getRHS();
5161 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
5162 IsXLHSInRHSPart = true;
5163 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5164 AtomicBody->IgnoreParenImpCasts())) {
5165 // Check for Binary Operation
5166 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
5168 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5169 AtomicBody->IgnoreParenImpCasts())) {
5170 // Check for Unary Operation
5171 if (AtomicUnaryOp->isIncrementDecrementOp()) {
5172 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
5173 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5174 OpLoc = AtomicUnaryOp->getOperatorLoc();
5175 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
5176 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5177 IsXLHSInRHSPart = true;
5179 ErrorFound = NotAnUnaryIncDecExpression;
5180 ErrorLoc = AtomicUnaryOp->getExprLoc();
5181 ErrorRange = AtomicUnaryOp->getSourceRange();
5182 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5183 NoteRange = SourceRange(NoteLoc, NoteLoc);
5185 } else if (!AtomicBody->isInstantiationDependent()) {
5186 ErrorFound = NotABinaryOrUnaryExpression;
5187 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5188 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5191 ErrorFound = NotAScalarType;
5192 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5193 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5196 ErrorFound = NotAnExpression;
5197 NoteLoc = ErrorLoc = S->getLocStart();
5198 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5200 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5201 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5202 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5204 } else if (SemaRef.CurContext->isDependentContext())
5205 E = X = UpdateExpr = nullptr;
5206 if (ErrorFound == NoError && E && X) {
5207 // Build an update expression of form 'OpaqueValueExpr(x) binop
5208 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5209 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5210 auto *OVEX = new (SemaRef.getASTContext())
5211 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5212 auto *OVEExpr = new (SemaRef.getASTContext())
5213 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5215 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5216 IsXLHSInRHSPart ? OVEExpr : OVEX);
5217 if (Update.isInvalid())
5219 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5221 if (Update.isInvalid())
5223 UpdateExpr = Update.get();
5225 return ErrorFound != NoError;
5228 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5230 SourceLocation StartLoc,
5231 SourceLocation EndLoc) {
5235 auto *CS = cast<CapturedStmt>(AStmt);
5236 // 1.2.2 OpenMP Language Terminology
5237 // Structured block - An executable statement with a single entry at the
5238 // top and a single exit at the bottom.
5239 // The point of exit cannot be a branch out of the structured block.
5240 // longjmp() and throw() must not violate the entry/exit criteria.
5241 OpenMPClauseKind AtomicKind = OMPC_unknown;
5242 SourceLocation AtomicKindLoc;
5243 for (auto *C : Clauses) {
5244 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
5245 C->getClauseKind() == OMPC_update ||
5246 C->getClauseKind() == OMPC_capture) {
5247 if (AtomicKind != OMPC_unknown) {
5248 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5249 << SourceRange(C->getLocStart(), C->getLocEnd());
5250 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5251 << getOpenMPClauseName(AtomicKind);
5253 AtomicKind = C->getClauseKind();
5254 AtomicKindLoc = C->getLocStart();
5259 auto Body = CS->getCapturedStmt();
5260 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5261 Body = EWC->getSubExpr();
5267 bool IsXLHSInRHSPart = false;
5268 bool IsPostfixUpdate = false;
5269 // OpenMP [2.12.6, atomic Construct]
5270 // In the next expressions:
5271 // * x and v (as applicable) are both l-value expressions with scalar type.
5272 // * During the execution of an atomic region, multiple syntactic
5273 // occurrences of x must designate the same storage location.
5274 // * Neither of v and expr (as applicable) may access the storage location
5276 // * Neither of x and expr (as applicable) may access the storage location
5278 // * expr is an expression with scalar type.
5279 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5280 // * binop, binop=, ++, and -- are not overloaded operators.
5281 // * The expression x binop expr must be numerically equivalent to x binop
5282 // (expr). This requirement is satisfied if the operators in expr have
5283 // precedence greater than binop, or by using parentheses around expr or
5284 // subexpressions of expr.
5285 // * The expression expr binop x must be numerically equivalent to (expr)
5286 // binop x. This requirement is satisfied if the operators in expr have
5287 // precedence equal to or greater than binop, or by using parentheses around
5288 // expr or subexpressions of expr.
5289 // * For forms that allow multiple occurrences of x, the number of times
5290 // that x is evaluated is unspecified.
5291 if (AtomicKind == OMPC_read) {
5298 } ErrorFound = NoError;
5299 SourceLocation ErrorLoc, NoteLoc;
5300 SourceRange ErrorRange, NoteRange;
5301 // If clause is read:
5303 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5305 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5306 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5307 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5308 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5309 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5310 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5311 if (!X->isLValue() || !V->isLValue()) {
5312 auto NotLValueExpr = X->isLValue() ? V : X;
5313 ErrorFound = NotAnLValue;
5314 ErrorLoc = AtomicBinOp->getExprLoc();
5315 ErrorRange = AtomicBinOp->getSourceRange();
5316 NoteLoc = NotLValueExpr->getExprLoc();
5317 NoteRange = NotLValueExpr->getSourceRange();
5319 } else if (!X->isInstantiationDependent() ||
5320 !V->isInstantiationDependent()) {
5321 auto NotScalarExpr =
5322 (X->isInstantiationDependent() || X->getType()->isScalarType())
5325 ErrorFound = NotAScalarType;
5326 ErrorLoc = AtomicBinOp->getExprLoc();
5327 ErrorRange = AtomicBinOp->getSourceRange();
5328 NoteLoc = NotScalarExpr->getExprLoc();
5329 NoteRange = NotScalarExpr->getSourceRange();
5331 } else if (!AtomicBody->isInstantiationDependent()) {
5332 ErrorFound = NotAnAssignmentOp;
5333 ErrorLoc = AtomicBody->getExprLoc();
5334 ErrorRange = AtomicBody->getSourceRange();
5335 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5336 : AtomicBody->getExprLoc();
5337 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5338 : AtomicBody->getSourceRange();
5341 ErrorFound = NotAnExpression;
5342 NoteLoc = ErrorLoc = Body->getLocStart();
5343 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5345 if (ErrorFound != NoError) {
5346 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5348 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5351 } else if (CurContext->isDependentContext())
5353 } else if (AtomicKind == OMPC_write) {
5360 } ErrorFound = NoError;
5361 SourceLocation ErrorLoc, NoteLoc;
5362 SourceRange ErrorRange, NoteRange;
5363 // If clause is write:
5365 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5367 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5368 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5369 X = AtomicBinOp->getLHS();
5370 E = AtomicBinOp->getRHS();
5371 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5372 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5373 if (!X->isLValue()) {
5374 ErrorFound = NotAnLValue;
5375 ErrorLoc = AtomicBinOp->getExprLoc();
5376 ErrorRange = AtomicBinOp->getSourceRange();
5377 NoteLoc = X->getExprLoc();
5378 NoteRange = X->getSourceRange();
5380 } else if (!X->isInstantiationDependent() ||
5381 !E->isInstantiationDependent()) {
5382 auto NotScalarExpr =
5383 (X->isInstantiationDependent() || X->getType()->isScalarType())
5386 ErrorFound = NotAScalarType;
5387 ErrorLoc = AtomicBinOp->getExprLoc();
5388 ErrorRange = AtomicBinOp->getSourceRange();
5389 NoteLoc = NotScalarExpr->getExprLoc();
5390 NoteRange = NotScalarExpr->getSourceRange();
5392 } else if (!AtomicBody->isInstantiationDependent()) {
5393 ErrorFound = NotAnAssignmentOp;
5394 ErrorLoc = AtomicBody->getExprLoc();
5395 ErrorRange = AtomicBody->getSourceRange();
5396 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5397 : AtomicBody->getExprLoc();
5398 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5399 : AtomicBody->getSourceRange();
5402 ErrorFound = NotAnExpression;
5403 NoteLoc = ErrorLoc = Body->getLocStart();
5404 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5406 if (ErrorFound != NoError) {
5407 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5409 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5412 } else if (CurContext->isDependentContext())
5414 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
5415 // If clause is update:
5421 // x = x binop expr;
5422 // x = expr binop x;
5423 OpenMPAtomicUpdateChecker Checker(*this);
5424 if (Checker.checkStatement(
5425 Body, (AtomicKind == OMPC_update)
5426 ? diag::err_omp_atomic_update_not_expression_statement
5427 : diag::err_omp_atomic_not_expression_statement,
5428 diag::note_omp_atomic_update))
5430 if (!CurContext->isDependentContext()) {
5431 E = Checker.getExpr();
5433 UE = Checker.getUpdateExpr();
5434 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5436 } else if (AtomicKind == OMPC_capture) {
5439 NotACompoundStatement,
5440 NotTwoSubstatements,
5441 NotASpecificExpression,
5443 } ErrorFound = NoError;
5444 SourceLocation ErrorLoc, NoteLoc;
5445 SourceRange ErrorRange, NoteRange;
5446 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5447 // If clause is a capture:
5452 // v = x binop= expr;
5453 // v = x = x binop expr;
5454 // v = x = expr binop x;
5456 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5457 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5458 V = AtomicBinOp->getLHS();
5459 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5460 OpenMPAtomicUpdateChecker Checker(*this);
5461 if (Checker.checkStatement(
5462 Body, diag::err_omp_atomic_capture_not_expression_statement,
5463 diag::note_omp_atomic_update))
5465 E = Checker.getExpr();
5467 UE = Checker.getUpdateExpr();
5468 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5469 IsPostfixUpdate = Checker.isPostfixUpdate();
5470 } else if (!AtomicBody->isInstantiationDependent()) {
5471 ErrorLoc = AtomicBody->getExprLoc();
5472 ErrorRange = AtomicBody->getSourceRange();
5473 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5474 : AtomicBody->getExprLoc();
5475 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5476 : AtomicBody->getSourceRange();
5477 ErrorFound = NotAnAssignmentOp;
5479 if (ErrorFound != NoError) {
5480 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5482 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5484 } else if (CurContext->isDependentContext()) {
5485 UE = V = E = X = nullptr;
5488 // If clause is a capture:
5489 // { v = x; x = expr; }
5494 // { v = x; x binop= expr; }
5495 // { v = x; x = x binop expr; }
5496 // { v = x; x = expr binop x; }
5501 // { x binop= expr; v = x; }
5502 // { x = x binop expr; v = x; }
5503 // { x = expr binop x; v = x; }
5504 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5505 // Check that this is { expr1; expr2; }
5506 if (CS->size() == 2) {
5507 auto *First = CS->body_front();
5508 auto *Second = CS->body_back();
5509 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5510 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5511 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5512 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5513 // Need to find what subexpression is 'v' and what is 'x'.
5514 OpenMPAtomicUpdateChecker Checker(*this);
5515 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5516 BinaryOperator *BinOp = nullptr;
5517 if (IsUpdateExprFound) {
5518 BinOp = dyn_cast<BinaryOperator>(First);
5519 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5521 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5526 // { v = x; x binop= expr; }
5527 // { v = x; x = x binop expr; }
5528 // { v = x; x = expr binop x; }
5529 // Check that the first expression has form v = x.
5530 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5531 llvm::FoldingSetNodeID XId, PossibleXId;
5532 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5533 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5534 IsUpdateExprFound = XId == PossibleXId;
5535 if (IsUpdateExprFound) {
5536 V = BinOp->getLHS();
5538 E = Checker.getExpr();
5539 UE = Checker.getUpdateExpr();
5540 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5541 IsPostfixUpdate = true;
5544 if (!IsUpdateExprFound) {
5545 IsUpdateExprFound = !Checker.checkStatement(First);
5547 if (IsUpdateExprFound) {
5548 BinOp = dyn_cast<BinaryOperator>(Second);
5549 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5551 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5556 // { x binop= expr; v = x; }
5557 // { x = x binop expr; v = x; }
5558 // { x = expr binop x; v = x; }
5559 // Check that the second expression has form v = x.
5560 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5561 llvm::FoldingSetNodeID XId, PossibleXId;
5562 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5563 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5564 IsUpdateExprFound = XId == PossibleXId;
5565 if (IsUpdateExprFound) {
5566 V = BinOp->getLHS();
5568 E = Checker.getExpr();
5569 UE = Checker.getUpdateExpr();
5570 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5571 IsPostfixUpdate = false;
5575 if (!IsUpdateExprFound) {
5576 // { v = x; x = expr; }
5577 auto *FirstExpr = dyn_cast<Expr>(First);
5578 auto *SecondExpr = dyn_cast<Expr>(Second);
5579 if (!FirstExpr || !SecondExpr ||
5580 !(FirstExpr->isInstantiationDependent() ||
5581 SecondExpr->isInstantiationDependent())) {
5582 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5583 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
5584 ErrorFound = NotAnAssignmentOp;
5585 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5586 : First->getLocStart();
5587 NoteRange = ErrorRange = FirstBinOp
5588 ? FirstBinOp->getSourceRange()
5589 : SourceRange(ErrorLoc, ErrorLoc);
5591 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5592 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5593 ErrorFound = NotAnAssignmentOp;
5594 NoteLoc = ErrorLoc = SecondBinOp
5595 ? SecondBinOp->getOperatorLoc()
5596 : Second->getLocStart();
5597 NoteRange = ErrorRange =
5598 SecondBinOp ? SecondBinOp->getSourceRange()
5599 : SourceRange(ErrorLoc, ErrorLoc);
5601 auto *PossibleXRHSInFirst =
5602 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5603 auto *PossibleXLHSInSecond =
5604 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5605 llvm::FoldingSetNodeID X1Id, X2Id;
5606 PossibleXRHSInFirst->Profile(X1Id, Context,
5607 /*Canonical=*/true);
5608 PossibleXLHSInSecond->Profile(X2Id, Context,
5609 /*Canonical=*/true);
5610 IsUpdateExprFound = X1Id == X2Id;
5611 if (IsUpdateExprFound) {
5612 V = FirstBinOp->getLHS();
5613 X = SecondBinOp->getLHS();
5614 E = SecondBinOp->getRHS();
5616 IsXLHSInRHSPart = false;
5617 IsPostfixUpdate = true;
5619 ErrorFound = NotASpecificExpression;
5620 ErrorLoc = FirstBinOp->getExprLoc();
5621 ErrorRange = FirstBinOp->getSourceRange();
5622 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5623 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5630 NoteLoc = ErrorLoc = Body->getLocStart();
5631 NoteRange = ErrorRange =
5632 SourceRange(Body->getLocStart(), Body->getLocStart());
5633 ErrorFound = NotTwoSubstatements;
5636 NoteLoc = ErrorLoc = Body->getLocStart();
5637 NoteRange = ErrorRange =
5638 SourceRange(Body->getLocStart(), Body->getLocStart());
5639 ErrorFound = NotACompoundStatement;
5641 if (ErrorFound != NoError) {
5642 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5644 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5646 } else if (CurContext->isDependentContext()) {
5647 UE = V = E = X = nullptr;
5652 getCurFunction()->setHasBranchProtectedScope();
5654 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5655 X, V, E, UE, IsXLHSInRHSPart,
5659 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5661 SourceLocation StartLoc,
5662 SourceLocation EndLoc) {
5666 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5667 // 1.2.2 OpenMP Language Terminology
5668 // Structured block - An executable statement with a single entry at the
5669 // top and a single exit at the bottom.
5670 // The point of exit cannot be a branch out of the structured block.
5671 // longjmp() and throw() must not violate the entry/exit criteria.
5672 CS->getCapturedDecl()->setNothrow();
5674 // OpenMP [2.16, Nesting of Regions]
5675 // If specified, a teams construct must be contained within a target
5676 // construct. That target construct must contain no statements or directives
5677 // outside of the teams construct.
5678 if (DSAStack->hasInnerTeamsRegion()) {
5679 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5680 bool OMPTeamsFound = true;
5681 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5682 auto I = CS->body_begin();
5683 while (I != CS->body_end()) {
5684 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
5685 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5686 OMPTeamsFound = false;
5691 assert(I != CS->body_end() && "Not found statement");
5694 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5695 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
5697 if (!OMPTeamsFound) {
5698 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5699 Diag(DSAStack->getInnerTeamsRegionLoc(),
5700 diag::note_omp_nested_teams_construct_here);
5701 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5702 << isa<OMPExecutableDirective>(S);
5707 getCurFunction()->setHasBranchProtectedScope();
5709 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5713 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5714 Stmt *AStmt, SourceLocation StartLoc,
5715 SourceLocation EndLoc) {
5719 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5720 // 1.2.2 OpenMP Language Terminology
5721 // Structured block - An executable statement with a single entry at the
5722 // top and a single exit at the bottom.
5723 // The point of exit cannot be a branch out of the structured block.
5724 // longjmp() and throw() must not violate the entry/exit criteria.
5725 CS->getCapturedDecl()->setNothrow();
5727 getCurFunction()->setHasBranchProtectedScope();
5729 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5733 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5734 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5735 SourceLocation EndLoc,
5736 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5740 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5741 // 1.2.2 OpenMP Language Terminology
5742 // Structured block - An executable statement with a single entry at the
5743 // top and a single exit at the bottom.
5744 // The point of exit cannot be a branch out of the structured block.
5745 // longjmp() and throw() must not violate the entry/exit criteria.
5746 CS->getCapturedDecl()->setNothrow();
5748 OMPLoopDirective::HelperExprs B;
5749 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5750 // define the nested loops number.
5751 unsigned NestedLoopCount =
5752 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5753 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5754 VarsWithImplicitDSA, B);
5755 if (NestedLoopCount == 0)
5758 assert((CurContext->isDependentContext() || B.builtAll()) &&
5759 "omp target parallel for loop exprs were not built");
5761 if (!CurContext->isDependentContext()) {
5762 // Finalize the clauses that need pre-built expressions for CodeGen.
5763 for (auto C : Clauses) {
5764 if (auto *LC = dyn_cast<OMPLinearClause>(C))
5765 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5766 B.NumIterations, *this, CurScope,
5772 getCurFunction()->setHasBranchProtectedScope();
5773 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5774 NestedLoopCount, Clauses, AStmt,
5775 B, DSAStack->isCancelRegion());
5778 /// \brief Check for existence of a map clause in the list of clauses.
5779 static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5780 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5782 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5790 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5792 SourceLocation StartLoc,
5793 SourceLocation EndLoc) {
5797 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5799 // OpenMP [2.10.1, Restrictions, p. 97]
5800 // At least one map clause must appear on the directive.
5801 if (!HasMapClause(Clauses)) {
5802 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5803 << getOpenMPDirectiveName(OMPD_target_data);
5807 getCurFunction()->setHasBranchProtectedScope();
5809 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5814 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5815 SourceLocation StartLoc,
5816 SourceLocation EndLoc) {
5817 // OpenMP [2.10.2, Restrictions, p. 99]
5818 // At least one map clause must appear on the directive.
5819 if (!HasMapClause(Clauses)) {
5820 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5821 << getOpenMPDirectiveName(OMPD_target_enter_data);
5825 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5830 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5831 SourceLocation StartLoc,
5832 SourceLocation EndLoc) {
5833 // OpenMP [2.10.3, Restrictions, p. 102]
5834 // At least one map clause must appear on the directive.
5835 if (!HasMapClause(Clauses)) {
5836 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5837 << getOpenMPDirectiveName(OMPD_target_exit_data);
5841 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5844 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5845 SourceLocation StartLoc,
5846 SourceLocation EndLoc) {
5847 bool seenMotionClause = false;
5848 for (auto *C : Clauses) {
5849 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
5850 seenMotionClause = true;
5852 if (!seenMotionClause) {
5853 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5856 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5859 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5860 Stmt *AStmt, SourceLocation StartLoc,
5861 SourceLocation EndLoc) {
5865 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5866 // 1.2.2 OpenMP Language Terminology
5867 // Structured block - An executable statement with a single entry at the
5868 // top and a single exit at the bottom.
5869 // The point of exit cannot be a branch out of the structured block.
5870 // longjmp() and throw() must not violate the entry/exit criteria.
5871 CS->getCapturedDecl()->setNothrow();
5873 getCurFunction()->setHasBranchProtectedScope();
5875 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5879 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5880 SourceLocation EndLoc,
5881 OpenMPDirectiveKind CancelRegion) {
5882 if (DSAStack->isParentNowaitRegion()) {
5883 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5886 if (DSAStack->isParentOrderedRegion()) {
5887 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5890 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5894 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5895 SourceLocation StartLoc,
5896 SourceLocation EndLoc,
5897 OpenMPDirectiveKind CancelRegion) {
5898 if (DSAStack->isParentNowaitRegion()) {
5899 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5902 if (DSAStack->isParentOrderedRegion()) {
5903 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5906 DSAStack->setParentCancelRegion(/*Cancel=*/true);
5907 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5911 static bool checkGrainsizeNumTasksClauses(Sema &S,
5912 ArrayRef<OMPClause *> Clauses) {
5913 OMPClause *PrevClause = nullptr;
5914 bool ErrorFound = false;
5915 for (auto *C : Clauses) {
5916 if (C->getClauseKind() == OMPC_grainsize ||
5917 C->getClauseKind() == OMPC_num_tasks) {
5920 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5921 S.Diag(C->getLocStart(),
5922 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5923 << getOpenMPClauseName(C->getClauseKind())
5924 << getOpenMPClauseName(PrevClause->getClauseKind());
5925 S.Diag(PrevClause->getLocStart(),
5926 diag::note_omp_previous_grainsize_num_tasks)
5927 << getOpenMPClauseName(PrevClause->getClauseKind());
5935 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5936 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5937 SourceLocation EndLoc,
5938 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5942 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5943 OMPLoopDirective::HelperExprs B;
5944 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5945 // define the nested loops number.
5946 unsigned NestedLoopCount =
5947 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
5948 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5949 VarsWithImplicitDSA, B);
5950 if (NestedLoopCount == 0)
5953 assert((CurContext->isDependentContext() || B.builtAll()) &&
5954 "omp for loop exprs were not built");
5956 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5957 // The grainsize clause and num_tasks clause are mutually exclusive and may
5958 // not appear on the same taskloop directive.
5959 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5962 getCurFunction()->setHasBranchProtectedScope();
5963 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5964 NestedLoopCount, Clauses, AStmt, B);
5967 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5968 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5969 SourceLocation EndLoc,
5970 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5974 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5975 OMPLoopDirective::HelperExprs B;
5976 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5977 // define the nested loops number.
5978 unsigned NestedLoopCount =
5979 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5980 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5981 VarsWithImplicitDSA, B);
5982 if (NestedLoopCount == 0)
5985 assert((CurContext->isDependentContext() || B.builtAll()) &&
5986 "omp for loop exprs were not built");
5988 if (!CurContext->isDependentContext()) {
5989 // Finalize the clauses that need pre-built expressions for CodeGen.
5990 for (auto C : Clauses) {
5991 if (auto *LC = dyn_cast<OMPLinearClause>(C))
5992 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5993 B.NumIterations, *this, CurScope,
5999 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6000 // The grainsize clause and num_tasks clause are mutually exclusive and may
6001 // not appear on the same taskloop directive.
6002 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6005 getCurFunction()->setHasBranchProtectedScope();
6006 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6007 NestedLoopCount, Clauses, AStmt, B);
6010 StmtResult Sema::ActOnOpenMPDistributeDirective(
6011 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6012 SourceLocation EndLoc,
6013 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6017 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6018 OMPLoopDirective::HelperExprs B;
6019 // In presence of clause 'collapse' with number of loops, it will
6020 // define the nested loops number.
6021 unsigned NestedLoopCount =
6022 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6023 nullptr /*ordered not a clause on distribute*/, AStmt,
6024 *this, *DSAStack, VarsWithImplicitDSA, B);
6025 if (NestedLoopCount == 0)
6028 assert((CurContext->isDependentContext() || B.builtAll()) &&
6029 "omp for loop exprs were not built");
6031 getCurFunction()->setHasBranchProtectedScope();
6032 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6033 NestedLoopCount, Clauses, AStmt, B);
6036 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6037 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6038 SourceLocation EndLoc,
6039 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6043 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6044 // 1.2.2 OpenMP Language Terminology
6045 // Structured block - An executable statement with a single entry at the
6046 // top and a single exit at the bottom.
6047 // The point of exit cannot be a branch out of the structured block.
6048 // longjmp() and throw() must not violate the entry/exit criteria.
6049 CS->getCapturedDecl()->setNothrow();
6051 OMPLoopDirective::HelperExprs B;
6052 // In presence of clause 'collapse' with number of loops, it will
6053 // define the nested loops number.
6054 unsigned NestedLoopCount = CheckOpenMPLoop(
6055 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6056 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6057 VarsWithImplicitDSA, B);
6058 if (NestedLoopCount == 0)
6061 assert((CurContext->isDependentContext() || B.builtAll()) &&
6062 "omp for loop exprs were not built");
6064 getCurFunction()->setHasBranchProtectedScope();
6065 return OMPDistributeParallelForDirective::Create(
6066 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6069 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6070 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6071 SourceLocation EndLoc,
6072 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6076 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6077 // 1.2.2 OpenMP Language Terminology
6078 // Structured block - An executable statement with a single entry at the
6079 // top and a single exit at the bottom.
6080 // The point of exit cannot be a branch out of the structured block.
6081 // longjmp() and throw() must not violate the entry/exit criteria.
6082 CS->getCapturedDecl()->setNothrow();
6084 OMPLoopDirective::HelperExprs B;
6085 // In presence of clause 'collapse' with number of loops, it will
6086 // define the nested loops number.
6087 unsigned NestedLoopCount = CheckOpenMPLoop(
6088 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6089 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6090 VarsWithImplicitDSA, B);
6091 if (NestedLoopCount == 0)
6094 assert((CurContext->isDependentContext() || B.builtAll()) &&
6095 "omp for loop exprs were not built");
6097 if (checkSimdlenSafelenSpecified(*this, Clauses))
6100 getCurFunction()->setHasBranchProtectedScope();
6101 return OMPDistributeParallelForSimdDirective::Create(
6102 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6105 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6106 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6107 SourceLocation EndLoc,
6108 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6112 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6113 // 1.2.2 OpenMP Language Terminology
6114 // Structured block - An executable statement with a single entry at the
6115 // top and a single exit at the bottom.
6116 // The point of exit cannot be a branch out of the structured block.
6117 // longjmp() and throw() must not violate the entry/exit criteria.
6118 CS->getCapturedDecl()->setNothrow();
6120 OMPLoopDirective::HelperExprs B;
6121 // In presence of clause 'collapse' with number of loops, it will
6122 // define the nested loops number.
6123 unsigned NestedLoopCount =
6124 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6125 nullptr /*ordered not a clause on distribute*/, AStmt,
6126 *this, *DSAStack, VarsWithImplicitDSA, B);
6127 if (NestedLoopCount == 0)
6130 assert((CurContext->isDependentContext() || B.builtAll()) &&
6131 "omp for loop exprs were not built");
6133 if (checkSimdlenSafelenSpecified(*this, Clauses))
6136 getCurFunction()->setHasBranchProtectedScope();
6137 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6138 NestedLoopCount, Clauses, AStmt, B);
6141 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6142 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6143 SourceLocation EndLoc,
6144 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6148 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6149 // 1.2.2 OpenMP Language Terminology
6150 // Structured block - An executable statement with a single entry at the
6151 // top and a single exit at the bottom.
6152 // The point of exit cannot be a branch out of the structured block.
6153 // longjmp() and throw() must not violate the entry/exit criteria.
6154 CS->getCapturedDecl()->setNothrow();
6156 OMPLoopDirective::HelperExprs B;
6157 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6158 // define the nested loops number.
6159 unsigned NestedLoopCount = CheckOpenMPLoop(
6160 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6161 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6162 VarsWithImplicitDSA, B);
6163 if (NestedLoopCount == 0)
6166 assert((CurContext->isDependentContext() || B.builtAll()) &&
6167 "omp target parallel for simd loop exprs were not built");
6169 if (!CurContext->isDependentContext()) {
6170 // Finalize the clauses that need pre-built expressions for CodeGen.
6171 for (auto C : Clauses) {
6172 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6173 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6174 B.NumIterations, *this, CurScope,
6179 if (checkSimdlenSafelenSpecified(*this, Clauses))
6182 getCurFunction()->setHasBranchProtectedScope();
6183 return OMPTargetParallelForSimdDirective::Create(
6184 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6187 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6188 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6189 SourceLocation EndLoc,
6190 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6194 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6195 // 1.2.2 OpenMP Language Terminology
6196 // Structured block - An executable statement with a single entry at the
6197 // top and a single exit at the bottom.
6198 // The point of exit cannot be a branch out of the structured block.
6199 // longjmp() and throw() must not violate the entry/exit criteria.
6200 CS->getCapturedDecl()->setNothrow();
6202 OMPLoopDirective::HelperExprs B;
6203 // In presence of clause 'collapse' with number of loops, it will define the
6204 // nested loops number.
6205 unsigned NestedLoopCount =
6206 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6207 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6208 VarsWithImplicitDSA, B);
6209 if (NestedLoopCount == 0)
6212 assert((CurContext->isDependentContext() || B.builtAll()) &&
6213 "omp target simd loop exprs were not built");
6215 if (!CurContext->isDependentContext()) {
6216 // Finalize the clauses that need pre-built expressions for CodeGen.
6217 for (auto C : Clauses) {
6218 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6219 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6220 B.NumIterations, *this, CurScope,
6226 if (checkSimdlenSafelenSpecified(*this, Clauses))
6229 getCurFunction()->setHasBranchProtectedScope();
6230 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6231 NestedLoopCount, Clauses, AStmt, B);
6234 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6235 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6236 SourceLocation EndLoc,
6237 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6241 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6242 // 1.2.2 OpenMP Language Terminology
6243 // Structured block - An executable statement with a single entry at the
6244 // top and a single exit at the bottom.
6245 // The point of exit cannot be a branch out of the structured block.
6246 // longjmp() and throw() must not violate the entry/exit criteria.
6247 CS->getCapturedDecl()->setNothrow();
6249 OMPLoopDirective::HelperExprs B;
6250 // In presence of clause 'collapse' with number of loops, it will
6251 // define the nested loops number.
6252 unsigned NestedLoopCount =
6253 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6254 nullptr /*ordered not a clause on distribute*/, AStmt,
6255 *this, *DSAStack, VarsWithImplicitDSA, B);
6256 if (NestedLoopCount == 0)
6259 assert((CurContext->isDependentContext() || B.builtAll()) &&
6260 "omp teams distribute loop exprs were not built");
6262 getCurFunction()->setHasBranchProtectedScope();
6263 return OMPTeamsDistributeDirective::Create(
6264 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6267 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6268 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6269 SourceLocation EndLoc,
6270 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6274 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6275 // 1.2.2 OpenMP Language Terminology
6276 // Structured block - An executable statement with a single entry at the
6277 // top and a single exit at the bottom.
6278 // The point of exit cannot be a branch out of the structured block.
6279 // longjmp() and throw() must not violate the entry/exit criteria.
6280 CS->getCapturedDecl()->setNothrow();
6282 OMPLoopDirective::HelperExprs B;
6283 // In presence of clause 'collapse' with number of loops, it will
6284 // define the nested loops number.
6285 unsigned NestedLoopCount = CheckOpenMPLoop(
6286 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6287 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6288 VarsWithImplicitDSA, B);
6290 if (NestedLoopCount == 0)
6293 assert((CurContext->isDependentContext() || B.builtAll()) &&
6294 "omp teams distribute simd loop exprs were not built");
6296 if (!CurContext->isDependentContext()) {
6297 // Finalize the clauses that need pre-built expressions for CodeGen.
6298 for (auto C : Clauses) {
6299 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6300 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6301 B.NumIterations, *this, CurScope,
6307 if (checkSimdlenSafelenSpecified(*this, Clauses))
6310 getCurFunction()->setHasBranchProtectedScope();
6311 return OMPTeamsDistributeSimdDirective::Create(
6312 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6315 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6316 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6317 SourceLocation EndLoc,
6318 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6322 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6323 // 1.2.2 OpenMP Language Terminology
6324 // Structured block - An executable statement with a single entry at the
6325 // top and a single exit at the bottom.
6326 // The point of exit cannot be a branch out of the structured block.
6327 // longjmp() and throw() must not violate the entry/exit criteria.
6328 CS->getCapturedDecl()->setNothrow();
6330 OMPLoopDirective::HelperExprs B;
6331 // In presence of clause 'collapse' with number of loops, it will
6332 // define the nested loops number.
6333 auto NestedLoopCount = CheckOpenMPLoop(
6334 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6335 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6336 VarsWithImplicitDSA, B);
6338 if (NestedLoopCount == 0)
6341 assert((CurContext->isDependentContext() || B.builtAll()) &&
6342 "omp for loop exprs were not built");
6344 if (!CurContext->isDependentContext()) {
6345 // Finalize the clauses that need pre-built expressions for CodeGen.
6346 for (auto C : Clauses) {
6347 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6348 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6349 B.NumIterations, *this, CurScope,
6355 if (checkSimdlenSafelenSpecified(*this, Clauses))
6358 getCurFunction()->setHasBranchProtectedScope();
6359 return OMPTeamsDistributeParallelForSimdDirective::Create(
6360 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6363 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6364 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6365 SourceLocation EndLoc,
6366 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6370 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6371 // 1.2.2 OpenMP Language Terminology
6372 // Structured block - An executable statement with a single entry at the
6373 // top and a single exit at the bottom.
6374 // The point of exit cannot be a branch out of the structured block.
6375 // longjmp() and throw() must not violate the entry/exit criteria.
6376 CS->getCapturedDecl()->setNothrow();
6378 OMPLoopDirective::HelperExprs B;
6379 // In presence of clause 'collapse' with number of loops, it will
6380 // define the nested loops number.
6381 unsigned NestedLoopCount = CheckOpenMPLoop(
6382 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6383 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6384 VarsWithImplicitDSA, B);
6386 if (NestedLoopCount == 0)
6389 assert((CurContext->isDependentContext() || B.builtAll()) &&
6390 "omp for loop exprs were not built");
6392 if (!CurContext->isDependentContext()) {
6393 // Finalize the clauses that need pre-built expressions for CodeGen.
6394 for (auto C : Clauses) {
6395 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6396 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6397 B.NumIterations, *this, CurScope,
6403 getCurFunction()->setHasBranchProtectedScope();
6404 return OMPTeamsDistributeParallelForDirective::Create(
6405 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6408 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6410 SourceLocation StartLoc,
6411 SourceLocation EndLoc) {
6415 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6416 // 1.2.2 OpenMP Language Terminology
6417 // Structured block - An executable statement with a single entry at the
6418 // top and a single exit at the bottom.
6419 // The point of exit cannot be a branch out of the structured block.
6420 // longjmp() and throw() must not violate the entry/exit criteria.
6421 CS->getCapturedDecl()->setNothrow();
6423 getCurFunction()->setHasBranchProtectedScope();
6425 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6429 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6430 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6431 SourceLocation EndLoc,
6432 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6436 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6437 // 1.2.2 OpenMP Language Terminology
6438 // Structured block - An executable statement with a single entry at the
6439 // top and a single exit at the bottom.
6440 // The point of exit cannot be a branch out of the structured block.
6441 // longjmp() and throw() must not violate the entry/exit criteria.
6442 CS->getCapturedDecl()->setNothrow();
6444 OMPLoopDirective::HelperExprs B;
6445 // In presence of clause 'collapse' with number of loops, it will
6446 // define the nested loops number.
6447 auto NestedLoopCount = CheckOpenMPLoop(
6448 OMPD_target_teams_distribute,
6449 getCollapseNumberExpr(Clauses),
6450 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6451 VarsWithImplicitDSA, B);
6452 if (NestedLoopCount == 0)
6455 assert((CurContext->isDependentContext() || B.builtAll()) &&
6456 "omp target teams distribute loop exprs were not built");
6458 getCurFunction()->setHasBranchProtectedScope();
6459 return OMPTargetTeamsDistributeDirective::Create(
6460 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6463 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6464 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6465 SourceLocation EndLoc,
6466 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6470 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6471 // 1.2.2 OpenMP Language Terminology
6472 // Structured block - An executable statement with a single entry at the
6473 // top and a single exit at the bottom.
6474 // The point of exit cannot be a branch out of the structured block.
6475 // longjmp() and throw() must not violate the entry/exit criteria.
6476 CS->getCapturedDecl()->setNothrow();
6478 OMPLoopDirective::HelperExprs B;
6479 // In presence of clause 'collapse' with number of loops, it will
6480 // define the nested loops number.
6481 auto NestedLoopCount = CheckOpenMPLoop(
6482 OMPD_target_teams_distribute_parallel_for,
6483 getCollapseNumberExpr(Clauses),
6484 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6485 VarsWithImplicitDSA, B);
6486 if (NestedLoopCount == 0)
6489 assert((CurContext->isDependentContext() || B.builtAll()) &&
6490 "omp target teams distribute parallel for loop exprs were not built");
6492 if (!CurContext->isDependentContext()) {
6493 // Finalize the clauses that need pre-built expressions for CodeGen.
6494 for (auto C : Clauses) {
6495 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6496 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6497 B.NumIterations, *this, CurScope,
6503 getCurFunction()->setHasBranchProtectedScope();
6504 return OMPTargetTeamsDistributeParallelForDirective::Create(
6505 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6508 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6509 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6510 SourceLocation EndLoc,
6511 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6515 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6516 // 1.2.2 OpenMP Language Terminology
6517 // Structured block - An executable statement with a single entry at the
6518 // top and a single exit at the bottom.
6519 // The point of exit cannot be a branch out of the structured block.
6520 // longjmp() and throw() must not violate the entry/exit criteria.
6521 CS->getCapturedDecl()->setNothrow();
6523 OMPLoopDirective::HelperExprs B;
6524 // In presence of clause 'collapse' with number of loops, it will
6525 // define the nested loops number.
6526 auto NestedLoopCount = CheckOpenMPLoop(
6527 OMPD_target_teams_distribute_parallel_for_simd,
6528 getCollapseNumberExpr(Clauses),
6529 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6530 VarsWithImplicitDSA, B);
6531 if (NestedLoopCount == 0)
6534 assert((CurContext->isDependentContext() || B.builtAll()) &&
6535 "omp target teams distribute parallel for simd loop exprs were not "
6538 if (!CurContext->isDependentContext()) {
6539 // Finalize the clauses that need pre-built expressions for CodeGen.
6540 for (auto C : Clauses) {
6541 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6542 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6543 B.NumIterations, *this, CurScope,
6549 getCurFunction()->setHasBranchProtectedScope();
6550 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6551 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6554 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6555 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6556 SourceLocation EndLoc,
6557 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6561 auto *CS = cast<CapturedStmt>(AStmt);
6562 // 1.2.2 OpenMP Language Terminology
6563 // Structured block - An executable statement with a single entry at the
6564 // top and a single exit at the bottom.
6565 // The point of exit cannot be a branch out of the structured block.
6566 // longjmp() and throw() must not violate the entry/exit criteria.
6567 CS->getCapturedDecl()->setNothrow();
6569 OMPLoopDirective::HelperExprs B;
6570 // In presence of clause 'collapse' with number of loops, it will
6571 // define the nested loops number.
6572 auto NestedLoopCount = CheckOpenMPLoop(
6573 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6574 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6575 VarsWithImplicitDSA, B);
6576 if (NestedLoopCount == 0)
6579 assert((CurContext->isDependentContext() || B.builtAll()) &&
6580 "omp target teams distribute simd loop exprs were not built");
6582 getCurFunction()->setHasBranchProtectedScope();
6583 return OMPTargetTeamsDistributeSimdDirective::Create(
6584 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6587 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
6588 SourceLocation StartLoc,
6589 SourceLocation LParenLoc,
6590 SourceLocation EndLoc) {
6591 OMPClause *Res = nullptr;
6594 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6596 case OMPC_num_threads:
6597 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6600 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6603 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6606 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6609 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6612 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6614 case OMPC_num_teams:
6615 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6617 case OMPC_thread_limit:
6618 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6621 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6623 case OMPC_grainsize:
6624 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6626 case OMPC_num_tasks:
6627 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6630 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6634 case OMPC_proc_bind:
6637 case OMPC_firstprivate:
6638 case OMPC_lastprivate:
6640 case OMPC_reduction:
6644 case OMPC_copyprivate:
6647 case OMPC_mergeable:
6648 case OMPC_threadprivate:
6660 case OMPC_dist_schedule:
6661 case OMPC_defaultmap:
6666 case OMPC_use_device_ptr:
6667 case OMPC_is_device_ptr:
6668 llvm_unreachable("Clause is not allowed.");
6673 // An OpenMP directive such as 'target parallel' has two captured regions:
6674 // for the 'target' and 'parallel' respectively. This function returns
6675 // the region in which to capture expressions associated with a clause.
6676 // A return value of OMPD_unknown signifies that the expression should not
6678 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
6679 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
6680 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
6681 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
6686 case OMPD_target_parallel:
6687 // If this clause applies to the nested 'parallel' region, capture within
6688 // the 'target' region, otherwise do not capture.
6689 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
6690 CaptureRegion = OMPD_target;
6694 case OMPD_parallel_sections:
6695 case OMPD_parallel_for:
6696 case OMPD_parallel_for_simd:
6698 case OMPD_target_simd:
6699 case OMPD_target_parallel_for:
6700 case OMPD_target_parallel_for_simd:
6701 case OMPD_target_teams:
6702 case OMPD_target_teams_distribute:
6703 case OMPD_target_teams_distribute_simd:
6704 case OMPD_target_teams_distribute_parallel_for:
6705 case OMPD_target_teams_distribute_parallel_for_simd:
6706 case OMPD_teams_distribute_parallel_for:
6707 case OMPD_teams_distribute_parallel_for_simd:
6708 case OMPD_distribute_parallel_for:
6709 case OMPD_distribute_parallel_for_simd:
6712 case OMPD_taskloop_simd:
6713 case OMPD_target_data:
6714 case OMPD_target_enter_data:
6715 case OMPD_target_exit_data:
6716 case OMPD_target_update:
6717 // Do not capture if-clause expressions.
6719 case OMPD_threadprivate:
6720 case OMPD_taskyield:
6723 case OMPD_cancellation_point:
6725 case OMPD_declare_reduction:
6726 case OMPD_declare_simd:
6727 case OMPD_declare_target:
6728 case OMPD_end_declare_target:
6738 case OMPD_taskgroup:
6739 case OMPD_distribute:
6742 case OMPD_distribute_simd:
6743 case OMPD_teams_distribute:
6744 case OMPD_teams_distribute_simd:
6745 llvm_unreachable("Unexpected OpenMP directive with if-clause");
6747 llvm_unreachable("Unknown OpenMP directive");
6750 case OMPC_num_threads:
6752 case OMPD_target_parallel:
6753 CaptureRegion = OMPD_target;
6757 case OMPD_parallel_sections:
6758 case OMPD_parallel_for:
6759 case OMPD_parallel_for_simd:
6761 case OMPD_target_simd:
6762 case OMPD_target_parallel_for:
6763 case OMPD_target_parallel_for_simd:
6764 case OMPD_target_teams:
6765 case OMPD_target_teams_distribute:
6766 case OMPD_target_teams_distribute_simd:
6767 case OMPD_target_teams_distribute_parallel_for:
6768 case OMPD_target_teams_distribute_parallel_for_simd:
6769 case OMPD_teams_distribute_parallel_for:
6770 case OMPD_teams_distribute_parallel_for_simd:
6771 case OMPD_distribute_parallel_for:
6772 case OMPD_distribute_parallel_for_simd:
6775 case OMPD_taskloop_simd:
6776 case OMPD_target_data:
6777 case OMPD_target_enter_data:
6778 case OMPD_target_exit_data:
6779 case OMPD_target_update:
6780 // Do not capture num_threads-clause expressions.
6782 case OMPD_threadprivate:
6783 case OMPD_taskyield:
6786 case OMPD_cancellation_point:
6788 case OMPD_declare_reduction:
6789 case OMPD_declare_simd:
6790 case OMPD_declare_target:
6791 case OMPD_end_declare_target:
6801 case OMPD_taskgroup:
6802 case OMPD_distribute:
6805 case OMPD_distribute_simd:
6806 case OMPD_teams_distribute:
6807 case OMPD_teams_distribute_simd:
6808 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
6810 llvm_unreachable("Unknown OpenMP directive");
6813 case OMPC_num_teams:
6815 case OMPD_target_teams:
6816 CaptureRegion = OMPD_target;
6820 case OMPD_parallel_sections:
6821 case OMPD_parallel_for:
6822 case OMPD_parallel_for_simd:
6824 case OMPD_target_simd:
6825 case OMPD_target_parallel:
6826 case OMPD_target_parallel_for:
6827 case OMPD_target_parallel_for_simd:
6828 case OMPD_target_teams_distribute:
6829 case OMPD_target_teams_distribute_simd:
6830 case OMPD_target_teams_distribute_parallel_for:
6831 case OMPD_target_teams_distribute_parallel_for_simd:
6832 case OMPD_teams_distribute_parallel_for:
6833 case OMPD_teams_distribute_parallel_for_simd:
6834 case OMPD_distribute_parallel_for:
6835 case OMPD_distribute_parallel_for_simd:
6838 case OMPD_taskloop_simd:
6839 case OMPD_target_data:
6840 case OMPD_target_enter_data:
6841 case OMPD_target_exit_data:
6842 case OMPD_target_update:
6844 case OMPD_teams_distribute:
6845 case OMPD_teams_distribute_simd:
6846 // Do not capture num_teams-clause expressions.
6848 case OMPD_threadprivate:
6849 case OMPD_taskyield:
6852 case OMPD_cancellation_point:
6854 case OMPD_declare_reduction:
6855 case OMPD_declare_simd:
6856 case OMPD_declare_target:
6857 case OMPD_end_declare_target:
6866 case OMPD_taskgroup:
6867 case OMPD_distribute:
6870 case OMPD_distribute_simd:
6871 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
6873 llvm_unreachable("Unknown OpenMP directive");
6876 case OMPC_thread_limit:
6878 case OMPD_target_teams:
6879 CaptureRegion = OMPD_target;
6883 case OMPD_parallel_sections:
6884 case OMPD_parallel_for:
6885 case OMPD_parallel_for_simd:
6887 case OMPD_target_simd:
6888 case OMPD_target_parallel:
6889 case OMPD_target_parallel_for:
6890 case OMPD_target_parallel_for_simd:
6891 case OMPD_target_teams_distribute:
6892 case OMPD_target_teams_distribute_simd:
6893 case OMPD_target_teams_distribute_parallel_for:
6894 case OMPD_target_teams_distribute_parallel_for_simd:
6895 case OMPD_teams_distribute_parallel_for:
6896 case OMPD_teams_distribute_parallel_for_simd:
6897 case OMPD_distribute_parallel_for:
6898 case OMPD_distribute_parallel_for_simd:
6901 case OMPD_taskloop_simd:
6902 case OMPD_target_data:
6903 case OMPD_target_enter_data:
6904 case OMPD_target_exit_data:
6905 case OMPD_target_update:
6907 case OMPD_teams_distribute:
6908 case OMPD_teams_distribute_simd:
6909 // Do not capture thread_limit-clause expressions.
6911 case OMPD_threadprivate:
6912 case OMPD_taskyield:
6915 case OMPD_cancellation_point:
6917 case OMPD_declare_reduction:
6918 case OMPD_declare_simd:
6919 case OMPD_declare_target:
6920 case OMPD_end_declare_target:
6929 case OMPD_taskgroup:
6930 case OMPD_distribute:
6933 case OMPD_distribute_simd:
6934 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
6936 llvm_unreachable("Unknown OpenMP directive");
6940 case OMPC_dist_schedule:
6941 case OMPC_firstprivate:
6942 case OMPC_lastprivate:
6943 case OMPC_reduction:
6946 case OMPC_proc_bind:
6955 case OMPC_copyprivate:
6959 case OMPC_mergeable:
6960 case OMPC_threadprivate:
6973 case OMPC_grainsize:
6975 case OMPC_num_tasks:
6977 case OMPC_defaultmap:
6982 case OMPC_use_device_ptr:
6983 case OMPC_is_device_ptr:
6984 llvm_unreachable("Unexpected OpenMP clause.");
6986 return CaptureRegion;
6989 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6990 Expr *Condition, SourceLocation StartLoc,
6991 SourceLocation LParenLoc,
6992 SourceLocation NameModifierLoc,
6993 SourceLocation ColonLoc,
6994 SourceLocation EndLoc) {
6995 Expr *ValExpr = Condition;
6996 Stmt *HelperValStmt = nullptr;
6997 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
6998 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6999 !Condition->isInstantiationDependent() &&
7000 !Condition->containsUnexpandedParameterPack()) {
7001 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
7002 if (Val.isInvalid())
7005 ValExpr = MakeFullExpr(Val.get()).get();
7007 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7009 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7010 if (CaptureRegion != OMPD_unknown) {
7011 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7012 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7013 HelperValStmt = buildPreInits(Context, Captures);
7017 return new (Context)
7018 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7019 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
7022 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7023 SourceLocation StartLoc,
7024 SourceLocation LParenLoc,
7025 SourceLocation EndLoc) {
7026 Expr *ValExpr = Condition;
7027 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7028 !Condition->isInstantiationDependent() &&
7029 !Condition->containsUnexpandedParameterPack()) {
7030 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
7031 if (Val.isInvalid())
7034 ValExpr = MakeFullExpr(Val.get()).get();
7037 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7039 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7044 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7046 IntConvertDiagnoser()
7047 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
7048 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7049 QualType T) override {
7050 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7052 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7053 QualType T) override {
7054 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7056 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7058 QualType ConvTy) override {
7059 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7061 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7062 QualType ConvTy) override {
7063 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
7064 << ConvTy->isEnumeralType() << ConvTy;
7066 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7067 QualType T) override {
7068 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7070 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7071 QualType ConvTy) override {
7072 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
7073 << ConvTy->isEnumeralType() << ConvTy;
7075 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7076 QualType) override {
7077 llvm_unreachable("conversion functions are permitted");
7080 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7083 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
7084 OpenMPClauseKind CKind,
7085 bool StrictlyPositive) {
7086 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7087 !ValExpr->isInstantiationDependent()) {
7088 SourceLocation Loc = ValExpr->getExprLoc();
7090 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7091 if (Value.isInvalid())
7094 ValExpr = Value.get();
7095 // The expression must evaluate to a non-negative integer value.
7096 llvm::APSInt Result;
7097 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
7098 Result.isSigned() &&
7099 !((!StrictlyPositive && Result.isNonNegative()) ||
7100 (StrictlyPositive && Result.isStrictlyPositive()))) {
7101 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
7102 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7103 << ValExpr->getSourceRange();
7110 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7111 SourceLocation StartLoc,
7112 SourceLocation LParenLoc,
7113 SourceLocation EndLoc) {
7114 Expr *ValExpr = NumThreads;
7115 Stmt *HelperValStmt = nullptr;
7116 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7118 // OpenMP [2.5, Restrictions]
7119 // The num_threads expression must evaluate to a positive integer value.
7120 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7121 /*StrictlyPositive=*/true))
7124 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7125 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7126 if (CaptureRegion != OMPD_unknown) {
7127 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7128 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7129 HelperValStmt = buildPreInits(Context, Captures);
7132 return new (Context) OMPNumThreadsClause(
7133 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
7136 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
7137 OpenMPClauseKind CKind,
7138 bool StrictlyPositive) {
7141 if (E->isValueDependent() || E->isTypeDependent() ||
7142 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
7144 llvm::APSInt Result;
7145 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7146 if (ICE.isInvalid())
7148 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7149 (!StrictlyPositive && !Result.isNonNegative())) {
7150 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
7151 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7152 << E->getSourceRange();
7155 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7156 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7157 << E->getSourceRange();
7160 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7161 DSAStack->setAssociatedLoops(Result.getExtValue());
7162 else if (CKind == OMPC_ordered)
7163 DSAStack->setAssociatedLoops(Result.getExtValue());
7167 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7168 SourceLocation LParenLoc,
7169 SourceLocation EndLoc) {
7170 // OpenMP [2.8.1, simd construct, Description]
7171 // The parameter of the safelen clause must be a constant
7172 // positive integer expression.
7173 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7174 if (Safelen.isInvalid())
7176 return new (Context)
7177 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
7180 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7181 SourceLocation LParenLoc,
7182 SourceLocation EndLoc) {
7183 // OpenMP [2.8.1, simd construct, Description]
7184 // The parameter of the simdlen clause must be a constant
7185 // positive integer expression.
7186 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7187 if (Simdlen.isInvalid())
7189 return new (Context)
7190 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7193 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7194 SourceLocation StartLoc,
7195 SourceLocation LParenLoc,
7196 SourceLocation EndLoc) {
7197 // OpenMP [2.7.1, loop construct, Description]
7198 // OpenMP [2.8.1, simd construct, Description]
7199 // OpenMP [2.9.6, distribute construct, Description]
7200 // The parameter of the collapse clause must be a constant
7201 // positive integer expression.
7202 ExprResult NumForLoopsResult =
7203 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7204 if (NumForLoopsResult.isInvalid())
7206 return new (Context)
7207 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
7210 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7211 SourceLocation EndLoc,
7212 SourceLocation LParenLoc,
7213 Expr *NumForLoops) {
7214 // OpenMP [2.7.1, loop construct, Description]
7215 // OpenMP [2.8.1, simd construct, Description]
7216 // OpenMP [2.9.6, distribute construct, Description]
7217 // The parameter of the ordered clause must be a constant
7218 // positive integer expression if any.
7219 if (NumForLoops && LParenLoc.isValid()) {
7220 ExprResult NumForLoopsResult =
7221 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7222 if (NumForLoopsResult.isInvalid())
7224 NumForLoops = NumForLoopsResult.get();
7226 NumForLoops = nullptr;
7227 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
7228 return new (Context)
7229 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7232 OMPClause *Sema::ActOnOpenMPSimpleClause(
7233 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7234 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
7235 OMPClause *Res = nullptr;
7239 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7240 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
7242 case OMPC_proc_bind:
7243 Res = ActOnOpenMPProcBindClause(
7244 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7249 case OMPC_num_threads:
7255 case OMPC_firstprivate:
7256 case OMPC_lastprivate:
7258 case OMPC_reduction:
7262 case OMPC_copyprivate:
7266 case OMPC_mergeable:
7267 case OMPC_threadprivate:
7279 case OMPC_num_teams:
7280 case OMPC_thread_limit:
7282 case OMPC_grainsize:
7284 case OMPC_num_tasks:
7286 case OMPC_dist_schedule:
7287 case OMPC_defaultmap:
7292 case OMPC_use_device_ptr:
7293 case OMPC_is_device_ptr:
7294 llvm_unreachable("Clause is not allowed.");
7300 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7301 ArrayRef<unsigned> Exclude = llvm::None) {
7303 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7304 unsigned Skipped = Exclude.size();
7305 auto S = Exclude.begin(), E = Exclude.end();
7306 for (unsigned i = First; i < Last; ++i) {
7307 if (std::find(S, E, i) != E) {
7312 Values += getOpenMPSimpleClauseTypeName(K, i);
7314 if (i == Bound - Skipped)
7316 else if (i != Bound + 1 - Skipped)
7322 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7323 SourceLocation KindKwLoc,
7324 SourceLocation StartLoc,
7325 SourceLocation LParenLoc,
7326 SourceLocation EndLoc) {
7327 if (Kind == OMPC_DEFAULT_unknown) {
7328 static_assert(OMPC_DEFAULT_unknown > 0,
7329 "OMPC_DEFAULT_unknown not greater than 0");
7330 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
7331 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7332 /*Last=*/OMPC_DEFAULT_unknown)
7333 << getOpenMPClauseName(OMPC_default);
7337 case OMPC_DEFAULT_none:
7338 DSAStack->setDefaultDSANone(KindKwLoc);
7340 case OMPC_DEFAULT_shared:
7341 DSAStack->setDefaultDSAShared(KindKwLoc);
7343 case OMPC_DEFAULT_unknown:
7344 llvm_unreachable("Clause kind is not allowed.");
7347 return new (Context)
7348 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
7351 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7352 SourceLocation KindKwLoc,
7353 SourceLocation StartLoc,
7354 SourceLocation LParenLoc,
7355 SourceLocation EndLoc) {
7356 if (Kind == OMPC_PROC_BIND_unknown) {
7357 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
7358 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7359 /*Last=*/OMPC_PROC_BIND_unknown)
7360 << getOpenMPClauseName(OMPC_proc_bind);
7363 return new (Context)
7364 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
7367 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
7368 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
7369 SourceLocation StartLoc, SourceLocation LParenLoc,
7370 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
7371 SourceLocation EndLoc) {
7372 OMPClause *Res = nullptr;
7375 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7376 assert(Argument.size() == NumberOfElements &&
7377 ArgumentLoc.size() == NumberOfElements);
7378 Res = ActOnOpenMPScheduleClause(
7379 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7380 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7381 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7382 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7383 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
7386 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7387 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7388 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7391 case OMPC_dist_schedule:
7392 Res = ActOnOpenMPDistScheduleClause(
7393 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7394 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7396 case OMPC_defaultmap:
7397 enum { Modifier, DefaultmapKind };
7398 Res = ActOnOpenMPDefaultmapClause(
7399 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7400 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
7401 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7405 case OMPC_num_threads:
7410 case OMPC_proc_bind:
7412 case OMPC_firstprivate:
7413 case OMPC_lastprivate:
7415 case OMPC_reduction:
7419 case OMPC_copyprivate:
7423 case OMPC_mergeable:
7424 case OMPC_threadprivate:
7436 case OMPC_num_teams:
7437 case OMPC_thread_limit:
7439 case OMPC_grainsize:
7441 case OMPC_num_tasks:
7447 case OMPC_use_device_ptr:
7448 case OMPC_is_device_ptr:
7449 llvm_unreachable("Clause is not allowed.");
7454 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7455 OpenMPScheduleClauseModifier M2,
7456 SourceLocation M1Loc, SourceLocation M2Loc) {
7457 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7458 SmallVector<unsigned, 2> Excluded;
7459 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7460 Excluded.push_back(M2);
7461 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7462 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7463 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7464 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7465 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7466 << getListOfPossibleValues(OMPC_schedule,
7467 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7468 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7470 << getOpenMPClauseName(OMPC_schedule);
7476 OMPClause *Sema::ActOnOpenMPScheduleClause(
7477 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
7478 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
7479 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7480 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7481 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7482 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7484 // OpenMP, 2.7.1, Loop Construct, Restrictions
7485 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7487 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7488 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7489 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7490 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7491 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7492 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7493 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7494 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7497 if (Kind == OMPC_SCHEDULE_unknown) {
7499 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7500 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7501 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7502 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7505 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7506 /*Last=*/OMPC_SCHEDULE_unknown);
7508 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7509 << Values << getOpenMPClauseName(OMPC_schedule);
7512 // OpenMP, 2.7.1, Loop Construct, Restrictions
7513 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7514 // schedule(guided).
7515 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7516 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7517 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7518 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7519 diag::err_omp_schedule_nonmonotonic_static);
7522 Expr *ValExpr = ChunkSize;
7523 Stmt *HelperValStmt = nullptr;
7525 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7526 !ChunkSize->isInstantiationDependent() &&
7527 !ChunkSize->containsUnexpandedParameterPack()) {
7528 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7530 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7531 if (Val.isInvalid())
7534 ValExpr = Val.get();
7536 // OpenMP [2.7.1, Restrictions]
7537 // chunk_size must be a loop invariant integer expression with a positive
7539 llvm::APSInt Result;
7540 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7541 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7542 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
7543 << "schedule" << 1 << ChunkSize->getSourceRange();
7546 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7547 !CurContext->isDependentContext()) {
7548 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7549 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7550 HelperValStmt = buildPreInits(Context, Captures);
7555 return new (Context)
7556 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
7557 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
7560 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7561 SourceLocation StartLoc,
7562 SourceLocation EndLoc) {
7563 OMPClause *Res = nullptr;
7566 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7569 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7572 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7574 case OMPC_mergeable:
7575 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7578 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7581 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7584 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7587 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7590 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7593 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7596 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7599 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7603 case OMPC_num_threads:
7609 case OMPC_firstprivate:
7610 case OMPC_lastprivate:
7612 case OMPC_reduction:
7616 case OMPC_copyprivate:
7618 case OMPC_proc_bind:
7619 case OMPC_threadprivate:
7624 case OMPC_num_teams:
7625 case OMPC_thread_limit:
7627 case OMPC_grainsize:
7628 case OMPC_num_tasks:
7630 case OMPC_dist_schedule:
7631 case OMPC_defaultmap:
7636 case OMPC_use_device_ptr:
7637 case OMPC_is_device_ptr:
7638 llvm_unreachable("Clause is not allowed.");
7643 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7644 SourceLocation EndLoc) {
7645 DSAStack->setNowaitRegion();
7646 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7649 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7650 SourceLocation EndLoc) {
7651 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7654 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7655 SourceLocation EndLoc) {
7656 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7659 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7660 SourceLocation EndLoc) {
7661 return new (Context) OMPReadClause(StartLoc, EndLoc);
7664 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7665 SourceLocation EndLoc) {
7666 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7669 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7670 SourceLocation EndLoc) {
7671 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7674 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7675 SourceLocation EndLoc) {
7676 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7679 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7680 SourceLocation EndLoc) {
7681 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7684 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7685 SourceLocation EndLoc) {
7686 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7689 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7690 SourceLocation EndLoc) {
7691 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7694 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7695 SourceLocation EndLoc) {
7696 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7699 OMPClause *Sema::ActOnOpenMPVarListClause(
7700 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7701 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7702 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
7703 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
7704 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7705 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7706 SourceLocation DepLinMapLoc) {
7707 OMPClause *Res = nullptr;
7710 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7712 case OMPC_firstprivate:
7713 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7715 case OMPC_lastprivate:
7716 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7719 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7721 case OMPC_reduction:
7722 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7723 EndLoc, ReductionIdScopeSpec, ReductionId);
7726 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
7727 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
7730 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7734 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7736 case OMPC_copyprivate:
7737 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7740 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7743 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
7744 StartLoc, LParenLoc, EndLoc);
7747 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7748 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7752 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7755 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7757 case OMPC_use_device_ptr:
7758 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7760 case OMPC_is_device_ptr:
7761 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7765 case OMPC_num_threads:
7770 case OMPC_proc_bind:
7775 case OMPC_mergeable:
7776 case OMPC_threadprivate:
7785 case OMPC_num_teams:
7786 case OMPC_thread_limit:
7788 case OMPC_grainsize:
7790 case OMPC_num_tasks:
7792 case OMPC_dist_schedule:
7793 case OMPC_defaultmap:
7796 llvm_unreachable("Clause is not allowed.");
7801 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
7802 ExprObjectKind OK, SourceLocation Loc) {
7803 ExprResult Res = BuildDeclRefExpr(
7804 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7805 if (!Res.isUsable())
7807 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7808 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7809 if (!Res.isUsable())
7812 if (VK != VK_LValue && Res.get()->isGLValue()) {
7813 Res = DefaultLvalueConversion(Res.get());
7814 if (!Res.isUsable())
7820 static std::pair<ValueDecl *, bool>
7821 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7822 SourceRange &ERange, bool AllowArraySection = false) {
7823 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7824 RefExpr->containsUnexpandedParameterPack())
7825 return std::make_pair(nullptr, true);
7827 // OpenMP [3.1, C/C++]
7828 // A list item is a variable name.
7829 // OpenMP [2.9.3.3, Restrictions, p.1]
7830 // A variable that is part of another variable (as an array or
7831 // structure element) cannot appear in a private clause.
7832 RefExpr = RefExpr->IgnoreParens();
7837 } IsArrayExpr = NoArrayExpr;
7838 if (AllowArraySection) {
7839 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7840 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7841 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7842 Base = TempASE->getBase()->IgnoreParenImpCasts();
7844 IsArrayExpr = ArraySubscript;
7845 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7846 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7847 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7848 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7849 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7850 Base = TempASE->getBase()->IgnoreParenImpCasts();
7852 IsArrayExpr = OMPArraySection;
7855 ELoc = RefExpr->getExprLoc();
7856 ERange = RefExpr->getSourceRange();
7857 RefExpr = RefExpr->IgnoreParenImpCasts();
7858 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7859 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7860 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7861 (S.getCurrentThisType().isNull() || !ME ||
7862 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7863 !isa<FieldDecl>(ME->getMemberDecl()))) {
7864 if (IsArrayExpr != NoArrayExpr)
7865 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7870 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7871 : diag::err_omp_expected_var_name_member_expr)
7872 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7874 return std::make_pair(nullptr, false);
7876 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7879 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7880 SourceLocation StartLoc,
7881 SourceLocation LParenLoc,
7882 SourceLocation EndLoc) {
7883 SmallVector<Expr *, 8> Vars;
7884 SmallVector<Expr *, 8> PrivateCopies;
7885 for (auto &RefExpr : VarList) {
7886 assert(RefExpr && "NULL expr in OpenMP private clause.");
7887 SourceLocation ELoc;
7889 Expr *SimpleRefExpr = RefExpr;
7890 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7892 // It will be analyzed later.
7893 Vars.push_back(RefExpr);
7894 PrivateCopies.push_back(nullptr);
7896 ValueDecl *D = Res.first;
7900 QualType Type = D->getType();
7901 auto *VD = dyn_cast<VarDecl>(D);
7903 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7904 // A variable that appears in a private clause must not have an incomplete
7905 // type or a reference type.
7906 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
7908 Type = Type.getNonReferenceType();
7910 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7912 // Variables with the predetermined data-sharing attributes may not be
7913 // listed in data-sharing attributes clauses, except for the cases
7914 // listed below. For these exceptions only, listing a predetermined
7915 // variable in a data-sharing attribute clause is allowed and overrides
7916 // the variable's predetermined data-sharing attributes.
7917 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7918 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
7919 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7920 << getOpenMPClauseName(OMPC_private);
7921 ReportOriginalDSA(*this, DSAStack, D, DVar);
7925 auto CurrDir = DSAStack->getCurrentDirective();
7926 // Variably modified types are not supported for tasks.
7927 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
7928 isOpenMPTaskingDirective(CurrDir)) {
7929 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7930 << getOpenMPClauseName(OMPC_private) << Type
7931 << getOpenMPDirectiveName(CurrDir);
7934 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7935 Diag(D->getLocation(),
7936 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7941 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7942 // A list item cannot appear in both a map clause and a data-sharing
7943 // attribute clause on the same construct
7944 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
7945 CurrDir == OMPD_target_teams ||
7946 CurrDir == OMPD_target_teams_distribute ||
7947 CurrDir == OMPD_target_teams_distribute_parallel_for ||
7948 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
7949 CurrDir == OMPD_target_teams_distribute_simd ||
7950 CurrDir == OMPD_target_parallel_for_simd ||
7951 CurrDir == OMPD_target_parallel_for) {
7952 OpenMPClauseKind ConflictKind;
7953 if (DSAStack->checkMappableExprComponentListsForDecl(
7954 VD, /*CurrentRegionOnly=*/true,
7955 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7956 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7957 ConflictKind = WhereFoundClauseKind;
7960 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
7961 << getOpenMPClauseName(OMPC_private)
7962 << getOpenMPClauseName(ConflictKind)
7963 << getOpenMPDirectiveName(CurrDir);
7964 ReportOriginalDSA(*this, DSAStack, D, DVar);
7969 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7970 // A variable of class type (or array thereof) that appears in a private
7971 // clause requires an accessible, unambiguous default constructor for the
7973 // Generate helper private variable and initialize it with the default
7974 // value. The address of the original variable is replaced by the address of
7975 // the new private variable in CodeGen. This new variable is not added to
7976 // IdResolver, so the code in the OpenMP region uses original variable for
7977 // proper diagnostics.
7978 Type = Type.getUnqualifiedType();
7979 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7980 D->hasAttrs() ? &D->getAttrs() : nullptr);
7981 ActOnUninitializedDecl(VDPrivate);
7982 if (VDPrivate->isInvalidDecl())
7984 auto VDPrivateRefExpr = buildDeclRefExpr(
7985 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
7987 DeclRefExpr *Ref = nullptr;
7988 if (!VD && !CurContext->isDependentContext())
7989 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
7990 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
7991 Vars.push_back((VD || CurContext->isDependentContext())
7992 ? RefExpr->IgnoreParens()
7994 PrivateCopies.push_back(VDPrivateRefExpr);
8000 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8005 class DiagsUninitializedSeveretyRAII {
8007 DiagnosticsEngine &Diags;
8008 SourceLocation SavedLoc;
8012 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8014 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8016 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8017 /*Map*/ diag::Severity::Ignored, Loc);
8020 ~DiagsUninitializedSeveretyRAII() {
8022 Diags.popMappings(SavedLoc);
8027 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8028 SourceLocation StartLoc,
8029 SourceLocation LParenLoc,
8030 SourceLocation EndLoc) {
8031 SmallVector<Expr *, 8> Vars;
8032 SmallVector<Expr *, 8> PrivateCopies;
8033 SmallVector<Expr *, 8> Inits;
8034 SmallVector<Decl *, 4> ExprCaptures;
8035 bool IsImplicitClause =
8036 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8037 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8039 for (auto &RefExpr : VarList) {
8040 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
8041 SourceLocation ELoc;
8043 Expr *SimpleRefExpr = RefExpr;
8044 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
8046 // It will be analyzed later.
8047 Vars.push_back(RefExpr);
8048 PrivateCopies.push_back(nullptr);
8049 Inits.push_back(nullptr);
8051 ValueDecl *D = Res.first;
8055 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
8056 QualType Type = D->getType();
8057 auto *VD = dyn_cast<VarDecl>(D);
8059 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8060 // A variable that appears in a private clause must not have an incomplete
8061 // type or a reference type.
8062 if (RequireCompleteType(ELoc, Type,
8063 diag::err_omp_firstprivate_incomplete_type))
8065 Type = Type.getNonReferenceType();
8067 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8068 // A variable of class type (or array thereof) that appears in a private
8069 // clause requires an accessible, unambiguous copy constructor for the
8071 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
8073 // If an implicit firstprivate variable found it was checked already.
8074 DSAStackTy::DSAVarData TopDVar;
8075 if (!IsImplicitClause) {
8076 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8078 bool IsConstant = ElemType.isConstant(Context);
8079 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8080 // A list item that specifies a given variable may not appear in more
8081 // than one clause on the same directive, except that a variable may be
8082 // specified in both firstprivate and lastprivate clauses.
8083 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
8084 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
8085 Diag(ELoc, diag::err_omp_wrong_dsa)
8086 << getOpenMPClauseName(DVar.CKind)
8087 << getOpenMPClauseName(OMPC_firstprivate);
8088 ReportOriginalDSA(*this, DSAStack, D, DVar);
8092 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8094 // Variables with the predetermined data-sharing attributes may not be
8095 // listed in data-sharing attributes clauses, except for the cases
8096 // listed below. For these exceptions only, listing a predetermined
8097 // variable in a data-sharing attribute clause is allowed and overrides
8098 // the variable's predetermined data-sharing attributes.
8099 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8100 // in a Construct, C/C++, p.2]
8101 // Variables with const-qualified type having no mutable member may be
8102 // listed in a firstprivate clause, even if they are static data members.
8103 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
8104 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8105 Diag(ELoc, diag::err_omp_wrong_dsa)
8106 << getOpenMPClauseName(DVar.CKind)
8107 << getOpenMPClauseName(OMPC_firstprivate);
8108 ReportOriginalDSA(*this, DSAStack, D, DVar);
8112 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8113 // OpenMP [2.9.3.4, Restrictions, p.2]
8114 // A list item that is private within a parallel region must not appear
8115 // in a firstprivate clause on a worksharing construct if any of the
8116 // worksharing regions arising from the worksharing construct ever bind
8117 // to any of the parallel regions arising from the parallel construct.
8118 if (isOpenMPWorksharingDirective(CurrDir) &&
8119 !isOpenMPParallelDirective(CurrDir) &&
8120 !isOpenMPTeamsDirective(CurrDir)) {
8121 DVar = DSAStack->getImplicitDSA(D, true);
8122 if (DVar.CKind != OMPC_shared &&
8123 (isOpenMPParallelDirective(DVar.DKind) ||
8124 DVar.DKind == OMPD_unknown)) {
8125 Diag(ELoc, diag::err_omp_required_access)
8126 << getOpenMPClauseName(OMPC_firstprivate)
8127 << getOpenMPClauseName(OMPC_shared);
8128 ReportOriginalDSA(*this, DSAStack, D, DVar);
8132 // OpenMP [2.9.3.4, Restrictions, p.3]
8133 // A list item that appears in a reduction clause of a parallel construct
8134 // must not appear in a firstprivate clause on a worksharing or task
8135 // construct if any of the worksharing or task regions arising from the
8136 // worksharing or task construct ever bind to any of the parallel regions
8137 // arising from the parallel construct.
8138 // OpenMP [2.9.3.4, Restrictions, p.4]
8139 // A list item that appears in a reduction clause in worksharing
8140 // construct must not appear in a firstprivate clause in a task construct
8141 // encountered during execution of any of the worksharing regions arising
8142 // from the worksharing construct.
8143 if (isOpenMPTaskingDirective(CurrDir)) {
8144 DVar = DSAStack->hasInnermostDSA(
8145 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8146 [](OpenMPDirectiveKind K) -> bool {
8147 return isOpenMPParallelDirective(K) ||
8148 isOpenMPWorksharingDirective(K);
8151 if (DVar.CKind == OMPC_reduction &&
8152 (isOpenMPParallelDirective(DVar.DKind) ||
8153 isOpenMPWorksharingDirective(DVar.DKind))) {
8154 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8155 << getOpenMPDirectiveName(DVar.DKind);
8156 ReportOriginalDSA(*this, DSAStack, D, DVar);
8161 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8162 // A list item that is private within a teams region must not appear in a
8163 // firstprivate clause on a distribute construct if any of the distribute
8164 // regions arising from the distribute construct ever bind to any of the
8165 // teams regions arising from the teams construct.
8166 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8167 // A list item that appears in a reduction clause of a teams construct
8168 // must not appear in a firstprivate clause on a distribute construct if
8169 // any of the distribute regions arising from the distribute construct
8170 // ever bind to any of the teams regions arising from the teams construct.
8171 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8172 // A list item may appear in a firstprivate or lastprivate clause but not
8174 if (CurrDir == OMPD_distribute) {
8175 DVar = DSAStack->hasInnermostDSA(
8176 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
8177 [](OpenMPDirectiveKind K) -> bool {
8178 return isOpenMPTeamsDirective(K);
8181 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
8182 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
8183 ReportOriginalDSA(*this, DSAStack, D, DVar);
8186 DVar = DSAStack->hasInnermostDSA(
8187 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8188 [](OpenMPDirectiveKind K) -> bool {
8189 return isOpenMPTeamsDirective(K);
8192 if (DVar.CKind == OMPC_reduction &&
8193 isOpenMPTeamsDirective(DVar.DKind)) {
8194 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
8195 ReportOriginalDSA(*this, DSAStack, D, DVar);
8198 DVar = DSAStack->getTopDSA(D, false);
8199 if (DVar.CKind == OMPC_lastprivate) {
8200 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8201 ReportOriginalDSA(*this, DSAStack, D, DVar);
8205 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8206 // A list item cannot appear in both a map clause and a data-sharing
8207 // attribute clause on the same construct
8208 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
8209 CurrDir == OMPD_target_teams ||
8210 CurrDir == OMPD_target_teams_distribute ||
8211 CurrDir == OMPD_target_teams_distribute_parallel_for ||
8212 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
8213 CurrDir == OMPD_target_teams_distribute_simd ||
8214 CurrDir == OMPD_target_parallel_for_simd ||
8215 CurrDir == OMPD_target_parallel_for) {
8216 OpenMPClauseKind ConflictKind;
8217 if (DSAStack->checkMappableExprComponentListsForDecl(
8218 VD, /*CurrentRegionOnly=*/true,
8219 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8220 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8221 ConflictKind = WhereFoundClauseKind;
8224 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
8225 << getOpenMPClauseName(OMPC_firstprivate)
8226 << getOpenMPClauseName(ConflictKind)
8227 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8228 ReportOriginalDSA(*this, DSAStack, D, DVar);
8234 // Variably modified types are not supported for tasks.
8235 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
8236 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
8237 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8238 << getOpenMPClauseName(OMPC_firstprivate) << Type
8239 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8242 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8243 Diag(D->getLocation(),
8244 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8249 Type = Type.getUnqualifiedType();
8250 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8251 D->hasAttrs() ? &D->getAttrs() : nullptr);
8252 // Generate helper private variable and initialize it with the value of the
8253 // original variable. The address of the original variable is replaced by
8254 // the address of the new private variable in the CodeGen. This new variable
8255 // is not added to IdResolver, so the code in the OpenMP region uses
8256 // original variable for proper diagnostics and variable capturing.
8257 Expr *VDInitRefExpr = nullptr;
8258 // For arrays generate initializer for single element and replace it by the
8259 // original array element in CodeGen.
8260 if (Type->isArrayType()) {
8262 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
8263 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
8264 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
8265 ElemType = ElemType.getUnqualifiedType();
8266 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
8267 ".firstprivate.temp");
8268 InitializedEntity Entity =
8269 InitializedEntity::InitializeVariable(VDInitTemp);
8270 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8272 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8273 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8274 if (Result.isInvalid())
8275 VDPrivate->setInvalidDecl();
8277 VDPrivate->setInit(Result.getAs<Expr>());
8278 // Remove temp variable declaration.
8279 Context.Deallocate(VDInitTemp);
8281 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8282 ".firstprivate.temp");
8283 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8284 RefExpr->getExprLoc());
8285 AddInitializerToDecl(VDPrivate,
8286 DefaultLvalueConversion(VDInitRefExpr).get(),
8287 /*DirectInit=*/false);
8289 if (VDPrivate->isInvalidDecl()) {
8290 if (IsImplicitClause) {
8291 Diag(RefExpr->getExprLoc(),
8292 diag::note_omp_task_predetermined_firstprivate_here);
8296 CurContext->addDecl(VDPrivate);
8297 auto VDPrivateRefExpr = buildDeclRefExpr(
8298 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8299 RefExpr->getExprLoc());
8300 DeclRefExpr *Ref = nullptr;
8301 if (!VD && !CurContext->isDependentContext()) {
8302 if (TopDVar.CKind == OMPC_lastprivate)
8303 Ref = TopDVar.PrivateCopy;
8305 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8306 if (!IsOpenMPCapturedDecl(D))
8307 ExprCaptures.push_back(Ref->getDecl());
8310 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
8311 Vars.push_back((VD || CurContext->isDependentContext())
8312 ? RefExpr->IgnoreParens()
8314 PrivateCopies.push_back(VDPrivateRefExpr);
8315 Inits.push_back(VDInitRefExpr);
8321 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
8322 Vars, PrivateCopies, Inits,
8323 buildPreInits(Context, ExprCaptures));
8326 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8327 SourceLocation StartLoc,
8328 SourceLocation LParenLoc,
8329 SourceLocation EndLoc) {
8330 SmallVector<Expr *, 8> Vars;
8331 SmallVector<Expr *, 8> SrcExprs;
8332 SmallVector<Expr *, 8> DstExprs;
8333 SmallVector<Expr *, 8> AssignmentOps;
8334 SmallVector<Decl *, 4> ExprCaptures;
8335 SmallVector<Expr *, 4> ExprPostUpdates;
8336 for (auto &RefExpr : VarList) {
8337 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
8338 SourceLocation ELoc;
8340 Expr *SimpleRefExpr = RefExpr;
8341 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
8343 // It will be analyzed later.
8344 Vars.push_back(RefExpr);
8345 SrcExprs.push_back(nullptr);
8346 DstExprs.push_back(nullptr);
8347 AssignmentOps.push_back(nullptr);
8349 ValueDecl *D = Res.first;
8353 QualType Type = D->getType();
8354 auto *VD = dyn_cast<VarDecl>(D);
8356 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8357 // A variable that appears in a lastprivate clause must not have an
8358 // incomplete type or a reference type.
8359 if (RequireCompleteType(ELoc, Type,
8360 diag::err_omp_lastprivate_incomplete_type))
8362 Type = Type.getNonReferenceType();
8364 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8366 // Variables with the predetermined data-sharing attributes may not be
8367 // listed in data-sharing attributes clauses, except for the cases
8369 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8370 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
8371 DVar.CKind != OMPC_firstprivate &&
8372 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8373 Diag(ELoc, diag::err_omp_wrong_dsa)
8374 << getOpenMPClauseName(DVar.CKind)
8375 << getOpenMPClauseName(OMPC_lastprivate);
8376 ReportOriginalDSA(*this, DSAStack, D, DVar);
8380 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8381 // OpenMP [2.14.3.5, Restrictions, p.2]
8382 // A list item that is private within a parallel region, or that appears in
8383 // the reduction clause of a parallel construct, must not appear in a
8384 // lastprivate clause on a worksharing construct if any of the corresponding
8385 // worksharing regions ever binds to any of the corresponding parallel
8387 DSAStackTy::DSAVarData TopDVar = DVar;
8388 if (isOpenMPWorksharingDirective(CurrDir) &&
8389 !isOpenMPParallelDirective(CurrDir) &&
8390 !isOpenMPTeamsDirective(CurrDir)) {
8391 DVar = DSAStack->getImplicitDSA(D, true);
8392 if (DVar.CKind != OMPC_shared) {
8393 Diag(ELoc, diag::err_omp_required_access)
8394 << getOpenMPClauseName(OMPC_lastprivate)
8395 << getOpenMPClauseName(OMPC_shared);
8396 ReportOriginalDSA(*this, DSAStack, D, DVar);
8401 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8402 // A list item may appear in a firstprivate or lastprivate clause but not
8404 if (CurrDir == OMPD_distribute) {
8405 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8406 if (DVar.CKind == OMPC_firstprivate) {
8407 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8408 ReportOriginalDSA(*this, DSAStack, D, DVar);
8413 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
8414 // A variable of class type (or array thereof) that appears in a
8415 // lastprivate clause requires an accessible, unambiguous default
8416 // constructor for the class type, unless the list item is also specified
8417 // in a firstprivate clause.
8418 // A variable of class type (or array thereof) that appears in a
8419 // lastprivate clause requires an accessible, unambiguous copy assignment
8420 // operator for the class type.
8421 Type = Context.getBaseElementType(Type).getNonReferenceType();
8422 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
8423 Type.getUnqualifiedType(), ".lastprivate.src",
8424 D->hasAttrs() ? &D->getAttrs() : nullptr);
8425 auto *PseudoSrcExpr =
8426 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
8428 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
8429 D->hasAttrs() ? &D->getAttrs() : nullptr);
8430 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
8431 // For arrays generate assignment operation for single element and replace
8432 // it by the original array element in CodeGen.
8433 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
8434 PseudoDstExpr, PseudoSrcExpr);
8435 if (AssignmentOp.isInvalid())
8437 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
8438 /*DiscardedValue=*/true);
8439 if (AssignmentOp.isInvalid())
8442 DeclRefExpr *Ref = nullptr;
8443 if (!VD && !CurContext->isDependentContext()) {
8444 if (TopDVar.CKind == OMPC_firstprivate)
8445 Ref = TopDVar.PrivateCopy;
8447 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8448 if (!IsOpenMPCapturedDecl(D))
8449 ExprCaptures.push_back(Ref->getDecl());
8451 if (TopDVar.CKind == OMPC_firstprivate ||
8452 (!IsOpenMPCapturedDecl(D) &&
8453 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
8454 ExprResult RefRes = DefaultLvalueConversion(Ref);
8455 if (!RefRes.isUsable())
8457 ExprResult PostUpdateRes =
8458 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8460 if (!PostUpdateRes.isUsable())
8462 ExprPostUpdates.push_back(
8463 IgnoredValueConversions(PostUpdateRes.get()).get());
8466 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
8467 Vars.push_back((VD || CurContext->isDependentContext())
8468 ? RefExpr->IgnoreParens()
8470 SrcExprs.push_back(PseudoSrcExpr);
8471 DstExprs.push_back(PseudoDstExpr);
8472 AssignmentOps.push_back(AssignmentOp.get());
8478 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
8479 Vars, SrcExprs, DstExprs, AssignmentOps,
8480 buildPreInits(Context, ExprCaptures),
8481 buildPostUpdate(*this, ExprPostUpdates));
8484 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8485 SourceLocation StartLoc,
8486 SourceLocation LParenLoc,
8487 SourceLocation EndLoc) {
8488 SmallVector<Expr *, 8> Vars;
8489 for (auto &RefExpr : VarList) {
8490 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
8491 SourceLocation ELoc;
8493 Expr *SimpleRefExpr = RefExpr;
8494 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
8496 // It will be analyzed later.
8497 Vars.push_back(RefExpr);
8499 ValueDecl *D = Res.first;
8503 auto *VD = dyn_cast<VarDecl>(D);
8504 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8506 // Variables with the predetermined data-sharing attributes may not be
8507 // listed in data-sharing attributes clauses, except for the cases
8508 // listed below. For these exceptions only, listing a predetermined
8509 // variable in a data-sharing attribute clause is allowed and overrides
8510 // the variable's predetermined data-sharing attributes.
8511 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8512 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8514 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8515 << getOpenMPClauseName(OMPC_shared);
8516 ReportOriginalDSA(*this, DSAStack, D, DVar);
8520 DeclRefExpr *Ref = nullptr;
8521 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
8522 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8523 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
8524 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8525 ? RefExpr->IgnoreParens()
8532 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8536 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8540 bool VisitDeclRefExpr(DeclRefExpr *E) {
8541 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
8542 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
8543 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8545 if (DVar.CKind != OMPC_unknown)
8547 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8548 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8550 if (DVarPrivate.CKind != OMPC_unknown)
8556 bool VisitStmt(Stmt *S) {
8557 for (auto Child : S->children()) {
8558 if (Child && Visit(Child))
8563 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
8568 // Transform MemberExpression for specified FieldDecl of current class to
8569 // DeclRefExpr to specified OMPCapturedExprDecl.
8570 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8571 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8573 DeclRefExpr *CapturedExpr;
8576 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8577 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8579 ExprResult TransformMemberExpr(MemberExpr *E) {
8580 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8581 E->getMemberDecl() == Field) {
8582 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
8583 return CapturedExpr;
8585 return BaseTransform::TransformMemberExpr(E);
8587 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8591 template <typename T>
8592 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8593 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8594 for (auto &Set : Lookups) {
8595 for (auto *D : Set) {
8596 if (auto Res = Gen(cast<ValueDecl>(D)))
8604 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8605 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8606 const DeclarationNameInfo &ReductionId, QualType Ty,
8607 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8608 if (ReductionIdScopeSpec.isInvalid())
8610 SmallVector<UnresolvedSet<8>, 4> Lookups;
8612 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8613 Lookup.suppressDiagnostics();
8614 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8615 auto *D = Lookup.getRepresentativeDecl();
8618 } while (S && !S->isDeclScope(D));
8621 Lookups.push_back(UnresolvedSet<8>());
8622 Lookups.back().append(Lookup.begin(), Lookup.end());
8625 } else if (auto *ULE =
8626 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8627 Lookups.push_back(UnresolvedSet<8>());
8628 Decl *PrevD = nullptr;
8629 for (auto *D : ULE->decls()) {
8631 Lookups.push_back(UnresolvedSet<8>());
8632 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8633 Lookups.back().addDecl(DRD);
8637 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8638 Ty->containsUnexpandedParameterPack() ||
8639 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8640 return !D->isInvalidDecl() &&
8641 (D->getType()->isDependentType() ||
8642 D->getType()->isInstantiationDependentType() ||
8643 D->getType()->containsUnexpandedParameterPack());
8645 UnresolvedSet<8> ResSet;
8646 for (auto &Set : Lookups) {
8647 ResSet.append(Set.begin(), Set.end());
8648 // The last item marks the end of all declarations at the specified scope.
8649 ResSet.addDecl(Set[Set.size() - 1]);
8651 return UnresolvedLookupExpr::Create(
8652 SemaRef.Context, /*NamingClass=*/nullptr,
8653 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8654 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8656 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8657 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8658 if (!D->isInvalidDecl() &&
8659 SemaRef.Context.hasSameType(D->getType(), Ty))
8663 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8664 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8665 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8666 if (!D->isInvalidDecl() &&
8667 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8668 !Ty.isMoreQualifiedThan(D->getType()))
8672 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8673 /*DetectVirtual=*/false);
8674 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8675 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8676 VD->getType().getUnqualifiedType()))) {
8677 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8679 Sema::AR_inaccessible) {
8680 SemaRef.BuildBasePathArray(Paths, BasePath);
8681 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8686 if (ReductionIdScopeSpec.isSet()) {
8687 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8693 OMPClause *Sema::ActOnOpenMPReductionClause(
8694 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8695 SourceLocation ColonLoc, SourceLocation EndLoc,
8696 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8697 ArrayRef<Expr *> UnresolvedReductions) {
8698 auto DN = ReductionId.getName();
8699 auto OOK = DN.getCXXOverloadedOperator();
8700 BinaryOperatorKind BOK = BO_Comma;
8702 // OpenMP [2.14.3.6, reduction clause]
8704 // reduction-identifier is either an identifier or one of the following
8705 // operators: +, -, *, &, |, ^, && and ||
8707 // reduction-identifier is either an id-expression or one of the following
8708 // operators: +, -, *, &, |, ^, && and ||
8709 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8736 case OO_Array_Delete:
8745 case OO_GreaterEqual:
8750 case OO_PercentEqual:
8755 case OO_GreaterGreater:
8756 case OO_LessLessEqual:
8757 case OO_GreaterGreaterEqual:
8759 case OO_ExclaimEqual:
8767 case OO_Conditional:
8769 case NUM_OVERLOADED_OPERATORS:
8770 llvm_unreachable("Unexpected reduction identifier");
8772 if (auto II = DN.getAsIdentifierInfo()) {
8773 if (II->isStr("max"))
8775 else if (II->isStr("min"))
8780 SourceRange ReductionIdRange;
8781 if (ReductionIdScopeSpec.isValid())
8782 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
8783 ReductionIdRange.setEnd(ReductionId.getEndLoc());
8785 SmallVector<Expr *, 8> Vars;
8786 SmallVector<Expr *, 8> Privates;
8787 SmallVector<Expr *, 8> LHSs;
8788 SmallVector<Expr *, 8> RHSs;
8789 SmallVector<Expr *, 8> ReductionOps;
8790 SmallVector<Decl *, 4> ExprCaptures;
8791 SmallVector<Expr *, 4> ExprPostUpdates;
8792 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8793 bool FirstIter = true;
8794 for (auto RefExpr : VarList) {
8795 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
8796 // OpenMP [2.1, C/C++]
8797 // A list item is a variable or array section, subject to the restrictions
8798 // specified in Section 2.4 on page 42 and in each of the sections
8799 // describing clauses and directives for which a list appears.
8800 // OpenMP [2.14.3.3, Restrictions, p.1]
8801 // A variable that is part of another variable (as an array or
8802 // structure element) cannot appear in a private clause.
8803 if (!FirstIter && IR != ER)
8806 SourceLocation ELoc;
8808 Expr *SimpleRefExpr = RefExpr;
8809 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8810 /*AllowArraySection=*/true);
8812 // It will be analyzed later.
8813 Vars.push_back(RefExpr);
8814 Privates.push_back(nullptr);
8815 LHSs.push_back(nullptr);
8816 RHSs.push_back(nullptr);
8817 // Try to find 'declare reduction' corresponding construct before using
8818 // builtin/overloaded operators.
8819 QualType Type = Context.DependentTy;
8820 CXXCastPath BasePath;
8821 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8822 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8823 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8824 if (CurContext->isDependentContext() &&
8825 (DeclareReductionRef.isUnset() ||
8826 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8827 ReductionOps.push_back(DeclareReductionRef.get());
8829 ReductionOps.push_back(nullptr);
8831 ValueDecl *D = Res.first;
8836 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8837 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8839 Type = ASE->getType().getNonReferenceType();
8841 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8842 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8843 Type = ATy->getElementType();
8845 Type = BaseType->getPointeeType();
8846 Type = Type.getNonReferenceType();
8848 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8849 auto *VD = dyn_cast<VarDecl>(D);
8851 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8852 // A variable that appears in a private clause must not have an incomplete
8853 // type or a reference type.
8854 if (RequireCompleteType(ELoc, Type,
8855 diag::err_omp_reduction_incomplete_type))
8857 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8858 // A list item that appears in a reduction clause must not be
8860 if (Type.getNonReferenceType().isConstant(Context)) {
8861 Diag(ELoc, diag::err_omp_const_reduction_list_item)
8862 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
8863 if (!ASE && !OASE) {
8864 bool IsDecl = !VD ||
8865 VD->isThisDeclarationADefinition(Context) ==
8866 VarDecl::DeclarationOnly;
8867 Diag(D->getLocation(),
8868 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8873 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8874 // If a list-item is a reference type then it must bind to the same object
8875 // for all threads of the team.
8876 if (!ASE && !OASE && VD) {
8877 VarDecl *VDDef = VD->getDefinition();
8878 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
8879 DSARefChecker Check(DSAStack);
8880 if (Check.Visit(VDDef->getInit())) {
8881 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8882 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8888 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8890 // Variables with the predetermined data-sharing attributes may not be
8891 // listed in data-sharing attributes clauses, except for the cases
8892 // listed below. For these exceptions only, listing a predetermined
8893 // variable in a data-sharing attribute clause is allowed and overrides
8894 // the variable's predetermined data-sharing attributes.
8895 // OpenMP [2.14.3.6, Restrictions, p.3]
8896 // Any number of reduction clauses can be specified on the directive,
8897 // but a list item can appear only once in the reduction clauses for that
8899 DSAStackTy::DSAVarData DVar;
8900 DVar = DSAStack->getTopDSA(D, false);
8901 if (DVar.CKind == OMPC_reduction) {
8902 Diag(ELoc, diag::err_omp_once_referenced)
8903 << getOpenMPClauseName(OMPC_reduction);
8905 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
8906 } else if (DVar.CKind != OMPC_unknown) {
8907 Diag(ELoc, diag::err_omp_wrong_dsa)
8908 << getOpenMPClauseName(DVar.CKind)
8909 << getOpenMPClauseName(OMPC_reduction);
8910 ReportOriginalDSA(*this, DSAStack, D, DVar);
8914 // OpenMP [2.14.3.6, Restrictions, p.1]
8915 // A list item that appears in a reduction clause of a worksharing
8916 // construct must be shared in the parallel regions to which any of the
8917 // worksharing regions arising from the worksharing construct bind.
8918 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8919 if (isOpenMPWorksharingDirective(CurrDir) &&
8920 !isOpenMPParallelDirective(CurrDir) &&
8921 !isOpenMPTeamsDirective(CurrDir)) {
8922 DVar = DSAStack->getImplicitDSA(D, true);
8923 if (DVar.CKind != OMPC_shared) {
8924 Diag(ELoc, diag::err_omp_required_access)
8925 << getOpenMPClauseName(OMPC_reduction)
8926 << getOpenMPClauseName(OMPC_shared);
8927 ReportOriginalDSA(*this, DSAStack, D, DVar);
8932 // Try to find 'declare reduction' corresponding construct before using
8933 // builtin/overloaded operators.
8934 CXXCastPath BasePath;
8935 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8936 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8937 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8938 if (DeclareReductionRef.isInvalid())
8940 if (CurContext->isDependentContext() &&
8941 (DeclareReductionRef.isUnset() ||
8942 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8943 Vars.push_back(RefExpr);
8944 Privates.push_back(nullptr);
8945 LHSs.push_back(nullptr);
8946 RHSs.push_back(nullptr);
8947 ReductionOps.push_back(DeclareReductionRef.get());
8950 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8951 // Not allowed reduction identifier is found.
8952 Diag(ReductionId.getLocStart(),
8953 diag::err_omp_unknown_reduction_identifier)
8954 << Type << ReductionIdRange;
8958 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8959 // The type of a list item that appears in a reduction clause must be valid
8960 // for the reduction-identifier. For a max or min reduction in C, the type
8961 // of the list item must be an allowed arithmetic data type: char, int,
8962 // float, double, or _Bool, possibly modified with long, short, signed, or
8963 // unsigned. For a max or min reduction in C++, the type of the list item
8964 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8965 // double, or bool, possibly modified with long, short, signed, or unsigned.
8966 if (DeclareReductionRef.isUnset()) {
8967 if ((BOK == BO_GT || BOK == BO_LT) &&
8968 !(Type->isScalarType() ||
8969 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8970 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8971 << getLangOpts().CPlusPlus;
8972 if (!ASE && !OASE) {
8973 bool IsDecl = !VD ||
8974 VD->isThisDeclarationADefinition(Context) ==
8975 VarDecl::DeclarationOnly;
8976 Diag(D->getLocation(),
8977 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8982 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8983 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8984 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8985 if (!ASE && !OASE) {
8986 bool IsDecl = !VD ||
8987 VD->isThisDeclarationADefinition(Context) ==
8988 VarDecl::DeclarationOnly;
8989 Diag(D->getLocation(),
8990 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8997 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
8998 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
8999 D->hasAttrs() ? &D->getAttrs() : nullptr);
9000 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
9001 D->hasAttrs() ? &D->getAttrs() : nullptr);
9002 auto PrivateTy = Type;
9005 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
9006 // For arrays/array sections only:
9007 // Create pseudo array type for private copy. The size for this array will
9008 // be generated during codegen.
9009 // For array subscripts or single variables Private Ty is the same as Type
9010 // (type of the variable or single array element).
9011 PrivateTy = Context.getVariableArrayType(
9012 Type, new (Context) OpaqueValueExpr(SourceLocation(),
9013 Context.getSizeType(), VK_RValue),
9014 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
9015 } else if (!ASE && !OASE &&
9016 Context.getAsArrayType(D->getType().getNonReferenceType()))
9017 PrivateTy = D->getType().getNonReferenceType();
9019 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
9020 D->hasAttrs() ? &D->getAttrs() : nullptr);
9021 // Add initializer for private variable.
9022 Expr *Init = nullptr;
9023 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
9024 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
9025 if (DeclareReductionRef.isUsable()) {
9026 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9027 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9028 if (DRD->getInitializer()) {
9030 RHSVD->setInit(DRDRef);
9031 RHSVD->setInitStyle(VarDecl::CallInit);
9039 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9040 if (Type->isScalarType() || Type->isAnyComplexType())
9041 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
9045 if (Type->isScalarType() || Type->isAnyComplexType()) {
9046 // '*' and '&&' reduction ops - initializer is '1'.
9047 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
9051 // '&' reduction op - initializer is '~0'.
9052 QualType OrigType = Type;
9053 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9054 Type = ComplexTy->getElementType();
9055 if (Type->isRealFloatingType()) {
9056 llvm::APFloat InitValue =
9057 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9059 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9061 } else if (Type->isScalarType()) {
9062 auto Size = Context.getTypeSize(Type);
9063 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9064 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9065 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9067 if (Init && OrigType->isAnyComplexType()) {
9068 // Init = 0xFFFF + 0xFFFFi;
9069 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
9070 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
9077 // 'min' reduction op - initializer is 'Largest representable number in
9078 // the reduction list item type'.
9079 // 'max' reduction op - initializer is 'Least representable number in
9080 // the reduction list item type'.
9081 if (Type->isIntegerType() || Type->isPointerType()) {
9082 bool IsSigned = Type->hasSignedIntegerRepresentation();
9083 auto Size = Context.getTypeSize(Type);
9085 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9086 llvm::APInt InitValue =
9088 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9089 : llvm::APInt::getMinValue(Size)
9090 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9091 : llvm::APInt::getMaxValue(Size);
9092 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9093 if (Type->isPointerType()) {
9094 // Cast to pointer type.
9095 auto CastExpr = BuildCStyleCastExpr(
9096 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
9097 SourceLocation(), Init);
9098 if (CastExpr.isInvalid())
9100 Init = CastExpr.get();
9102 } else if (Type->isRealFloatingType()) {
9103 llvm::APFloat InitValue = llvm::APFloat::getLargest(
9104 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9105 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9133 llvm_unreachable("Unexpected reduction operation");
9136 if (Init && DeclareReductionRef.isUnset()) {
9137 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
9139 ActOnUninitializedDecl(RHSVD);
9140 if (RHSVD->isInvalidDecl())
9142 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
9143 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
9144 << ReductionIdRange;
9147 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9148 Diag(D->getLocation(),
9149 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9153 // Store initializer for single element in private copy. Will be used during
9155 PrivateVD->setInit(RHSVD->getInit());
9156 PrivateVD->setInitStyle(RHSVD->getInitStyle());
9157 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
9158 ExprResult ReductionOp;
9159 if (DeclareReductionRef.isUsable()) {
9160 QualType RedTy = DeclareReductionRef.get()->getType();
9161 QualType PtrRedTy = Context.getPointerType(RedTy);
9162 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9163 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
9164 if (!BasePath.empty()) {
9165 LHS = DefaultLvalueConversion(LHS.get());
9166 RHS = DefaultLvalueConversion(RHS.get());
9167 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9168 CK_UncheckedDerivedToBase, LHS.get(),
9169 &BasePath, LHS.get()->getValueKind());
9170 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9171 CK_UncheckedDerivedToBase, RHS.get(),
9172 &BasePath, RHS.get()->getValueKind());
9174 FunctionProtoType::ExtProtoInfo EPI;
9175 QualType Params[] = {PtrRedTy, PtrRedTy};
9176 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9177 auto *OVE = new (Context) OpaqueValueExpr(
9178 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
9179 DefaultLvalueConversion(DeclareReductionRef.get()).get());
9180 Expr *Args[] = {LHS.get(), RHS.get()};
9181 ReductionOp = new (Context)
9182 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9184 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
9185 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
9186 if (ReductionOp.isUsable()) {
9187 if (BOK != BO_LT && BOK != BO_GT) {
9189 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9190 BO_Assign, LHSDRE, ReductionOp.get());
9192 auto *ConditionalOp = new (Context) ConditionalOperator(
9193 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9194 RHSDRE, Type, VK_LValue, OK_Ordinary);
9196 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9197 BO_Assign, LHSDRE, ConditionalOp);
9199 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
9201 if (ReductionOp.isInvalid())
9205 DeclRefExpr *Ref = nullptr;
9206 Expr *VarsExpr = RefExpr->IgnoreParens();
9207 if (!VD && !CurContext->isDependentContext()) {
9209 TransformExprToCaptures RebuildToCapture(*this, D);
9211 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9212 Ref = RebuildToCapture.getCapturedExpr();
9215 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9217 if (!IsOpenMPCapturedDecl(D)) {
9218 ExprCaptures.push_back(Ref->getDecl());
9219 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9220 ExprResult RefRes = DefaultLvalueConversion(Ref);
9221 if (!RefRes.isUsable())
9223 ExprResult PostUpdateRes =
9224 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9225 SimpleRefExpr, RefRes.get());
9226 if (!PostUpdateRes.isUsable())
9228 ExprPostUpdates.push_back(
9229 IgnoredValueConversions(PostUpdateRes.get()).get());
9233 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
9234 Vars.push_back(VarsExpr);
9235 Privates.push_back(PrivateDRE);
9236 LHSs.push_back(LHSDRE);
9237 RHSs.push_back(RHSDRE);
9238 ReductionOps.push_back(ReductionOp.get());
9244 return OMPReductionClause::Create(
9245 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
9246 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
9247 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
9248 buildPostUpdate(*this, ExprPostUpdates));
9251 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9252 SourceLocation LinLoc) {
9253 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9254 LinKind == OMPC_LINEAR_unknown) {
9255 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9261 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9262 OpenMPLinearClauseKind LinKind,
9264 auto *VD = dyn_cast_or_null<VarDecl>(D);
9265 // A variable must not have an incomplete type or a reference type.
9266 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9268 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9269 !Type->isReferenceType()) {
9270 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9271 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9274 Type = Type.getNonReferenceType();
9276 // A list item must not be const-qualified.
9277 if (Type.isConstant(Context)) {
9278 Diag(ELoc, diag::err_omp_const_variable)
9279 << getOpenMPClauseName(OMPC_linear);
9283 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9284 Diag(D->getLocation(),
9285 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9291 // A list item must be of integral or pointer type.
9292 Type = Type.getUnqualifiedType().getCanonicalType();
9293 const auto *Ty = Type.getTypePtrOrNull();
9294 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9295 !Ty->isPointerType())) {
9296 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9300 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9301 Diag(D->getLocation(),
9302 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9310 OMPClause *Sema::ActOnOpenMPLinearClause(
9311 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9312 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9313 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9314 SmallVector<Expr *, 8> Vars;
9315 SmallVector<Expr *, 8> Privates;
9316 SmallVector<Expr *, 8> Inits;
9317 SmallVector<Decl *, 4> ExprCaptures;
9318 SmallVector<Expr *, 4> ExprPostUpdates;
9319 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
9320 LinKind = OMPC_LINEAR_val;
9321 for (auto &RefExpr : VarList) {
9322 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9323 SourceLocation ELoc;
9325 Expr *SimpleRefExpr = RefExpr;
9326 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9327 /*AllowArraySection=*/false);
9329 // It will be analyzed later.
9330 Vars.push_back(RefExpr);
9331 Privates.push_back(nullptr);
9332 Inits.push_back(nullptr);
9334 ValueDecl *D = Res.first;
9338 QualType Type = D->getType();
9339 auto *VD = dyn_cast<VarDecl>(D);
9341 // OpenMP [2.14.3.7, linear clause]
9342 // A list-item cannot appear in more than one linear clause.
9343 // A list-item that appears in a linear clause cannot appear in any
9344 // other data-sharing attribute clause.
9345 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
9347 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9348 << getOpenMPClauseName(OMPC_linear);
9349 ReportOriginalDSA(*this, DSAStack, D, DVar);
9353 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
9355 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
9357 // Build private copy of original var.
9358 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9359 D->hasAttrs() ? &D->getAttrs() : nullptr);
9360 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
9361 // Build var to save initial value.
9362 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
9364 DeclRefExpr *Ref = nullptr;
9365 if (!VD && !CurContext->isDependentContext()) {
9366 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9367 if (!IsOpenMPCapturedDecl(D)) {
9368 ExprCaptures.push_back(Ref->getDecl());
9369 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9370 ExprResult RefRes = DefaultLvalueConversion(Ref);
9371 if (!RefRes.isUsable())
9373 ExprResult PostUpdateRes =
9374 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9375 SimpleRefExpr, RefRes.get());
9376 if (!PostUpdateRes.isUsable())
9378 ExprPostUpdates.push_back(
9379 IgnoredValueConversions(PostUpdateRes.get()).get());
9383 if (LinKind == OMPC_LINEAR_uval)
9384 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
9386 InitExpr = VD ? SimpleRefExpr : Ref;
9387 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
9388 /*DirectInit=*/false);
9389 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9391 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
9392 Vars.push_back((VD || CurContext->isDependentContext())
9393 ? RefExpr->IgnoreParens()
9395 Privates.push_back(PrivateRef);
9396 Inits.push_back(InitRef);
9402 Expr *StepExpr = Step;
9403 Expr *CalcStepExpr = nullptr;
9404 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9405 !Step->isInstantiationDependent() &&
9406 !Step->containsUnexpandedParameterPack()) {
9407 SourceLocation StepLoc = Step->getLocStart();
9408 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
9409 if (Val.isInvalid())
9411 StepExpr = Val.get();
9413 // Build var to save the step value.
9415 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
9416 ExprResult SaveRef =
9417 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
9418 ExprResult CalcStep =
9419 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
9420 CalcStep = ActOnFinishFullExpr(CalcStep.get());
9422 // Warn about zero linear step (it would be probably better specified as
9423 // making corresponding variables 'const').
9424 llvm::APSInt Result;
9425 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9426 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
9427 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9428 << (Vars.size() > 1);
9429 if (!IsConstant && CalcStep.isUsable()) {
9430 // Calculate the step beforehand instead of doing this on each iteration.
9431 // (This is not used if the number of iterations may be kfold-ed).
9432 CalcStepExpr = CalcStep.get();
9436 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9437 ColonLoc, EndLoc, Vars, Privates, Inits,
9438 StepExpr, CalcStepExpr,
9439 buildPreInits(Context, ExprCaptures),
9440 buildPostUpdate(*this, ExprPostUpdates));
9443 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9444 Expr *NumIterations, Sema &SemaRef,
9445 Scope *S, DSAStackTy *Stack) {
9446 // Walk the vars and build update/final expressions for the CodeGen.
9447 SmallVector<Expr *, 8> Updates;
9448 SmallVector<Expr *, 8> Finals;
9449 Expr *Step = Clause.getStep();
9450 Expr *CalcStep = Clause.getCalcStep();
9451 // OpenMP [2.14.3.7, linear clause]
9452 // If linear-step is not specified it is assumed to be 1.
9453 if (Step == nullptr)
9454 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
9455 else if (CalcStep) {
9456 Step = cast<BinaryOperator>(CalcStep)->getLHS();
9458 bool HasErrors = false;
9459 auto CurInit = Clause.inits().begin();
9460 auto CurPrivate = Clause.privates().begin();
9461 auto LinKind = Clause.getModifier();
9462 for (auto &RefExpr : Clause.varlists()) {
9463 SourceLocation ELoc;
9465 Expr *SimpleRefExpr = RefExpr;
9466 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9467 /*AllowArraySection=*/false);
9468 ValueDecl *D = Res.first;
9469 if (Res.second || !D) {
9470 Updates.push_back(nullptr);
9471 Finals.push_back(nullptr);
9475 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9476 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9479 auto &&Info = Stack->isLoopControlVariable(D);
9480 Expr *InitExpr = *CurInit;
9482 // Build privatized reference to the current linear var.
9483 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
9485 if (LinKind == OMPC_LINEAR_uval)
9486 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9489 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9490 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9491 /*RefersToCapture=*/true);
9493 // Build update: Var = InitExpr + IV * Step
9497 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9498 InitExpr, IV, Step, /* Subtract */ false);
9500 Update = *CurPrivate;
9501 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9502 /*DiscardedValue=*/true);
9504 // Build final: Var = InitExpr + NumIterations * Step
9507 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9508 InitExpr, NumIterations, Step,
9509 /* Subtract */ false);
9511 Final = *CurPrivate;
9512 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9513 /*DiscardedValue=*/true);
9515 if (!Update.isUsable() || !Final.isUsable()) {
9516 Updates.push_back(nullptr);
9517 Finals.push_back(nullptr);
9520 Updates.push_back(Update.get());
9521 Finals.push_back(Final.get());
9526 Clause.setUpdates(Updates);
9527 Clause.setFinals(Finals);
9531 OMPClause *Sema::ActOnOpenMPAlignedClause(
9532 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9533 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9535 SmallVector<Expr *, 8> Vars;
9536 for (auto &RefExpr : VarList) {
9537 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9538 SourceLocation ELoc;
9540 Expr *SimpleRefExpr = RefExpr;
9541 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9542 /*AllowArraySection=*/false);
9544 // It will be analyzed later.
9545 Vars.push_back(RefExpr);
9547 ValueDecl *D = Res.first;
9551 QualType QType = D->getType();
9552 auto *VD = dyn_cast<VarDecl>(D);
9554 // OpenMP [2.8.1, simd construct, Restrictions]
9555 // The type of list items appearing in the aligned clause must be
9556 // array, pointer, reference to array, or reference to pointer.
9557 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
9558 const Type *Ty = QType.getTypePtrOrNull();
9559 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
9560 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
9561 << QType << getLangOpts().CPlusPlus << ERange;
9564 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9565 Diag(D->getLocation(),
9566 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9571 // OpenMP [2.8.1, simd construct, Restrictions]
9572 // A list-item cannot appear in more than one aligned clause.
9573 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
9574 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
9575 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9576 << getOpenMPClauseName(OMPC_aligned);
9580 DeclRefExpr *Ref = nullptr;
9581 if (!VD && IsOpenMPCapturedDecl(D))
9582 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9583 Vars.push_back(DefaultFunctionArrayConversion(
9584 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9588 // OpenMP [2.8.1, simd construct, Description]
9589 // The parameter of the aligned clause, alignment, must be a constant
9590 // positive integer expression.
9591 // If no optional parameter is specified, implementation-defined default
9592 // alignments for SIMD instructions on the target platforms are assumed.
9593 if (Alignment != nullptr) {
9594 ExprResult AlignResult =
9595 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9596 if (AlignResult.isInvalid())
9598 Alignment = AlignResult.get();
9603 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9604 EndLoc, Vars, Alignment);
9607 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9608 SourceLocation StartLoc,
9609 SourceLocation LParenLoc,
9610 SourceLocation EndLoc) {
9611 SmallVector<Expr *, 8> Vars;
9612 SmallVector<Expr *, 8> SrcExprs;
9613 SmallVector<Expr *, 8> DstExprs;
9614 SmallVector<Expr *, 8> AssignmentOps;
9615 for (auto &RefExpr : VarList) {
9616 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9617 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
9618 // It will be analyzed later.
9619 Vars.push_back(RefExpr);
9620 SrcExprs.push_back(nullptr);
9621 DstExprs.push_back(nullptr);
9622 AssignmentOps.push_back(nullptr);
9626 SourceLocation ELoc = RefExpr->getExprLoc();
9627 // OpenMP [2.1, C/C++]
9628 // A list item is a variable name.
9629 // OpenMP [2.14.4.1, Restrictions, p.1]
9630 // A list item that appears in a copyin clause must be threadprivate.
9631 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
9632 if (!DE || !isa<VarDecl>(DE->getDecl())) {
9633 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9634 << 0 << RefExpr->getSourceRange();
9638 Decl *D = DE->getDecl();
9639 VarDecl *VD = cast<VarDecl>(D);
9641 QualType Type = VD->getType();
9642 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9643 // It will be analyzed later.
9645 SrcExprs.push_back(nullptr);
9646 DstExprs.push_back(nullptr);
9647 AssignmentOps.push_back(nullptr);
9651 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9652 // A list item that appears in a copyin clause must be threadprivate.
9653 if (!DSAStack->isThreadPrivate(VD)) {
9654 Diag(ELoc, diag::err_omp_required_access)
9655 << getOpenMPClauseName(OMPC_copyin)
9656 << getOpenMPDirectiveName(OMPD_threadprivate);
9660 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9661 // A variable of class type (or array thereof) that appears in a
9662 // copyin clause requires an accessible, unambiguous copy assignment
9663 // operator for the class type.
9664 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
9666 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9667 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
9668 auto *PseudoSrcExpr = buildDeclRefExpr(
9669 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9671 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9672 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
9673 auto *PseudoDstExpr =
9674 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
9675 // For arrays generate assignment operation for single element and replace
9676 // it by the original array element in CodeGen.
9677 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9678 PseudoDstExpr, PseudoSrcExpr);
9679 if (AssignmentOp.isInvalid())
9681 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9682 /*DiscardedValue=*/true);
9683 if (AssignmentOp.isInvalid())
9686 DSAStack->addDSA(VD, DE, OMPC_copyin);
9688 SrcExprs.push_back(PseudoSrcExpr);
9689 DstExprs.push_back(PseudoDstExpr);
9690 AssignmentOps.push_back(AssignmentOp.get());
9696 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9697 SrcExprs, DstExprs, AssignmentOps);
9700 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9701 SourceLocation StartLoc,
9702 SourceLocation LParenLoc,
9703 SourceLocation EndLoc) {
9704 SmallVector<Expr *, 8> Vars;
9705 SmallVector<Expr *, 8> SrcExprs;
9706 SmallVector<Expr *, 8> DstExprs;
9707 SmallVector<Expr *, 8> AssignmentOps;
9708 for (auto &RefExpr : VarList) {
9709 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9710 SourceLocation ELoc;
9712 Expr *SimpleRefExpr = RefExpr;
9713 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9714 /*AllowArraySection=*/false);
9716 // It will be analyzed later.
9717 Vars.push_back(RefExpr);
9718 SrcExprs.push_back(nullptr);
9719 DstExprs.push_back(nullptr);
9720 AssignmentOps.push_back(nullptr);
9722 ValueDecl *D = Res.first;
9726 QualType Type = D->getType();
9727 auto *VD = dyn_cast<VarDecl>(D);
9729 // OpenMP [2.14.4.2, Restrictions, p.2]
9730 // A list item that appears in a copyprivate clause may not appear in a
9731 // private or firstprivate clause on the single construct.
9732 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9733 auto DVar = DSAStack->getTopDSA(D, false);
9734 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9736 Diag(ELoc, diag::err_omp_wrong_dsa)
9737 << getOpenMPClauseName(DVar.CKind)
9738 << getOpenMPClauseName(OMPC_copyprivate);
9739 ReportOriginalDSA(*this, DSAStack, D, DVar);
9743 // OpenMP [2.11.4.2, Restrictions, p.1]
9744 // All list items that appear in a copyprivate clause must be either
9745 // threadprivate or private in the enclosing context.
9746 if (DVar.CKind == OMPC_unknown) {
9747 DVar = DSAStack->getImplicitDSA(D, false);
9748 if (DVar.CKind == OMPC_shared) {
9749 Diag(ELoc, diag::err_omp_required_access)
9750 << getOpenMPClauseName(OMPC_copyprivate)
9751 << "threadprivate or private in the enclosing context";
9752 ReportOriginalDSA(*this, DSAStack, D, DVar);
9758 // Variably modified types are not supported.
9759 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
9760 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9761 << getOpenMPClauseName(OMPC_copyprivate) << Type
9762 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9765 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9766 Diag(D->getLocation(),
9767 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9772 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9773 // A variable of class type (or array thereof) that appears in a
9774 // copyin clause requires an accessible, unambiguous copy assignment
9775 // operator for the class type.
9776 Type = Context.getBaseElementType(Type.getNonReferenceType())
9777 .getUnqualifiedType();
9779 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9780 D->hasAttrs() ? &D->getAttrs() : nullptr);
9781 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
9783 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9784 D->hasAttrs() ? &D->getAttrs() : nullptr);
9785 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
9786 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9787 PseudoDstExpr, PseudoSrcExpr);
9788 if (AssignmentOp.isInvalid())
9790 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
9791 /*DiscardedValue=*/true);
9792 if (AssignmentOp.isInvalid())
9795 // No need to mark vars as copyprivate, they are already threadprivate or
9796 // implicitly private.
9797 assert(VD || IsOpenMPCapturedDecl(D));
9799 VD ? RefExpr->IgnoreParens()
9800 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
9801 SrcExprs.push_back(PseudoSrcExpr);
9802 DstExprs.push_back(PseudoDstExpr);
9803 AssignmentOps.push_back(AssignmentOp.get());
9809 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9810 Vars, SrcExprs, DstExprs, AssignmentOps);
9813 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9814 SourceLocation StartLoc,
9815 SourceLocation LParenLoc,
9816 SourceLocation EndLoc) {
9817 if (VarList.empty())
9820 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9824 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9825 SourceLocation DepLoc, SourceLocation ColonLoc,
9826 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9827 SourceLocation LParenLoc, SourceLocation EndLoc) {
9828 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
9829 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
9830 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
9831 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
9834 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
9835 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9836 DepKind == OMPC_DEPEND_sink)) {
9837 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
9838 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
9839 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9840 /*Last=*/OMPC_DEPEND_unknown, Except)
9841 << getOpenMPClauseName(OMPC_depend);
9844 SmallVector<Expr *, 8> Vars;
9845 DSAStackTy::OperatorOffsetTy OpsOffs;
9846 llvm::APSInt DepCounter(/*BitWidth=*/32);
9847 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9848 if (DepKind == OMPC_DEPEND_sink) {
9849 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9850 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9851 TotalDepCount.setIsUnsigned(/*Val=*/true);
9854 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9855 DSAStack->getParentOrderedRegionParam()) {
9856 for (auto &RefExpr : VarList) {
9857 assert(RefExpr && "NULL expr in OpenMP shared clause.");
9858 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
9859 // It will be analyzed later.
9860 Vars.push_back(RefExpr);
9864 SourceLocation ELoc = RefExpr->getExprLoc();
9865 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9866 if (DepKind == OMPC_DEPEND_sink) {
9867 if (DepCounter >= TotalDepCount) {
9868 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9872 // OpenMP [2.13.9, Summary]
9873 // depend(dependence-type : vec), where dependence-type is:
9874 // 'sink' and where vec is the iteration vector, which has the form:
9875 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9876 // where n is the value specified by the ordered clause in the loop
9877 // directive, xi denotes the loop iteration variable of the i-th nested
9878 // loop associated with the loop directive, and di is a constant
9879 // non-negative integer.
9880 if (CurContext->isDependentContext()) {
9881 // It will be analyzed later.
9882 Vars.push_back(RefExpr);
9885 SimpleExpr = SimpleExpr->IgnoreImplicit();
9886 OverloadedOperatorKind OOK = OO_None;
9887 SourceLocation OOLoc;
9888 Expr *LHS = SimpleExpr;
9889 Expr *RHS = nullptr;
9890 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9891 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9892 OOLoc = BO->getOperatorLoc();
9893 LHS = BO->getLHS()->IgnoreParenImpCasts();
9894 RHS = BO->getRHS()->IgnoreParenImpCasts();
9895 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9896 OOK = OCE->getOperator();
9897 OOLoc = OCE->getOperatorLoc();
9898 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9899 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9900 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9901 OOK = MCE->getMethodDecl()
9904 .getCXXOverloadedOperator();
9905 OOLoc = MCE->getCallee()->getExprLoc();
9906 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9907 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9909 SourceLocation ELoc;
9911 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9912 /*AllowArraySection=*/false);
9914 // It will be analyzed later.
9915 Vars.push_back(RefExpr);
9917 ValueDecl *D = Res.first;
9921 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9922 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9926 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9927 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9928 if (RHSRes.isInvalid())
9931 if (!CurContext->isDependentContext() &&
9932 DSAStack->getParentOrderedRegionParam() &&
9933 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9934 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9935 << DSAStack->getParentLoopControlVariable(
9936 DepCounter.getZExtValue());
9939 OpsOffs.push_back({RHS, OOK});
9941 // OpenMP [2.11.1.1, Restrictions, p.3]
9942 // A variable that is part of another variable (such as a field of a
9943 // structure) but is not an array element or an array section cannot
9944 // appear in a depend clause.
9945 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9946 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9947 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9948 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9949 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
9953 .getNonReferenceType()
9954 ->isPointerType() &&
9955 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
9956 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9957 << 0 << RefExpr->getSourceRange();
9961 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9964 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9965 TotalDepCount > VarList.size() &&
9966 DSAStack->getParentOrderedRegionParam()) {
9967 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9968 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9970 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9974 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9975 DepKind, DepLoc, ColonLoc, Vars);
9976 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9977 DSAStack->addDoacrossDependClause(C, OpsOffs);
9981 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9982 SourceLocation LParenLoc,
9983 SourceLocation EndLoc) {
9984 Expr *ValExpr = Device;
9986 // OpenMP [2.9.1, Restrictions]
9987 // The device expression must evaluate to a non-negative integer value.
9988 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9989 /*StrictlyPositive=*/false))
9992 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9995 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9996 DSAStackTy *Stack, CXXRecordDecl *RD) {
9997 if (!RD || RD->isInvalidDecl())
10000 auto QTy = SemaRef.Context.getRecordType(RD);
10001 if (RD->isDynamicClass()) {
10002 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10003 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
10007 bool IsCorrect = true;
10008 for (auto *I : DC->decls()) {
10010 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
10011 if (MD->isStatic()) {
10012 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10013 SemaRef.Diag(MD->getLocation(),
10014 diag::note_omp_static_member_in_target);
10017 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
10018 if (VD->isStaticDataMember()) {
10019 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10020 SemaRef.Diag(VD->getLocation(),
10021 diag::note_omp_static_member_in_target);
10028 for (auto &I : RD->bases()) {
10029 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
10030 I.getType()->getAsCXXRecordDecl()))
10036 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
10037 DSAStackTy *Stack, QualType QTy) {
10039 if (QTy->isIncompleteType(&ND)) {
10040 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
10042 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
10043 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
10049 /// \brief Return true if it can be proven that the provided array expression
10050 /// (array section or array subscript) does NOT specify the whole size of the
10051 /// array whose base type is \a BaseQTy.
10052 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10054 QualType BaseQTy) {
10055 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10057 // If this is an array subscript, it refers to the whole size if the size of
10058 // the dimension is constant and equals 1. Also, an array section assumes the
10059 // format of an array subscript if no colon is used.
10060 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10061 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10062 return ATy->getSize().getSExtValue() != 1;
10063 // Size can't be evaluated statically.
10067 assert(OASE && "Expecting array section if not an array subscript.");
10068 auto *LowerBound = OASE->getLowerBound();
10069 auto *Length = OASE->getLength();
10071 // If there is a lower bound that does not evaluates to zero, we are not
10072 // covering the whole dimension.
10074 llvm::APSInt ConstLowerBound;
10075 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10076 return false; // Can't get the integer value as a constant.
10077 if (ConstLowerBound.getSExtValue())
10081 // If we don't have a length we covering the whole dimension.
10085 // If the base is a pointer, we don't have a way to get the size of the
10087 if (BaseQTy->isPointerType())
10090 // We can only check if the length is the same as the size of the dimension
10091 // if we have a constant array.
10092 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10096 llvm::APSInt ConstLength;
10097 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10098 return false; // Can't get the integer value as a constant.
10100 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10103 // Return true if it can be proven that the provided array expression (array
10104 // section or array subscript) does NOT specify a single element of the array
10105 // whose base type is \a BaseQTy.
10106 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
10108 QualType BaseQTy) {
10109 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10111 // An array subscript always refer to a single element. Also, an array section
10112 // assumes the format of an array subscript if no colon is used.
10113 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10116 assert(OASE && "Expecting array section if not an array subscript.");
10117 auto *Length = OASE->getLength();
10119 // If we don't have a length we have to check if the array has unitary size
10120 // for this dimension. Also, we should always expect a length if the base type
10123 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10124 return ATy->getSize().getSExtValue() != 1;
10125 // We cannot assume anything.
10129 // Check if the length evaluates to 1.
10130 llvm::APSInt ConstLength;
10131 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10132 return false; // Can't get the integer value as a constant.
10134 return ConstLength.getSExtValue() != 1;
10137 // Return the expression of the base of the mappable expression or null if it
10138 // cannot be determined and do all the necessary checks to see if the expression
10139 // is valid as a standalone mappable expression. In the process, record all the
10140 // components of the expression.
10141 static Expr *CheckMapClauseExpressionBase(
10142 Sema &SemaRef, Expr *E,
10143 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10144 OpenMPClauseKind CKind) {
10145 SourceLocation ELoc = E->getExprLoc();
10146 SourceRange ERange = E->getSourceRange();
10148 // The base of elements of list in a map clause have to be either:
10149 // - a reference to variable or field.
10150 // - a member expression.
10151 // - an array expression.
10153 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10154 // reference to 'r'.
10161 // #pragma omp target map (S.Arr[:12]);
10165 // We want to retrieve the member expression 'this->S';
10167 Expr *RelevantExpr = nullptr;
10169 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10170 // If a list item is an array section, it must specify contiguous storage.
10172 // For this restriction it is sufficient that we make sure only references
10173 // to variables or fields and array expressions, and that no array sections
10174 // exist except in the rightmost expression (unless they cover the whole
10175 // dimension of the array). E.g. these would be invalid:
10177 // r.ArrS[3:5].Arr[6:7]
10181 // but these would be valid:
10182 // r.ArrS[3].Arr[6:7]
10186 bool AllowUnitySizeArraySection = true;
10187 bool AllowWholeSizeArraySection = true;
10189 while (!RelevantExpr) {
10190 E = E->IgnoreParenImpCasts();
10192 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10193 if (!isa<VarDecl>(CurE->getDecl()))
10196 RelevantExpr = CurE;
10198 // If we got a reference to a declaration, we should not expect any array
10199 // section before that.
10200 AllowUnitySizeArraySection = false;
10201 AllowWholeSizeArraySection = false;
10203 // Record the component.
10204 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10205 CurE, CurE->getDecl()));
10209 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10210 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10212 if (isa<CXXThisExpr>(BaseE))
10213 // We found a base expression: this->Val.
10214 RelevantExpr = CurE;
10218 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10219 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10220 << CurE->getSourceRange();
10224 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10226 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10227 // A bit-field cannot appear in a map clause.
10229 if (FD->isBitField()) {
10230 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10231 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
10235 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10236 // If the type of a list item is a reference to a type T then the type
10237 // will be considered to be T for all purposes of this clause.
10238 QualType CurType = BaseE->getType().getNonReferenceType();
10240 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10241 // A list item cannot be a variable that is a member of a structure with
10244 if (auto *RT = CurType->getAs<RecordType>())
10245 if (RT->isUnionType()) {
10246 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10247 << CurE->getSourceRange();
10251 // If we got a member expression, we should not expect any array section
10254 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10255 // If a list item is an element of a structure, only the rightmost symbol
10256 // of the variable reference can be an array section.
10258 AllowUnitySizeArraySection = false;
10259 AllowWholeSizeArraySection = false;
10261 // Record the component.
10262 CurComponents.push_back(
10263 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
10267 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10268 E = CurE->getBase()->IgnoreParenImpCasts();
10270 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10271 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10272 << 0 << CurE->getSourceRange();
10276 // If we got an array subscript that express the whole dimension we
10277 // can have any array expressions before. If it only expressing part of
10278 // the dimension, we can only have unitary-size array expressions.
10279 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10281 AllowWholeSizeArraySection = false;
10283 // Record the component - we don't have any declaration associated.
10284 CurComponents.push_back(
10285 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
10289 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
10290 E = CurE->getBase()->IgnoreParenImpCasts();
10293 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10295 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10296 // If the type of a list item is a reference to a type T then the type
10297 // will be considered to be T for all purposes of this clause.
10298 if (CurType->isReferenceType())
10299 CurType = CurType->getPointeeType();
10301 bool IsPointer = CurType->isAnyPointerType();
10303 if (!IsPointer && !CurType->isArrayType()) {
10304 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10305 << 0 << CurE->getSourceRange();
10310 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10312 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10314 if (AllowWholeSizeArraySection) {
10315 // Any array section is currently allowed. Allowing a whole size array
10316 // section implies allowing a unity array section as well.
10318 // If this array section refers to the whole dimension we can still
10319 // accept other array sections before this one, except if the base is a
10320 // pointer. Otherwise, only unitary sections are accepted.
10321 if (NotWhole || IsPointer)
10322 AllowWholeSizeArraySection = false;
10323 } else if (AllowUnitySizeArraySection && NotUnity) {
10324 // A unity or whole array section is not allowed and that is not
10325 // compatible with the properties of the current array section.
10327 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10328 << CurE->getSourceRange();
10332 // Record the component - we don't have any declaration associated.
10333 CurComponents.push_back(
10334 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
10338 // If nothing else worked, this is not a valid map clause expression.
10340 diag::err_omp_expected_named_var_member_or_array_expression)
10345 return RelevantExpr;
10348 // Return true if expression E associated with value VD has conflicts with other
10349 // map information.
10350 static bool CheckMapConflicts(
10351 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10352 bool CurrentRegionOnly,
10353 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10354 OpenMPClauseKind CKind) {
10356 SourceLocation ELoc = E->getExprLoc();
10357 SourceRange ERange = E->getSourceRange();
10359 // In order to easily check the conflicts we need to match each component of
10360 // the expression under test with the components of the expressions that are
10361 // already in the stack.
10363 assert(!CurComponents.empty() && "Map clause expression with no components!");
10364 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
10365 "Map clause expression with unexpected base!");
10367 // Variables to help detecting enclosing problems in data environment nests.
10368 bool IsEnclosedByDataEnvironmentExpr = false;
10369 const Expr *EnclosingExpr = nullptr;
10371 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10372 VD, CurrentRegionOnly,
10373 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
10375 OpenMPClauseKind) -> bool {
10377 assert(!StackComponents.empty() &&
10378 "Map clause expression with no components!");
10379 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
10380 "Map clause expression with unexpected base!");
10382 // The whole expression in the stack.
10383 auto *RE = StackComponents.front().getAssociatedExpression();
10385 // Expressions must start from the same base. Here we detect at which
10386 // point both expressions diverge from each other and see if we can
10387 // detect if the memory referred to both expressions is contiguous and
10389 auto CI = CurComponents.rbegin();
10390 auto CE = CurComponents.rend();
10391 auto SI = StackComponents.rbegin();
10392 auto SE = StackComponents.rend();
10393 for (; CI != CE && SI != SE; ++CI, ++SI) {
10395 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10396 // At most one list item can be an array item derived from a given
10397 // variable in map clauses of the same construct.
10398 if (CurrentRegionOnly &&
10399 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10400 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10401 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10402 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10403 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
10404 diag::err_omp_multiple_array_items_in_map_clause)
10405 << CI->getAssociatedExpression()->getSourceRange();
10406 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10407 diag::note_used_here)
10408 << SI->getAssociatedExpression()->getSourceRange();
10412 // Do both expressions have the same kind?
10413 if (CI->getAssociatedExpression()->getStmtClass() !=
10414 SI->getAssociatedExpression()->getStmtClass())
10417 // Are we dealing with different variables/fields?
10418 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
10421 // Check if the extra components of the expressions in the enclosing
10422 // data environment are redundant for the current base declaration.
10423 // If they are, the maps completely overlap, which is legal.
10424 for (; SI != SE; ++SI) {
10427 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
10428 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
10429 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10430 SI->getAssociatedExpression())) {
10431 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10433 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10435 if (Type.isNull() || Type->isAnyPointerType() ||
10436 CheckArrayExpressionDoesNotReferToWholeSize(
10437 SemaRef, SI->getAssociatedExpression(), Type))
10441 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10442 // List items of map clauses in the same construct must not share
10443 // original storage.
10445 // If the expressions are exactly the same or one is a subset of the
10446 // other, it means they are sharing storage.
10447 if (CI == CE && SI == SE) {
10448 if (CurrentRegionOnly) {
10449 if (CKind == OMPC_map)
10450 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10452 assert(CKind == OMPC_to || CKind == OMPC_from);
10453 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10456 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10457 << RE->getSourceRange();
10460 // If we find the same expression in the enclosing data environment,
10462 IsEnclosedByDataEnvironmentExpr = true;
10467 QualType DerivedType =
10468 std::prev(CI)->getAssociatedDeclaration()->getType();
10469 SourceLocation DerivedLoc =
10470 std::prev(CI)->getAssociatedExpression()->getExprLoc();
10472 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10473 // If the type of a list item is a reference to a type T then the type
10474 // will be considered to be T for all purposes of this clause.
10475 DerivedType = DerivedType.getNonReferenceType();
10477 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10478 // A variable for which the type is pointer and an array section
10479 // derived from that variable must not appear as list items of map
10480 // clauses of the same construct.
10482 // Also, cover one of the cases in:
10483 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10484 // If any part of the original storage of a list item has corresponding
10485 // storage in the device data environment, all of the original storage
10486 // must have corresponding storage in the device data environment.
10488 if (DerivedType->isAnyPointerType()) {
10489 if (CI == CE || SI == SE) {
10492 diag::err_omp_pointer_mapped_along_with_derived_section)
10495 assert(CI != CE && SI != SE);
10496 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10499 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10500 << RE->getSourceRange();
10504 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10505 // List items of map clauses in the same construct must not share
10506 // original storage.
10508 // An expression is a subset of the other.
10509 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
10510 if (CKind == OMPC_map)
10511 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10513 assert(CKind == OMPC_to || CKind == OMPC_from);
10514 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10517 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10518 << RE->getSourceRange();
10522 // The current expression uses the same base as other expression in the
10523 // data environment but does not contain it completely.
10524 if (!CurrentRegionOnly && SI != SE)
10525 EnclosingExpr = RE;
10527 // The current expression is a subset of the expression in the data
10529 IsEnclosedByDataEnvironmentExpr |=
10530 (!CurrentRegionOnly && CI != CE && SI == SE);
10535 if (CurrentRegionOnly)
10538 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10539 // If any part of the original storage of a list item has corresponding
10540 // storage in the device data environment, all of the original storage must
10541 // have corresponding storage in the device data environment.
10542 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10543 // If a list item is an element of a structure, and a different element of
10544 // the structure has a corresponding list item in the device data environment
10545 // prior to a task encountering the construct associated with the map clause,
10546 // then the list item must also have a corresponding list item in the device
10547 // data environment prior to the task encountering the construct.
10549 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10551 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10553 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10554 << EnclosingExpr->getSourceRange();
10562 // Utility struct that gathers all the related lists associated with a mappable
10564 struct MappableVarListInfo final {
10565 // The list of expressions.
10566 ArrayRef<Expr *> VarList;
10567 // The list of processed expressions.
10568 SmallVector<Expr *, 16> ProcessedVarList;
10569 // The mappble components for each expression.
10570 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10571 // The base declaration of the variable.
10572 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10574 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10575 // We have a list of components and base declarations for each entry in the
10577 VarComponents.reserve(VarList.size());
10578 VarBaseDeclarations.reserve(VarList.size());
10583 // Check the validity of the provided variable list for the provided clause kind
10584 // \a CKind. In the check process the valid expressions, and mappable expression
10585 // components and variables are extracted and used to fill \a Vars,
10586 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10587 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10589 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10590 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10591 SourceLocation StartLoc,
10592 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10593 bool IsMapTypeImplicit = false) {
10594 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10595 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
10596 "Unexpected clause kind with mappable expressions!");
10598 // Keep track of the mappable components and base declarations in this clause.
10599 // Each entry in the list is going to have a list of components associated. We
10600 // record each set of the components so that we can build the clause later on.
10601 // In the end we should have the same amount of declarations and component
10604 for (auto &RE : MVLI.VarList) {
10605 assert(RE && "Null expr in omp to/from/map clause");
10606 SourceLocation ELoc = RE->getExprLoc();
10608 auto *VE = RE->IgnoreParenLValueCasts();
10610 if (VE->isValueDependent() || VE->isTypeDependent() ||
10611 VE->isInstantiationDependent() ||
10612 VE->containsUnexpandedParameterPack()) {
10613 // We can only analyze this information once the missing information is
10615 MVLI.ProcessedVarList.push_back(RE);
10619 auto *SimpleExpr = RE->IgnoreParenCasts();
10621 if (!RE->IgnoreParenImpCasts()->isLValue()) {
10623 diag::err_omp_expected_named_var_member_or_array_expression)
10624 << RE->getSourceRange();
10628 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10629 ValueDecl *CurDeclaration = nullptr;
10631 // Obtain the array or member expression bases if required. Also, fill the
10632 // components array with all the components identified in the process.
10634 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
10638 assert(!CurComponents.empty() &&
10639 "Invalid mappable expression information.");
10641 // For the following checks, we rely on the base declaration which is
10642 // expected to be associated with the last component. The declaration is
10643 // expected to be a variable or a field (if 'this' is being mapped).
10644 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10645 assert(CurDeclaration && "Null decl on map clause.");
10647 CurDeclaration->isCanonicalDecl() &&
10648 "Expecting components to have associated only canonical declarations.");
10650 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10651 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
10653 assert((VD || FD) && "Only variables or fields are expected here!");
10656 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
10657 // threadprivate variables cannot appear in a map clause.
10658 // OpenMP 4.5 [2.10.5, target update Construct]
10659 // threadprivate variables cannot appear in a from clause.
10660 if (VD && DSAS->isThreadPrivate(VD)) {
10661 auto DVar = DSAS->getTopDSA(VD, false);
10662 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10663 << getOpenMPClauseName(CKind);
10664 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
10668 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10669 // A list item cannot appear in both a map clause and a data-sharing
10670 // attribute clause on the same construct.
10672 // Check conflicts with other map clause expressions. We check the conflicts
10673 // with the current construct separately from the enclosing data
10674 // environment, because the restrictions are different. We only have to
10675 // check conflicts across regions for the map clauses.
10676 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10677 /*CurrentRegionOnly=*/true, CurComponents, CKind))
10679 if (CKind == OMPC_map &&
10680 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10681 /*CurrentRegionOnly=*/false, CurComponents, CKind))
10684 // OpenMP 4.5 [2.10.5, target update Construct]
10685 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10686 // If the type of a list item is a reference to a type T then the type will
10687 // be considered to be T for all purposes of this clause.
10688 QualType Type = CurDeclaration->getType().getNonReferenceType();
10690 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10691 // A list item in a to or from clause must have a mappable type.
10692 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10693 // A list item must have a mappable type.
10694 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10698 if (CKind == OMPC_map) {
10699 // target enter data
10700 // OpenMP [2.10.2, Restrictions, p. 99]
10701 // A map-type must be specified in all map clauses and must be either
10703 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10704 if (DKind == OMPD_target_enter_data &&
10705 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10706 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10707 << (IsMapTypeImplicit ? 1 : 0)
10708 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10709 << getOpenMPDirectiveName(DKind);
10713 // target exit_data
10714 // OpenMP [2.10.3, Restrictions, p. 102]
10715 // A map-type must be specified in all map clauses and must be either
10716 // from, release, or delete.
10717 if (DKind == OMPD_target_exit_data &&
10718 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10719 MapType == OMPC_MAP_delete)) {
10720 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10721 << (IsMapTypeImplicit ? 1 : 0)
10722 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10723 << getOpenMPDirectiveName(DKind);
10727 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10728 // A list item cannot appear in both a map clause and a data-sharing
10729 // attribute clause on the same construct
10730 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
10731 DKind == OMPD_target_teams_distribute ||
10732 DKind == OMPD_target_teams_distribute_parallel_for ||
10733 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
10734 DKind == OMPD_target_teams_distribute_simd) && VD) {
10735 auto DVar = DSAS->getTopDSA(VD, false);
10736 if (isOpenMPPrivate(DVar.CKind)) {
10737 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10738 << getOpenMPClauseName(DVar.CKind)
10739 << getOpenMPClauseName(OMPC_map)
10740 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10741 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10747 // Save the current expression.
10748 MVLI.ProcessedVarList.push_back(RE);
10750 // Store the components in the stack so that they can be used to check
10751 // against other clauses later on.
10752 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10753 /*WhereFoundClauseKind=*/OMPC_map);
10755 // Save the components and declaration to create the clause. For purposes of
10756 // the clause creation, any component list that has has base 'this' uses
10757 // null as base declaration.
10758 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10759 MVLI.VarComponents.back().append(CurComponents.begin(),
10760 CurComponents.end());
10761 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10767 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10768 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10769 SourceLocation MapLoc, SourceLocation ColonLoc,
10770 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10771 SourceLocation LParenLoc, SourceLocation EndLoc) {
10772 MappableVarListInfo MVLI(VarList);
10773 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10774 MapType, IsMapTypeImplicit);
10776 // We need to produce a map clause even if we don't have variables so that
10777 // other diagnostics related with non-existing map clauses are accurate.
10778 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10779 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10780 MVLI.VarComponents, MapTypeModifier, MapType,
10781 IsMapTypeImplicit, MapLoc);
10784 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10785 TypeResult ParsedType) {
10786 assert(ParsedType.isUsable());
10788 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10789 if (ReductionType.isNull())
10792 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10793 // A type name in a declare reduction directive cannot be a function type, an
10794 // array type, a reference type, or a type qualified with const, volatile or
10796 if (ReductionType.hasQualifiers()) {
10797 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10801 if (ReductionType->isFunctionType()) {
10802 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10805 if (ReductionType->isReferenceType()) {
10806 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10809 if (ReductionType->isArrayType()) {
10810 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10813 return ReductionType;
10816 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10817 Scope *S, DeclContext *DC, DeclarationName Name,
10818 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10819 AccessSpecifier AS, Decl *PrevDeclInScope) {
10820 SmallVector<Decl *, 8> Decls;
10821 Decls.reserve(ReductionTypes.size());
10823 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10825 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10826 // A reduction-identifier may not be re-declared in the current scope for the
10827 // same type or for a type that is compatible according to the base language
10829 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10830 OMPDeclareReductionDecl *PrevDRD = nullptr;
10831 bool InCompoundScope = true;
10832 if (S != nullptr) {
10833 // Find previous declaration with the same name not referenced in other
10835 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10837 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10838 LookupName(Lookup, S);
10839 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10840 /*AllowInlineNamespace=*/false);
10841 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10842 auto Filter = Lookup.makeFilter();
10843 while (Filter.hasNext()) {
10844 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10845 if (InCompoundScope) {
10846 auto I = UsedAsPrevious.find(PrevDecl);
10847 if (I == UsedAsPrevious.end())
10848 UsedAsPrevious[PrevDecl] = false;
10849 if (auto *D = PrevDecl->getPrevDeclInScope())
10850 UsedAsPrevious[D] = true;
10852 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10853 PrevDecl->getLocation();
10856 if (InCompoundScope) {
10857 for (auto &PrevData : UsedAsPrevious) {
10858 if (!PrevData.second) {
10859 PrevDRD = PrevData.first;
10864 } else if (PrevDeclInScope != nullptr) {
10865 auto *PrevDRDInScope = PrevDRD =
10866 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10868 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10869 PrevDRDInScope->getLocation();
10870 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10871 } while (PrevDRDInScope != nullptr);
10873 for (auto &TyData : ReductionTypes) {
10874 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10875 bool Invalid = false;
10876 if (I != PreviousRedeclTypes.end()) {
10877 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10879 Diag(I->second, diag::note_previous_definition);
10882 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10883 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10884 Name, TyData.first, PrevDRD);
10886 DRD->setAccess(AS);
10887 Decls.push_back(DRD);
10889 DRD->setInvalidDecl();
10894 return DeclGroupPtrTy::make(
10895 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10898 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10899 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10901 // Enter new function scope.
10902 PushFunctionScope();
10903 getCurFunction()->setHasBranchProtectedScope();
10904 getCurFunction()->setHasOMPDeclareReductionCombiner();
10907 PushDeclContext(S, DRD);
10911 PushExpressionEvaluationContext(
10912 ExpressionEvaluationContext::PotentiallyEvaluated);
10914 QualType ReductionType = DRD->getType();
10915 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10916 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10917 // uses semantics of argument handles by value, but it should be passed by
10918 // reference. C lang does not support references, so pass all parameters as
10920 // Create 'T omp_in;' variable.
10922 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
10923 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10924 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10925 // uses semantics of argument handles by value, but it should be passed by
10926 // reference. C lang does not support references, so pass all parameters as
10928 // Create 'T omp_out;' variable.
10930 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10931 if (S != nullptr) {
10932 PushOnScopeChains(OmpInParm, S);
10933 PushOnScopeChains(OmpOutParm, S);
10935 DRD->addDecl(OmpInParm);
10936 DRD->addDecl(OmpOutParm);
10940 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10941 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10942 DiscardCleanupsInEvaluationContext();
10943 PopExpressionEvaluationContext();
10946 PopFunctionScopeInfo();
10948 if (Combiner != nullptr)
10949 DRD->setCombiner(Combiner);
10951 DRD->setInvalidDecl();
10954 void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10955 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10957 // Enter new function scope.
10958 PushFunctionScope();
10959 getCurFunction()->setHasBranchProtectedScope();
10962 PushDeclContext(S, DRD);
10966 PushExpressionEvaluationContext(
10967 ExpressionEvaluationContext::PotentiallyEvaluated);
10969 QualType ReductionType = DRD->getType();
10970 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10971 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10972 // uses semantics of argument handles by value, but it should be passed by
10973 // reference. C lang does not support references, so pass all parameters as
10975 // Create 'T omp_priv;' variable.
10976 auto *OmpPrivParm =
10977 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
10978 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10979 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10980 // uses semantics of argument handles by value, but it should be passed by
10981 // reference. C lang does not support references, so pass all parameters as
10983 // Create 'T omp_orig;' variable.
10984 auto *OmpOrigParm =
10985 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
10986 if (S != nullptr) {
10987 PushOnScopeChains(OmpPrivParm, S);
10988 PushOnScopeChains(OmpOrigParm, S);
10990 DRD->addDecl(OmpPrivParm);
10991 DRD->addDecl(OmpOrigParm);
10995 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10996 Expr *Initializer) {
10997 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10998 DiscardCleanupsInEvaluationContext();
10999 PopExpressionEvaluationContext();
11002 PopFunctionScopeInfo();
11004 if (Initializer != nullptr)
11005 DRD->setInitializer(Initializer);
11007 DRD->setInvalidDecl();
11010 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
11011 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
11012 for (auto *D : DeclReductions.get()) {
11014 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11016 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
11018 D->setInvalidDecl();
11020 return DeclReductions;
11023 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
11024 SourceLocation StartLoc,
11025 SourceLocation LParenLoc,
11026 SourceLocation EndLoc) {
11027 Expr *ValExpr = NumTeams;
11028 Stmt *HelperValStmt = nullptr;
11029 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
11031 // OpenMP [teams Constrcut, Restrictions]
11032 // The num_teams expression must evaluate to a positive integer value.
11033 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
11034 /*StrictlyPositive=*/true))
11037 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11038 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
11039 if (CaptureRegion != OMPD_unknown) {
11040 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11041 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11042 HelperValStmt = buildPreInits(Context, Captures);
11045 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
11046 StartLoc, LParenLoc, EndLoc);
11049 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11050 SourceLocation StartLoc,
11051 SourceLocation LParenLoc,
11052 SourceLocation EndLoc) {
11053 Expr *ValExpr = ThreadLimit;
11054 Stmt *HelperValStmt = nullptr;
11055 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
11057 // OpenMP [teams Constrcut, Restrictions]
11058 // The thread_limit expression must evaluate to a positive integer value.
11059 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
11060 /*StrictlyPositive=*/true))
11063 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11064 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
11065 if (CaptureRegion != OMPD_unknown) {
11066 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11067 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11068 HelperValStmt = buildPreInits(Context, Captures);
11071 return new (Context) OMPThreadLimitClause(
11072 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
11075 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
11076 SourceLocation StartLoc,
11077 SourceLocation LParenLoc,
11078 SourceLocation EndLoc) {
11079 Expr *ValExpr = Priority;
11081 // OpenMP [2.9.1, task Constrcut]
11082 // The priority-value is a non-negative numerical scalar expression.
11083 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
11084 /*StrictlyPositive=*/false))
11087 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11090 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
11091 SourceLocation StartLoc,
11092 SourceLocation LParenLoc,
11093 SourceLocation EndLoc) {
11094 Expr *ValExpr = Grainsize;
11096 // OpenMP [2.9.2, taskloop Constrcut]
11097 // The parameter of the grainsize clause must be a positive integer
11099 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11100 /*StrictlyPositive=*/true))
11103 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11106 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
11107 SourceLocation StartLoc,
11108 SourceLocation LParenLoc,
11109 SourceLocation EndLoc) {
11110 Expr *ValExpr = NumTasks;
11112 // OpenMP [2.9.2, taskloop Constrcut]
11113 // The parameter of the num_tasks clause must be a positive integer
11115 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11116 /*StrictlyPositive=*/true))
11119 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11122 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11123 SourceLocation LParenLoc,
11124 SourceLocation EndLoc) {
11125 // OpenMP [2.13.2, critical construct, Description]
11126 // ... where hint-expression is an integer constant expression that evaluates
11127 // to a valid lock hint.
11128 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11129 if (HintExpr.isInvalid())
11131 return new (Context)
11132 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11135 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11136 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11137 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11138 SourceLocation EndLoc) {
11139 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11140 std::string Values;
11142 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11144 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11145 << Values << getOpenMPClauseName(OMPC_dist_schedule);
11148 Expr *ValExpr = ChunkSize;
11149 Stmt *HelperValStmt = nullptr;
11151 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11152 !ChunkSize->isInstantiationDependent() &&
11153 !ChunkSize->containsUnexpandedParameterPack()) {
11154 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11156 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11157 if (Val.isInvalid())
11160 ValExpr = Val.get();
11162 // OpenMP [2.7.1, Restrictions]
11163 // chunk_size must be a loop invariant integer expression with a positive
11165 llvm::APSInt Result;
11166 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11167 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11168 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11169 << "dist_schedule" << ChunkSize->getSourceRange();
11172 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11173 !CurContext->isDependentContext()) {
11174 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11175 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11176 HelperValStmt = buildPreInits(Context, Captures);
11181 return new (Context)
11182 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
11183 Kind, ValExpr, HelperValStmt);
11186 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11187 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11188 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11189 SourceLocation KindLoc, SourceLocation EndLoc) {
11190 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
11191 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
11193 SourceLocation Loc;
11195 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11196 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
11197 OMPC_DEFAULTMAP_MODIFIER_tofrom);
11200 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
11201 OMPC_DEFAULTMAP_scalar);
11205 Diag(Loc, diag::err_omp_unexpected_clause_value)
11206 << Value << getOpenMPClauseName(OMPC_defaultmap);
11210 return new (Context)
11211 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11214 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11215 DeclContext *CurLexicalContext = getCurLexicalContext();
11216 if (!CurLexicalContext->isFileContext() &&
11217 !CurLexicalContext->isExternCContext() &&
11218 !CurLexicalContext->isExternCXXContext()) {
11219 Diag(Loc, diag::err_omp_region_not_file_context);
11222 if (IsInOpenMPDeclareTargetContext) {
11223 Diag(Loc, diag::err_omp_enclosed_declare_target);
11227 IsInOpenMPDeclareTargetContext = true;
11231 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11232 assert(IsInOpenMPDeclareTargetContext &&
11233 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11235 IsInOpenMPDeclareTargetContext = false;
11238 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
11239 CXXScopeSpec &ScopeSpec,
11240 const DeclarationNameInfo &Id,
11241 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11242 NamedDeclSetType &SameDirectiveDecls) {
11243 LookupResult Lookup(*this, Id, LookupOrdinaryName);
11244 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11246 if (Lookup.isAmbiguous())
11248 Lookup.suppressDiagnostics();
11250 if (!Lookup.isSingleResult()) {
11251 if (TypoCorrection Corrected =
11252 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11253 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11254 CTK_ErrorRecovery)) {
11255 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11257 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11261 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11265 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11266 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11267 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11268 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11270 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11271 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11273 if (ASTMutationListener *ML = Context.getASTMutationListener())
11274 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11275 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11276 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11277 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11281 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11284 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11285 Sema &SemaRef, Decl *D) {
11288 Decl *LD = nullptr;
11289 if (isa<TagDecl>(D)) {
11290 LD = cast<TagDecl>(D)->getDefinition();
11291 } else if (isa<VarDecl>(D)) {
11292 LD = cast<VarDecl>(D)->getDefinition();
11294 // If this is an implicit variable that is legal and we do not need to do
11296 if (cast<VarDecl>(D)->isImplicit()) {
11297 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11298 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11300 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
11301 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11305 } else if (isa<FunctionDecl>(D)) {
11306 const FunctionDecl *FD = nullptr;
11307 if (cast<FunctionDecl>(D)->hasBody(FD))
11308 LD = const_cast<FunctionDecl *>(FD);
11310 // If the definition is associated with the current declaration in the
11311 // target region (it can be e.g. a lambda) that is legal and we do not need
11312 // to do anything else.
11314 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11315 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11317 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
11318 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11324 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11325 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11326 // Outlined declaration is not declared target.
11327 if (LD->isOutOfLine()) {
11328 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11329 SemaRef.Diag(SL, diag::note_used_here) << SR;
11331 DeclContext *DC = LD->getDeclContext();
11333 if (isa<FunctionDecl>(DC) &&
11334 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11336 DC = DC->getParent();
11341 // Is not declared in target context.
11342 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11343 SemaRef.Diag(SL, diag::note_used_here) << SR;
11345 // Mark decl as declared target to prevent further diagnostic.
11346 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11347 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11349 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
11350 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11354 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11355 Sema &SemaRef, DSAStackTy *Stack,
11357 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11359 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11364 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11365 if (!D || D->isInvalidDecl())
11367 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11368 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11369 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11370 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11371 if (DSAStack->isThreadPrivate(VD)) {
11372 Diag(SL, diag::err_omp_threadprivate_in_target);
11373 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11377 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11378 // Problem if any with var declared with incomplete type will be reported
11379 // as normal, so no need to check it here.
11380 if ((E || !VD->getType()->isIncompleteType()) &&
11381 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11382 // Mark decl as declared target to prevent further diagnostic.
11383 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
11384 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11385 Context, OMPDeclareTargetDeclAttr::MT_To);
11387 if (ASTMutationListener *ML = Context.getASTMutationListener())
11388 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
11394 // Checking declaration inside declare target region.
11395 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11396 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
11397 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11398 Context, OMPDeclareTargetDeclAttr::MT_To);
11400 if (ASTMutationListener *ML = Context.getASTMutationListener())
11401 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11405 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11408 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11409 SourceLocation StartLoc,
11410 SourceLocation LParenLoc,
11411 SourceLocation EndLoc) {
11412 MappableVarListInfo MVLI(VarList);
11413 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11414 if (MVLI.ProcessedVarList.empty())
11417 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11418 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11419 MVLI.VarComponents);
11422 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11423 SourceLocation StartLoc,
11424 SourceLocation LParenLoc,
11425 SourceLocation EndLoc) {
11426 MappableVarListInfo MVLI(VarList);
11427 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11428 if (MVLI.ProcessedVarList.empty())
11431 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11432 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11433 MVLI.VarComponents);
11436 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11437 SourceLocation StartLoc,
11438 SourceLocation LParenLoc,
11439 SourceLocation EndLoc) {
11440 MappableVarListInfo MVLI(VarList);
11441 SmallVector<Expr *, 8> PrivateCopies;
11442 SmallVector<Expr *, 8> Inits;
11444 for (auto &RefExpr : VarList) {
11445 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11446 SourceLocation ELoc;
11447 SourceRange ERange;
11448 Expr *SimpleRefExpr = RefExpr;
11449 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11451 // It will be analyzed later.
11452 MVLI.ProcessedVarList.push_back(RefExpr);
11453 PrivateCopies.push_back(nullptr);
11454 Inits.push_back(nullptr);
11456 ValueDecl *D = Res.first;
11460 QualType Type = D->getType();
11461 Type = Type.getNonReferenceType().getUnqualifiedType();
11463 auto *VD = dyn_cast<VarDecl>(D);
11465 // Item should be a pointer or reference to pointer.
11466 if (!Type->isPointerType()) {
11467 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
11468 << 0 << RefExpr->getSourceRange();
11472 // Build the private variable and the expression that refers to it.
11473 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
11474 D->hasAttrs() ? &D->getAttrs() : nullptr);
11475 if (VDPrivate->isInvalidDecl())
11478 CurContext->addDecl(VDPrivate);
11479 auto VDPrivateRefExpr = buildDeclRefExpr(
11480 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11482 // Add temporary variable to initialize the private copy of the pointer.
11484 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11485 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11486 RefExpr->getExprLoc());
11487 AddInitializerToDecl(VDPrivate,
11488 DefaultLvalueConversion(VDInitRefExpr).get(),
11489 /*DirectInit=*/false);
11491 // If required, build a capture to implement the privatization initialized
11492 // with the current list item value.
11493 DeclRefExpr *Ref = nullptr;
11495 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11496 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11497 PrivateCopies.push_back(VDPrivateRefExpr);
11498 Inits.push_back(VDInitRefExpr);
11500 // We need to add a data sharing attribute for this variable to make sure it
11501 // is correctly captured. A variable that shows up in a use_device_ptr has
11502 // similar properties of a first private variable.
11503 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11505 // Create a mappable component for the list item. List items in this clause
11506 // only need a component.
11507 MVLI.VarBaseDeclarations.push_back(D);
11508 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11509 MVLI.VarComponents.back().push_back(
11510 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
11513 if (MVLI.ProcessedVarList.empty())
11516 return OMPUseDevicePtrClause::Create(
11517 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11518 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
11521 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11522 SourceLocation StartLoc,
11523 SourceLocation LParenLoc,
11524 SourceLocation EndLoc) {
11525 MappableVarListInfo MVLI(VarList);
11526 for (auto &RefExpr : VarList) {
11527 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
11528 SourceLocation ELoc;
11529 SourceRange ERange;
11530 Expr *SimpleRefExpr = RefExpr;
11531 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11533 // It will be analyzed later.
11534 MVLI.ProcessedVarList.push_back(RefExpr);
11536 ValueDecl *D = Res.first;
11540 QualType Type = D->getType();
11541 // item should be a pointer or array or reference to pointer or array
11542 if (!Type.getNonReferenceType()->isPointerType() &&
11543 !Type.getNonReferenceType()->isArrayType()) {
11544 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11545 << 0 << RefExpr->getSourceRange();
11549 // Check if the declaration in the clause does not show up in any data
11550 // sharing attribute.
11551 auto DVar = DSAStack->getTopDSA(D, false);
11552 if (isOpenMPPrivate(DVar.CKind)) {
11553 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11554 << getOpenMPClauseName(DVar.CKind)
11555 << getOpenMPClauseName(OMPC_is_device_ptr)
11556 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11557 ReportOriginalDSA(*this, DSAStack, D, DVar);
11561 Expr *ConflictExpr;
11562 if (DSAStack->checkMappableExprComponentListsForDecl(
11563 D, /*CurrentRegionOnly=*/true,
11565 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
11566 OpenMPClauseKind) -> bool {
11567 ConflictExpr = R.front().getAssociatedExpression();
11570 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
11571 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
11572 << ConflictExpr->getSourceRange();
11576 // Store the components in the stack so that they can be used to check
11577 // against other clauses later on.
11578 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11579 DSAStack->addMappableExpressionComponents(
11580 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11582 // Record the expression we've just processed.
11583 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11585 // Create a mappable component for the list item. List items in this clause
11586 // only need a component. We use a null declaration to signal fields in
11588 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11589 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11590 "Unexpected device pointer expression!");
11591 MVLI.VarBaseDeclarations.push_back(
11592 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11593 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11594 MVLI.VarComponents.back().push_back(MC);
11597 if (MVLI.ProcessedVarList.empty())
11600 return OMPIsDevicePtrClause::Create(
11601 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11602 MVLI.VarBaseDeclarations, MVLI.VarComponents);