1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// \brief This file implements semantic analysis for OpenMP directives and
13 //===----------------------------------------------------------------------===//
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclOpenMP.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtOpenMP.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeOrdering.h"
26 #include "clang/Basic/OpenMPKinds.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/Initialization.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/Scope.h"
32 #include "clang/Sema/ScopeInfo.h"
33 #include "clang/Sema/SemaInternal.h"
34 using namespace clang;
36 //===----------------------------------------------------------------------===//
37 // Stack of data-sharing attributes for variables
38 //===----------------------------------------------------------------------===//
41 /// \brief Default data sharing attributes, which can be applied to directive.
42 enum DefaultDataSharingAttributes {
43 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
48 /// \brief Stack for tracking declarations used in OpenMP directives and
49 /// clauses and their data-sharing attributes.
50 class DSAStackTy final {
52 struct DSAVarData final {
53 OpenMPDirectiveKind DKind = OMPD_unknown;
54 OpenMPClauseKind CKind = OMPC_unknown;
55 Expr *RefExpr = nullptr;
56 DeclRefExpr *PrivateCopy = nullptr;
57 SourceLocation ImplicitDSALoc;
60 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
64 struct DSAInfo final {
65 OpenMPClauseKind Attributes = OMPC_unknown;
66 /// Pointer to a reference expression and a flag which shows that the
67 /// variable is marked as lastprivate(true) or not (false).
68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
69 DeclRefExpr *PrivateCopy = nullptr;
71 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
73 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
75 /// Struct that associates a component with the clause kind where they are
77 struct MappedExprComponentTy {
78 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
79 OpenMPClauseKind Kind = OMPC_unknown;
81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
82 MappedExprComponentsTy;
83 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
85 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
88 struct SharingMapTy final {
89 DeclSAMapTy SharingMap;
90 AlignedMapTy AlignedMap;
91 MappedExprComponentsTy MappedExprComponents;
92 LoopControlVariablesMapTy LCVMap;
93 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
94 SourceLocation DefaultAttrLoc;
95 OpenMPDirectiveKind Directive = OMPD_unknown;
96 DeclarationNameInfo DirectiveName;
97 Scope *CurScope = nullptr;
98 SourceLocation ConstructLoc;
99 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
100 /// get the data (loop counters etc.) about enclosing loop-based construct.
101 /// This data is required during codegen.
102 DoacrossDependMapTy DoacrossDepends;
103 /// \brief first argument (Expr *) contains optional argument of the
104 /// 'ordered' clause, the second one is true if the regions has 'ordered'
105 /// clause, false otherwise.
106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
107 bool NowaitRegion = false;
108 bool CancelRegion = false;
109 unsigned AssociatedLoops = 1;
110 SourceLocation InnerTeamsRegionLoc;
111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
112 Scope *CurScope, SourceLocation Loc)
113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
118 typedef SmallVector<SharingMapTy, 4> StackTy;
120 /// \brief Stack of used declaration and their data-sharing attributes.
122 /// \brief true, if check for DSA must be from parent directive, false, if
123 /// from current directive.
124 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
126 bool ForceCapturing = false;
127 CriticalsWithHintsTy Criticals;
129 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
131 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
133 /// \brief Checks if the variable is a local for OpenMP region.
134 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
137 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
139 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
140 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
142 bool isForceVarCapturing() const { return ForceCapturing; }
143 void setForceVarCapturing(bool V) { ForceCapturing = V; }
145 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
146 Scope *CurScope, SourceLocation Loc) {
147 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
148 Stack.back().DefaultAttrLoc = Loc;
152 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
156 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
157 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
159 const std::pair<OMPCriticalDirective *, llvm::APSInt>
160 getCriticalWithHint(const DeclarationNameInfo &Name) const {
161 auto I = Criticals.find(Name.getAsString());
162 if (I != Criticals.end())
164 return std::make_pair(nullptr, llvm::APSInt());
166 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
167 /// add it and return NULL; otherwise return previous occurrence's expression
169 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
171 /// \brief Register specified variable as loop control variable.
172 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
173 /// \brief Check if the specified variable is a loop control variable for
175 /// \return The index of the loop control variable in the list of associated
176 /// for-loops (from outer to inner).
177 LCDeclInfo isLoopControlVariable(ValueDecl *D);
178 /// \brief Check if the specified variable is a loop control variable for
180 /// \return The index of the loop control variable in the list of associated
181 /// for-loops (from outer to inner).
182 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
183 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
184 /// parent directive.
185 ValueDecl *getParentLoopControlVariable(unsigned I);
187 /// \brief Adds explicit data sharing attribute to the specified declaration.
188 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
189 DeclRefExpr *PrivateCopy = nullptr);
191 /// \brief Returns data sharing attributes from top of the stack for the
192 /// specified declaration.
193 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
194 /// \brief Returns data-sharing attributes for the specified declaration.
195 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
196 /// \brief Checks if the specified variables has data-sharing attributes which
197 /// match specified \a CPred predicate in any directive which matches \a DPred
199 DSAVarData hasDSA(ValueDecl *D,
200 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
201 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
203 /// \brief Checks if the specified variables has data-sharing attributes which
204 /// match specified \a CPred predicate in any innermost directive which
205 /// matches \a DPred predicate.
207 hasInnermostDSA(ValueDecl *D,
208 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
209 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
211 /// \brief Checks if the specified variables has explicit data-sharing
212 /// attributes which match specified \a CPred predicate at the specified
214 bool hasExplicitDSA(ValueDecl *D,
215 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
216 unsigned Level, bool NotLastprivate = false);
218 /// \brief Returns true if the directive at level \Level matches in the
219 /// specified \a DPred predicate.
220 bool hasExplicitDirective(
221 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
224 /// \brief Finds a directive which matches specified \a DPred predicate.
225 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
226 const DeclarationNameInfo &,
227 SourceLocation)> &DPred,
230 /// \brief Returns currently analyzed directive.
231 OpenMPDirectiveKind getCurrentDirective() const {
232 return Stack.back().Directive;
234 /// \brief Returns parent directive.
235 OpenMPDirectiveKind getParentDirective() const {
236 if (Stack.size() > 2)
237 return Stack[Stack.size() - 2].Directive;
241 /// \brief Set default data sharing attribute to none.
242 void setDefaultDSANone(SourceLocation Loc) {
243 Stack.back().DefaultAttr = DSA_none;
244 Stack.back().DefaultAttrLoc = Loc;
246 /// \brief Set default data sharing attribute to shared.
247 void setDefaultDSAShared(SourceLocation Loc) {
248 Stack.back().DefaultAttr = DSA_shared;
249 Stack.back().DefaultAttrLoc = Loc;
252 DefaultDataSharingAttributes getDefaultDSA() const {
253 return Stack.back().DefaultAttr;
255 SourceLocation getDefaultDSALocation() const {
256 return Stack.back().DefaultAttrLoc;
259 /// \brief Checks if the specified variable is a threadprivate.
260 bool isThreadPrivate(VarDecl *D) {
261 DSAVarData DVar = getTopDSA(D, false);
262 return isOpenMPThreadPrivate(DVar.CKind);
265 /// \brief Marks current region as ordered (it has an 'ordered' clause).
266 void setOrderedRegion(bool IsOrdered, Expr *Param) {
267 Stack.back().OrderedRegion.setInt(IsOrdered);
268 Stack.back().OrderedRegion.setPointer(Param);
270 /// \brief Returns true, if parent region is ordered (has associated
271 /// 'ordered' clause), false - otherwise.
272 bool isParentOrderedRegion() const {
273 if (Stack.size() > 2)
274 return Stack[Stack.size() - 2].OrderedRegion.getInt();
277 /// \brief Returns optional parameter for the ordered region.
278 Expr *getParentOrderedRegionParam() const {
279 if (Stack.size() > 2)
280 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
283 /// \brief Marks current region as nowait (it has a 'nowait' clause).
284 void setNowaitRegion(bool IsNowait = true) {
285 Stack.back().NowaitRegion = IsNowait;
287 /// \brief Returns true, if parent region is nowait (has associated
288 /// 'nowait' clause), false - otherwise.
289 bool isParentNowaitRegion() const {
290 if (Stack.size() > 2)
291 return Stack[Stack.size() - 2].NowaitRegion;
294 /// \brief Marks parent region as cancel region.
295 void setParentCancelRegion(bool Cancel = true) {
296 if (Stack.size() > 2)
297 Stack[Stack.size() - 2].CancelRegion =
298 Stack[Stack.size() - 2].CancelRegion || Cancel;
300 /// \brief Return true if current region has inner cancel construct.
301 bool isCancelRegion() const { return Stack.back().CancelRegion; }
303 /// \brief Set collapse value for the region.
304 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
305 /// \brief Return collapse value for region.
306 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
308 /// \brief Marks current target region as one with closely nested teams
310 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
311 if (Stack.size() > 2)
312 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
314 /// \brief Returns true, if current region has closely nested teams region.
315 bool hasInnerTeamsRegion() const {
316 return getInnerTeamsRegionLoc().isValid();
318 /// \brief Returns location of the nested teams region (if any).
319 SourceLocation getInnerTeamsRegionLoc() const {
320 if (Stack.size() > 1)
321 return Stack.back().InnerTeamsRegionLoc;
322 return SourceLocation();
325 Scope *getCurScope() const { return Stack.back().CurScope; }
326 Scope *getCurScope() { return Stack.back().CurScope; }
327 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
329 /// Do the check specified in \a Check to all component lists and return true
330 /// if any issue is found.
331 bool checkMappableExprComponentListsForDecl(
332 ValueDecl *VD, bool CurrentRegionOnly,
333 const llvm::function_ref<
334 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
335 OpenMPClauseKind)> &Check) {
336 auto SI = Stack.rbegin();
337 auto SE = Stack.rend();
342 if (CurrentRegionOnly) {
348 for (; SI != SE; ++SI) {
349 auto MI = SI->MappedExprComponents.find(VD);
350 if (MI != SI->MappedExprComponents.end())
351 for (auto &L : MI->second.Components)
352 if (Check(L, MI->second.Kind))
358 /// Create a new mappable expression component list associated with a given
359 /// declaration and initialize it with the provided list of components.
360 void addMappableExpressionComponents(
362 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
363 OpenMPClauseKind WhereFoundClauseKind) {
364 assert(Stack.size() > 1 &&
365 "Not expecting to retrieve components from a empty stack!");
366 auto &MEC = Stack.back().MappedExprComponents[VD];
367 // Create new entry and append the new components there.
368 MEC.Components.resize(MEC.Components.size() + 1);
369 MEC.Components.back().append(Components.begin(), Components.end());
370 MEC.Kind = WhereFoundClauseKind;
373 unsigned getNestingLevel() const {
374 assert(Stack.size() > 1);
375 return Stack.size() - 2;
377 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
378 assert(Stack.size() > 2);
379 assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive));
380 Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs});
382 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
383 getDoacrossDependClauses() const {
384 assert(Stack.size() > 1);
385 if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) {
386 auto &Ref = Stack[Stack.size() - 1].DoacrossDepends;
387 return llvm::make_range(Ref.begin(), Ref.end());
389 return llvm::make_range(Stack[0].DoacrossDepends.end(),
390 Stack[0].DoacrossDepends.end());
393 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
394 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
395 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
399 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
400 auto *VD = dyn_cast<VarDecl>(D);
401 auto *FD = dyn_cast<FieldDecl>(D);
403 VD = VD->getCanonicalDecl();
407 FD = FD->getCanonicalDecl();
413 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
415 D = getCanonicalDecl(D);
416 auto *VD = dyn_cast<VarDecl>(D);
417 auto *FD = dyn_cast<FieldDecl>(D);
419 if (Iter == std::prev(Stack.rend())) {
420 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
421 // in a region but not in construct]
422 // File-scope or namespace-scope variables referenced in called routines
423 // in the region are shared unless they appear in a threadprivate
425 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
426 DVar.CKind = OMPC_shared;
428 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
429 // in a region but not in construct]
430 // Variables with static storage duration that are declared in called
431 // routines in the region are shared.
432 if (VD && VD->hasGlobalStorage())
433 DVar.CKind = OMPC_shared;
435 // Non-static data members are shared by default.
437 DVar.CKind = OMPC_shared;
442 DVar.DKind = Iter->Directive;
443 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
444 // in a Construct, C/C++, predetermined, p.1]
445 // Variables with automatic storage duration that are declared in a scope
446 // inside the construct are private.
447 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
448 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
449 DVar.CKind = OMPC_private;
453 // Explicitly specified attributes and local variables with predetermined
455 if (Iter->SharingMap.count(D)) {
456 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
457 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
458 DVar.CKind = Iter->SharingMap[D].Attributes;
459 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
463 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
464 // in a Construct, C/C++, implicitly determined, p.1]
465 // In a parallel or task construct, the data-sharing attributes of these
466 // variables are determined by the default clause, if present.
467 switch (Iter->DefaultAttr) {
469 DVar.CKind = OMPC_shared;
470 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
474 case DSA_unspecified:
475 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
476 // in a Construct, implicitly determined, p.2]
477 // In a parallel construct, if no default clause is present, these
478 // variables are shared.
479 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
480 if (isOpenMPParallelDirective(DVar.DKind) ||
481 isOpenMPTeamsDirective(DVar.DKind)) {
482 DVar.CKind = OMPC_shared;
486 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
487 // in a Construct, implicitly determined, p.4]
488 // In a task construct, if no default clause is present, a variable that in
489 // the enclosing context is determined to be shared by all implicit tasks
490 // bound to the current team is shared.
491 if (isOpenMPTaskingDirective(DVar.DKind)) {
493 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
495 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
496 // Referenced in a Construct, implicitly determined, p.6]
497 // In a task construct, if no default clause is present, a variable
498 // whose data-sharing attribute is not determined by the rules above is
500 DVarTemp = getDSA(I, D);
501 if (DVarTemp.CKind != OMPC_shared) {
502 DVar.RefExpr = nullptr;
503 DVar.CKind = OMPC_firstprivate;
506 if (isParallelOrTaskRegion(I->Directive))
510 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
514 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
515 // in a Construct, implicitly determined, p.3]
516 // For constructs other than task, if no default clause is present, these
517 // variables inherit their data-sharing attributes from the enclosing
519 return getDSA(++Iter, D);
522 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
523 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
524 D = getCanonicalDecl(D);
525 auto It = Stack.back().AlignedMap.find(D);
526 if (It == Stack.back().AlignedMap.end()) {
527 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
528 Stack.back().AlignedMap[D] = NewDE;
531 assert(It->second && "Unexpected nullptr expr in the aligned map");
537 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
538 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
539 D = getCanonicalDecl(D);
540 Stack.back().LCVMap.insert(
541 std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
544 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
545 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
546 D = getCanonicalDecl(D);
547 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
548 : LCDeclInfo(0, nullptr);
551 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
552 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
553 D = getCanonicalDecl(D);
554 return Stack[Stack.size() - 2].LCVMap.count(D) > 0
555 ? Stack[Stack.size() - 2].LCVMap[D]
556 : LCDeclInfo(0, nullptr);
559 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
560 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
561 if (Stack[Stack.size() - 2].LCVMap.size() < I)
563 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
564 if (Pair.second.first == I)
570 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
571 DeclRefExpr *PrivateCopy) {
572 D = getCanonicalDecl(D);
573 if (A == OMPC_threadprivate) {
574 auto &Data = Stack[0].SharingMap[D];
576 Data.RefExpr.setPointer(E);
577 Data.PrivateCopy = nullptr;
579 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
580 auto &Data = Stack.back().SharingMap[D];
581 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
582 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
583 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
584 (isLoopControlVariable(D).first && A == OMPC_private));
585 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
586 Data.RefExpr.setInt(/*IntVal=*/true);
589 const bool IsLastprivate =
590 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
592 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
593 Data.PrivateCopy = PrivateCopy;
595 auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()];
597 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
598 Data.PrivateCopy = nullptr;
603 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
604 D = D->getCanonicalDecl();
605 if (Stack.size() > 2) {
606 reverse_iterator I = Iter, E = std::prev(Stack.rend());
607 Scope *TopScope = nullptr;
608 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
613 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
614 Scope *CurScope = getCurScope();
615 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
616 CurScope = CurScope->getParent();
618 return CurScope != TopScope;
623 /// \brief Build a variable declaration for OpenMP loop iteration variable.
624 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
625 StringRef Name, const AttrVec *Attrs = nullptr) {
626 DeclContext *DC = SemaRef.CurContext;
627 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
628 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
630 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
632 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
640 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
642 bool RefersToCapture = false) {
644 D->markUsed(S.Context);
645 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
646 SourceLocation(), D, RefersToCapture, Loc, Ty,
650 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
651 D = getCanonicalDecl(D);
654 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
655 // in a Construct, C/C++, predetermined, p.1]
656 // Variables appearing in threadprivate directives are threadprivate.
657 auto *VD = dyn_cast<VarDecl>(D);
658 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
659 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
660 SemaRef.getLangOpts().OpenMPUseTLS &&
661 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
662 (VD && VD->getStorageClass() == SC_Register &&
663 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
664 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
668 if (Stack[0].SharingMap.count(D)) {
669 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer();
670 DVar.CKind = OMPC_threadprivate;
674 if (Stack.size() == 1) {
675 // Not in OpenMP execution region and top scope was already checked.
679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
680 // in a Construct, C/C++, predetermined, p.4]
681 // Static data members are shared.
682 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
683 // in a Construct, C/C++, predetermined, p.7]
684 // Variables with static storage duration that are declared in a scope
685 // inside the construct are shared.
686 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
687 if (VD && VD->isStaticDataMember()) {
688 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
689 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
692 DVar.CKind = OMPC_shared;
696 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
697 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
698 Type = SemaRef.getASTContext().getBaseElementType(Type);
699 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
700 // in a Construct, C/C++, predetermined, p.6]
701 // Variables with const qualified type having no mutable member are
704 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
705 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
706 if (auto *CTD = CTSD->getSpecializedTemplate())
707 RD = CTD->getTemplatedDecl();
709 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
710 RD->hasMutableFields())) {
711 // Variables with const-qualified type having no mutable member may be
712 // listed in a firstprivate clause, even if they are static data members.
713 DSAVarData DVarTemp = hasDSA(
714 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
715 MatchesAlways, FromParent);
716 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
719 DVar.CKind = OMPC_shared;
723 // Explicitly specified attributes and local variables with predetermined
725 auto StartI = std::next(Stack.rbegin());
726 auto EndI = std::prev(Stack.rend());
727 if (FromParent && StartI != EndI) {
728 StartI = std::next(StartI);
730 auto I = std::prev(StartI);
731 if (I->SharingMap.count(D)) {
732 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
733 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
734 DVar.CKind = I->SharingMap[D].Attributes;
735 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
741 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
743 D = getCanonicalDecl(D);
744 auto StartI = Stack.rbegin();
745 auto EndI = std::prev(Stack.rend());
746 if (FromParent && StartI != EndI) {
747 StartI = std::next(StartI);
749 return getDSA(StartI, D);
752 DSAStackTy::DSAVarData
753 DSAStackTy::hasDSA(ValueDecl *D,
754 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
755 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
757 D = getCanonicalDecl(D);
758 auto StartI = std::next(Stack.rbegin());
759 auto EndI = Stack.rend();
760 if (FromParent && StartI != EndI) {
761 StartI = std::next(StartI);
763 for (auto I = StartI, EE = EndI; I != EE; ++I) {
764 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
766 DSAVarData DVar = getDSA(I, D);
767 if (CPred(DVar.CKind))
773 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
774 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
775 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
777 D = getCanonicalDecl(D);
778 auto StartI = std::next(Stack.rbegin());
779 auto EndI = Stack.rend();
780 if (FromParent && StartI != EndI)
781 StartI = std::next(StartI);
782 if (StartI == EndI || !DPred(StartI->Directive))
784 DSAVarData DVar = getDSA(StartI, D);
785 return CPred(DVar.CKind) ? DVar : DSAVarData();
788 bool DSAStackTy::hasExplicitDSA(
789 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
790 unsigned Level, bool NotLastprivate) {
791 if (CPred(ClauseKindMode))
793 D = getCanonicalDecl(D);
794 auto StartI = std::next(Stack.begin());
795 auto EndI = Stack.end();
796 if (std::distance(StartI, EndI) <= (int)Level)
798 std::advance(StartI, Level);
799 return (StartI->SharingMap.count(D) > 0) &&
800 StartI->SharingMap[D].RefExpr.getPointer() &&
801 CPred(StartI->SharingMap[D].Attributes) &&
802 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
805 bool DSAStackTy::hasExplicitDirective(
806 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
808 auto StartI = std::next(Stack.begin());
809 auto EndI = Stack.end();
810 if (std::distance(StartI, EndI) <= (int)Level)
812 std::advance(StartI, Level);
813 return DPred(StartI->Directive);
816 bool DSAStackTy::hasDirective(
817 const llvm::function_ref<bool(OpenMPDirectiveKind,
818 const DeclarationNameInfo &, SourceLocation)>
821 // We look only in the enclosing region.
822 if (Stack.size() < 2)
824 auto StartI = std::next(Stack.rbegin());
825 auto EndI = std::prev(Stack.rend());
826 if (FromParent && StartI != EndI) {
827 StartI = std::next(StartI);
829 for (auto I = StartI, EE = EndI; I != EE; ++I) {
830 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
836 void Sema::InitDataSharingAttributesStack() {
837 VarDataSharingAttributesStack = new DSAStackTy(*this);
840 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
842 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
843 assert(LangOpts.OpenMP && "OpenMP is not allowed");
845 auto &Ctx = getASTContext();
848 // Find the directive that is associated with the provided scope.
849 auto Ty = D->getType();
851 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
852 // This table summarizes how a given variable should be passed to the device
853 // given its type and the clauses where it appears. This table is based on
854 // the description in OpenMP 4.5 [2.10.4, target Construct] and
855 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
857 // =========================================================================
858 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
859 // | |(tofrom:scalar)| | pvt | | | |
860 // =========================================================================
861 // | scl | | | | - | | bycopy|
862 // | scl | | - | x | - | - | bycopy|
863 // | scl | | x | - | - | - | null |
864 // | scl | x | | | - | | byref |
865 // | scl | x | - | x | - | - | bycopy|
866 // | scl | x | x | - | - | - | null |
867 // | scl | | - | - | - | x | byref |
868 // | scl | x | - | - | - | x | byref |
870 // | agg | n.a. | | | - | | byref |
871 // | agg | n.a. | - | x | - | - | byref |
872 // | agg | n.a. | x | - | - | - | null |
873 // | agg | n.a. | - | - | - | x | byref |
874 // | agg | n.a. | - | - | - | x[] | byref |
876 // | ptr | n.a. | | | - | | bycopy|
877 // | ptr | n.a. | - | x | - | - | bycopy|
878 // | ptr | n.a. | x | - | - | - | null |
879 // | ptr | n.a. | - | - | - | x | byref |
880 // | ptr | n.a. | - | - | - | x[] | bycopy|
881 // | ptr | n.a. | - | - | x | | bycopy|
882 // | ptr | n.a. | - | - | x | x | bycopy|
883 // | ptr | n.a. | - | - | x | x[] | bycopy|
884 // =========================================================================
890 // - - invalid in this combination
891 // [] - mapped with an array section
892 // byref - should be mapped by reference
893 // byval - should be mapped by value
894 // null - initialize a local variable to null on the device
897 // - All scalar declarations that show up in a map clause have to be passed
898 // by reference, because they may have been mapped in the enclosing data
900 // - If the scalar value does not fit the size of uintptr, it has to be
901 // passed by reference, regardless the result in the table above.
902 // - For pointers mapped by value that have either an implicit map or an
903 // array section, the runtime library may pass the NULL value to the
904 // device instead of the value passed to it by the compiler.
906 if (Ty->isReferenceType())
907 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
909 // Locate map clauses and see if the variable being captured is referred to
910 // in any of those clauses. Here we only care about variables, not fields,
911 // because fields are part of aggregates.
912 bool IsVariableUsedInMapClause = false;
913 bool IsVariableAssociatedWithSection = false;
915 DSAStack->checkMappableExprComponentListsForDecl(
916 D, /*CurrentRegionOnly=*/true,
917 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
919 OpenMPClauseKind WhereFoundClauseKind) {
920 // Only the map clause information influences how a variable is
921 // captured. E.g. is_device_ptr does not require changing the default
923 if (WhereFoundClauseKind != OMPC_map)
926 auto EI = MapExprComponents.rbegin();
927 auto EE = MapExprComponents.rend();
929 assert(EI != EE && "Invalid map expression!");
931 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
932 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
938 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
939 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
940 isa<MemberExpr>(EI->getAssociatedExpression())) {
941 IsVariableAssociatedWithSection = true;
942 // There is nothing more we need to know about this variable.
946 // Keep looking for more map info.
950 if (IsVariableUsedInMapClause) {
951 // If variable is identified in a map clause it is always captured by
952 // reference except if it is a pointer that is dereferenced somehow.
953 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
955 // By default, all the data that has a scalar type is mapped by copy.
956 IsByRef = !Ty->isScalarType();
960 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
961 IsByRef = !DSAStack->hasExplicitDSA(
962 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
963 Level, /*NotLastprivate=*/true);
966 // When passing data by copy, we need to make sure it fits the uintptr size
967 // and alignment, because the runtime library only deals with uintptr types.
968 // If it does not fit the uintptr size, we need to pass the data by reference
971 (Ctx.getTypeSizeInChars(Ty) >
972 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
973 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
980 unsigned Sema::getOpenMPNestingLevel() const {
981 assert(getLangOpts().OpenMP);
982 return DSAStack->getNestingLevel();
985 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
986 assert(LangOpts.OpenMP && "OpenMP is not allowed");
987 D = getCanonicalDecl(D);
989 // If we are attempting to capture a global variable in a directive with
990 // 'target' we return true so that this global is also mapped to the device.
992 // FIXME: If the declaration is enclosed in a 'declare target' directive,
993 // then it should not be captured. Therefore, an extra check has to be
994 // inserted here once support for 'declare target' is added.
996 auto *VD = dyn_cast<VarDecl>(D);
997 if (VD && !VD->hasLocalStorage()) {
998 if (DSAStack->getCurrentDirective() == OMPD_target &&
999 !DSAStack->isClauseParsingMode())
1001 if (DSAStack->hasDirective(
1002 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1003 SourceLocation) -> bool {
1004 return isOpenMPTargetExecutionDirective(K);
1010 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1011 (!DSAStack->isClauseParsingMode() ||
1012 DSAStack->getParentDirective() != OMPD_unknown)) {
1013 auto &&Info = DSAStack->isLoopControlVariable(D);
1015 (VD && VD->hasLocalStorage() &&
1016 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
1017 (VD && DSAStack->isForceVarCapturing()))
1018 return VD ? VD : Info.second;
1019 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
1020 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
1021 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1022 DVarPrivate = DSAStack->hasDSA(
1023 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1024 DSAStack->isClauseParsingMode());
1025 if (DVarPrivate.CKind != OMPC_unknown)
1026 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1031 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
1032 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1033 return DSAStack->hasExplicitDSA(
1034 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
1037 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
1038 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1039 // Return true if the current level is no longer enclosed in a target region.
1041 auto *VD = dyn_cast<VarDecl>(D);
1042 return VD && !VD->hasLocalStorage() &&
1043 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1047 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
1049 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1050 const DeclarationNameInfo &DirName,
1051 Scope *CurScope, SourceLocation Loc) {
1052 DSAStack->push(DKind, DirName, CurScope, Loc);
1053 PushExpressionEvaluationContext(PotentiallyEvaluated);
1056 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1057 DSAStack->setClauseParsingMode(K);
1060 void Sema::EndOpenMPClause() {
1061 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1064 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1065 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1066 // A variable of class type (or array thereof) that appears in a lastprivate
1067 // clause requires an accessible, unambiguous default constructor for the
1068 // class type, unless the list item is also specified in a firstprivate
1070 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1071 for (auto *C : D->clauses()) {
1072 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1073 SmallVector<Expr *, 8> PrivateCopies;
1074 for (auto *DE : Clause->varlists()) {
1075 if (DE->isValueDependent() || DE->isTypeDependent()) {
1076 PrivateCopies.push_back(nullptr);
1079 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1080 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1081 QualType Type = VD->getType().getNonReferenceType();
1082 auto DVar = DSAStack->getTopDSA(VD, false);
1083 if (DVar.CKind == OMPC_lastprivate) {
1084 // Generate helper private variable and initialize it with the
1085 // default value. The address of the original variable is replaced
1086 // by the address of the new private variable in CodeGen. This new
1087 // variable is not added to IdResolver, so the code in the OpenMP
1088 // region uses original variable for proper diagnostics.
1089 auto *VDPrivate = buildVarDecl(
1090 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1091 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
1092 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
1093 if (VDPrivate->isInvalidDecl())
1095 PrivateCopies.push_back(buildDeclRefExpr(
1096 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1098 // The variable is also a firstprivate, so initialization sequence
1099 // for private copy is generated already.
1100 PrivateCopies.push_back(nullptr);
1103 // Set initializers to private copies if no errors were found.
1104 if (PrivateCopies.size() == Clause->varlist_size())
1105 Clause->setPrivateCopies(PrivateCopies);
1111 DiscardCleanupsInEvaluationContext();
1112 PopExpressionEvaluationContext();
1115 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1116 Expr *NumIterations, Sema &SemaRef,
1117 Scope *S, DSAStackTy *Stack);
1121 class VarDeclFilterCCC : public CorrectionCandidateCallback {
1126 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1127 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1128 NamedDecl *ND = Candidate.getCorrectionDecl();
1129 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1130 return VD->hasGlobalStorage() &&
1131 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1132 SemaRef.getCurScope());
1138 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1143 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1144 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1145 NamedDecl *ND = Candidate.getCorrectionDecl();
1146 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1147 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1148 SemaRef.getCurScope());
1156 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1157 CXXScopeSpec &ScopeSpec,
1158 const DeclarationNameInfo &Id) {
1159 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1160 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1162 if (Lookup.isAmbiguous())
1166 if (!Lookup.isSingleResult()) {
1167 if (TypoCorrection Corrected = CorrectTypo(
1168 Id, LookupOrdinaryName, CurScope, nullptr,
1169 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1170 diagnoseTypo(Corrected,
1171 PDiag(Lookup.empty()
1172 ? diag::err_undeclared_var_use_suggest
1173 : diag::err_omp_expected_var_arg_suggest)
1175 VD = Corrected.getCorrectionDeclAs<VarDecl>();
1177 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1178 : diag::err_omp_expected_var_arg)
1183 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1184 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1185 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1189 Lookup.suppressDiagnostics();
1191 // OpenMP [2.9.2, Syntax, C/C++]
1192 // Variables must be file-scope, namespace-scope, or static block-scope.
1193 if (!VD->hasGlobalStorage()) {
1194 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1195 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1197 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1198 Diag(VD->getLocation(),
1199 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1204 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1205 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
1206 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1207 // A threadprivate directive for file-scope variables must appear outside
1208 // any definition or declaration.
1209 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1210 !getCurLexicalContext()->isTranslationUnit()) {
1211 Diag(Id.getLoc(), diag::err_omp_var_scope)
1212 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1214 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1215 Diag(VD->getLocation(),
1216 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1220 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1221 // A threadprivate directive for static class member variables must appear
1222 // in the class definition, in the same scope in which the member
1223 // variables are declared.
1224 if (CanonicalVD->isStaticDataMember() &&
1225 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1226 Diag(Id.getLoc(), diag::err_omp_var_scope)
1227 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1229 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1230 Diag(VD->getLocation(),
1231 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1235 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1236 // A threadprivate directive for namespace-scope variables must appear
1237 // outside any definition or declaration other than the namespace
1238 // definition itself.
1239 if (CanonicalVD->getDeclContext()->isNamespace() &&
1240 (!getCurLexicalContext()->isFileContext() ||
1241 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1242 Diag(Id.getLoc(), diag::err_omp_var_scope)
1243 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1245 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1246 Diag(VD->getLocation(),
1247 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1251 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1252 // A threadprivate directive for static block-scope variables must appear
1253 // in the scope of the variable and not in a nested scope.
1254 if (CanonicalVD->isStaticLocal() && CurScope &&
1255 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1256 Diag(Id.getLoc(), diag::err_omp_var_scope)
1257 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1259 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1260 Diag(VD->getLocation(),
1261 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1266 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1267 // A threadprivate directive must lexically precede all references to any
1268 // of the variables in its list.
1269 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1270 Diag(Id.getLoc(), diag::err_omp_var_used)
1271 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1275 QualType ExprType = VD->getType().getNonReferenceType();
1276 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1277 SourceLocation(), VD,
1278 /*RefersToEnclosingVariableOrCapture=*/false,
1279 Id.getLoc(), ExprType, VK_LValue);
1282 Sema::DeclGroupPtrTy
1283 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1284 ArrayRef<Expr *> VarList) {
1285 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1286 CurContext->addDecl(D);
1287 return DeclGroupPtrTy::make(DeclGroupRef(D));
1293 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1297 bool VisitDeclRefExpr(const DeclRefExpr *E) {
1298 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1299 if (VD->hasLocalStorage()) {
1300 SemaRef.Diag(E->getLocStart(),
1301 diag::err_omp_local_var_in_threadprivate_init)
1302 << E->getSourceRange();
1303 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1304 << VD << VD->getSourceRange();
1310 bool VisitStmt(const Stmt *S) {
1311 for (auto Child : S->children()) {
1312 if (Child && Visit(Child))
1317 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1321 OMPThreadPrivateDecl *
1322 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1323 SmallVector<Expr *, 8> Vars;
1324 for (auto &RefExpr : VarList) {
1325 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
1326 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1327 SourceLocation ILoc = DE->getExprLoc();
1329 // Mark variable as used.
1330 VD->setReferenced();
1331 VD->markUsed(Context);
1333 QualType QType = VD->getType();
1334 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1335 // It will be analyzed later.
1340 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1341 // A threadprivate variable must not have an incomplete type.
1342 if (RequireCompleteType(ILoc, VD->getType(),
1343 diag::err_omp_threadprivate_incomplete_type)) {
1347 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1348 // A threadprivate variable must not have a reference type.
1349 if (VD->getType()->isReferenceType()) {
1350 Diag(ILoc, diag::err_omp_ref_type_arg)
1351 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1353 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1354 Diag(VD->getLocation(),
1355 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1360 // Check if this is a TLS variable. If TLS is not being supported, produce
1361 // the corresponding diagnostic.
1362 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1363 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1364 getLangOpts().OpenMPUseTLS &&
1365 getASTContext().getTargetInfo().isTLSSupported())) ||
1366 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1367 !VD->isLocalVarDecl())) {
1368 Diag(ILoc, diag::err_omp_var_thread_local)
1369 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1371 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1372 Diag(VD->getLocation(),
1373 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1378 // Check if initial value of threadprivate variable reference variable with
1379 // local storage (it is not supported by runtime).
1380 if (auto Init = VD->getAnyInitializer()) {
1381 LocalVarRefChecker Checker(*this);
1382 if (Checker.Visit(Init))
1386 Vars.push_back(RefExpr);
1387 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1388 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1389 Context, SourceRange(Loc, Loc)));
1390 if (auto *ML = Context.getASTMutationListener())
1391 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1393 OMPThreadPrivateDecl *D = nullptr;
1394 if (!Vars.empty()) {
1395 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1397 D->setAccess(AS_public);
1402 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1403 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
1404 bool IsLoopIterVar = false) {
1406 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1407 << getOpenMPClauseName(DVar.CKind);
1411 PDSA_StaticMemberShared,
1412 PDSA_StaticLocalVarShared,
1413 PDSA_LoopIterVarPrivate,
1414 PDSA_LoopIterVarLinear,
1415 PDSA_LoopIterVarLastprivate,
1416 PDSA_ConstVarShared,
1417 PDSA_GlobalVarShared,
1418 PDSA_TaskVarFirstprivate,
1419 PDSA_LocalVarPrivate,
1421 } Reason = PDSA_Implicit;
1422 bool ReportHint = false;
1423 auto ReportLoc = D->getLocation();
1424 auto *VD = dyn_cast<VarDecl>(D);
1425 if (IsLoopIterVar) {
1426 if (DVar.CKind == OMPC_private)
1427 Reason = PDSA_LoopIterVarPrivate;
1428 else if (DVar.CKind == OMPC_lastprivate)
1429 Reason = PDSA_LoopIterVarLastprivate;
1431 Reason = PDSA_LoopIterVarLinear;
1432 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1433 DVar.CKind == OMPC_firstprivate) {
1434 Reason = PDSA_TaskVarFirstprivate;
1435 ReportLoc = DVar.ImplicitDSALoc;
1436 } else if (VD && VD->isStaticLocal())
1437 Reason = PDSA_StaticLocalVarShared;
1438 else if (VD && VD->isStaticDataMember())
1439 Reason = PDSA_StaticMemberShared;
1440 else if (VD && VD->isFileVarDecl())
1441 Reason = PDSA_GlobalVarShared;
1442 else if (D->getType().isConstant(SemaRef.getASTContext()))
1443 Reason = PDSA_ConstVarShared;
1444 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1446 Reason = PDSA_LocalVarPrivate;
1448 if (Reason != PDSA_Implicit) {
1449 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1450 << Reason << ReportHint
1451 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1452 } else if (DVar.ImplicitDSALoc.isValid()) {
1453 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1454 << getOpenMPClauseName(DVar.CKind);
1459 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1464 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1465 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
1468 void VisitDeclRefExpr(DeclRefExpr *E) {
1469 if (E->isTypeDependent() || E->isValueDependent() ||
1470 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1472 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1473 // Skip internally declared variables.
1474 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1477 auto DVar = Stack->getTopDSA(VD, false);
1478 // Check if the variable has explicit DSA set and stop analysis if it so.
1482 auto ELoc = E->getExprLoc();
1483 auto DKind = Stack->getCurrentDirective();
1484 // The default(none) clause requires that each variable that is referenced
1485 // in the construct, and does not have a predetermined data-sharing
1486 // attribute, must have its data-sharing attribute explicitly determined
1487 // by being listed in a data-sharing attribute clause.
1488 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1489 isParallelOrTaskRegion(DKind) &&
1490 VarsWithInheritedDSA.count(VD) == 0) {
1491 VarsWithInheritedDSA[VD] = E;
1495 // OpenMP [2.9.3.6, Restrictions, p.2]
1496 // A list item that appears in a reduction clause of the innermost
1497 // enclosing worksharing or parallel construct may not be accessed in an
1499 DVar = Stack->hasInnermostDSA(
1500 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1501 [](OpenMPDirectiveKind K) -> bool {
1502 return isOpenMPParallelDirective(K) ||
1503 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1506 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1508 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1509 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1513 // Define implicit data-sharing attributes for task.
1514 DVar = Stack->getImplicitDSA(VD, false);
1515 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1516 !Stack->isLoopControlVariable(VD).first)
1517 ImplicitFirstprivate.push_back(E);
1520 void VisitMemberExpr(MemberExpr *E) {
1521 if (E->isTypeDependent() || E->isValueDependent() ||
1522 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1524 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1525 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1526 auto DVar = Stack->getTopDSA(FD, false);
1527 // Check if the variable has explicit DSA set and stop analysis if it
1532 auto ELoc = E->getExprLoc();
1533 auto DKind = Stack->getCurrentDirective();
1534 // OpenMP [2.9.3.6, Restrictions, p.2]
1535 // A list item that appears in a reduction clause of the innermost
1536 // enclosing worksharing or parallel construct may not be accessed in
1537 // an explicit task.
1538 DVar = Stack->hasInnermostDSA(
1539 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1540 [](OpenMPDirectiveKind K) -> bool {
1541 return isOpenMPParallelDirective(K) ||
1542 isOpenMPWorksharingDirective(K) ||
1543 isOpenMPTeamsDirective(K);
1546 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1548 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1549 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1553 // Define implicit data-sharing attributes for task.
1554 DVar = Stack->getImplicitDSA(FD, false);
1555 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1556 !Stack->isLoopControlVariable(FD).first)
1557 ImplicitFirstprivate.push_back(E);
1560 Visit(E->getBase());
1562 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
1563 for (auto *C : S->clauses()) {
1564 // Skip analysis of arguments of implicitly defined firstprivate clause
1565 // for task directives.
1566 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1567 for (auto *CC : C->children()) {
1573 void VisitStmt(Stmt *S) {
1574 for (auto *C : S->children()) {
1575 if (C && !isa<OMPExecutableDirective>(C))
1580 bool isErrorFound() { return ErrorFound; }
1581 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
1582 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
1583 return VarsWithInheritedDSA;
1586 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1587 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1591 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1594 case OMPD_parallel_for:
1595 case OMPD_parallel_for_simd:
1596 case OMPD_parallel_sections:
1598 case OMPD_target_teams: {
1599 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1600 QualType KmpInt32PtrTy =
1601 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1602 Sema::CapturedParamNameType Params[] = {
1603 std::make_pair(".global_tid.", KmpInt32PtrTy),
1604 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1605 std::make_pair(StringRef(), QualType()) // __context with shared vars
1607 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1619 case OMPD_taskgroup:
1620 case OMPD_distribute:
1623 case OMPD_target_data:
1625 case OMPD_target_parallel:
1626 case OMPD_target_parallel_for:
1627 case OMPD_target_parallel_for_simd:
1628 case OMPD_target_simd: {
1629 Sema::CapturedParamNameType Params[] = {
1630 std::make_pair(StringRef(), QualType()) // __context with shared vars
1632 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1637 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1638 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1639 FunctionProtoType::ExtProtoInfo EPI;
1640 EPI.Variadic = true;
1641 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1642 Sema::CapturedParamNameType Params[] = {
1643 std::make_pair(".global_tid.", KmpInt32Ty),
1644 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1645 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1646 std::make_pair(".copy_fn.",
1647 Context.getPointerType(CopyFnType).withConst()),
1648 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1649 std::make_pair(StringRef(), QualType()) // __context with shared vars
1651 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1653 // Mark this captured region as inlined, because we don't use outlined
1654 // function directly.
1655 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1656 AlwaysInlineAttr::CreateImplicit(
1657 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1661 case OMPD_taskloop_simd: {
1662 QualType KmpInt32Ty =
1663 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1664 QualType KmpUInt64Ty =
1665 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1666 QualType KmpInt64Ty =
1667 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1668 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1669 FunctionProtoType::ExtProtoInfo EPI;
1670 EPI.Variadic = true;
1671 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1672 Sema::CapturedParamNameType Params[] = {
1673 std::make_pair(".global_tid.", KmpInt32Ty),
1674 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1675 std::make_pair(".privates.",
1676 Context.VoidPtrTy.withConst().withRestrict()),
1679 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1680 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1681 std::make_pair(".lb.", KmpUInt64Ty),
1682 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1683 std::make_pair(".liter.", KmpInt32Ty),
1684 std::make_pair(StringRef(), QualType()) // __context with shared vars
1686 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1688 // Mark this captured region as inlined, because we don't use outlined
1689 // function directly.
1690 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1691 AlwaysInlineAttr::CreateImplicit(
1692 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1695 case OMPD_distribute_parallel_for_simd:
1696 case OMPD_distribute_simd:
1697 case OMPD_distribute_parallel_for:
1698 case OMPD_teams_distribute:
1699 case OMPD_teams_distribute_simd:
1700 case OMPD_teams_distribute_parallel_for_simd:
1701 case OMPD_teams_distribute_parallel_for:
1702 case OMPD_target_teams_distribute:
1703 case OMPD_target_teams_distribute_parallel_for: {
1704 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1705 QualType KmpInt32PtrTy =
1706 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1707 Sema::CapturedParamNameType Params[] = {
1708 std::make_pair(".global_tid.", KmpInt32PtrTy),
1709 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1710 std::make_pair(".previous.lb.", Context.getSizeType()),
1711 std::make_pair(".previous.ub.", Context.getSizeType()),
1712 std::make_pair(StringRef(), QualType()) // __context with shared vars
1714 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1718 case OMPD_threadprivate:
1719 case OMPD_taskyield:
1722 case OMPD_cancellation_point:
1725 case OMPD_target_enter_data:
1726 case OMPD_target_exit_data:
1727 case OMPD_declare_reduction:
1728 case OMPD_declare_simd:
1729 case OMPD_declare_target:
1730 case OMPD_end_declare_target:
1731 case OMPD_target_update:
1732 llvm_unreachable("OpenMP Directive is not allowed");
1734 llvm_unreachable("Unknown OpenMP directive");
1738 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
1739 Expr *CaptureExpr, bool WithInit,
1740 bool AsExpression) {
1741 assert(CaptureExpr);
1742 ASTContext &C = S.getASTContext();
1743 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
1744 QualType Ty = Init->getType();
1745 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1746 if (S.getLangOpts().CPlusPlus)
1747 Ty = C.getLValueReferenceType(Ty);
1749 Ty = C.getPointerType(Ty);
1751 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1752 if (!Res.isUsable())
1758 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1759 CaptureExpr->getLocStart());
1761 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
1762 S.CurContext->addHiddenDecl(CED);
1763 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false,
1764 /*TypeMayContainAuto=*/true);
1768 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1770 OMPCapturedExprDecl *CD;
1771 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1772 CD = cast<OMPCapturedExprDecl>(VD);
1774 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1775 /*AsExpression=*/false);
1776 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1777 CaptureExpr->getExprLoc());
1780 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1783 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1784 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1785 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1786 CaptureExpr->getExprLoc());
1788 ExprResult Res = Ref;
1789 if (!S.getLangOpts().CPlusPlus &&
1790 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1791 Ref->getType()->isPointerType())
1792 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1793 if (!Res.isUsable())
1795 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
1798 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1799 ArrayRef<OMPClause *> Clauses) {
1800 if (!S.isUsable()) {
1801 ActOnCapturedRegionError();
1805 OMPOrderedClause *OC = nullptr;
1806 OMPScheduleClause *SC = nullptr;
1807 SmallVector<OMPLinearClause *, 4> LCs;
1808 // This is required for proper codegen.
1809 for (auto *Clause : Clauses) {
1810 if (isOpenMPPrivate(Clause->getClauseKind()) ||
1811 Clause->getClauseKind() == OMPC_copyprivate ||
1812 (getLangOpts().OpenMPUseTLS &&
1813 getASTContext().getTargetInfo().isTLSSupported() &&
1814 Clause->getClauseKind() == OMPC_copyin)) {
1815 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
1816 // Mark all variables in private list clauses as used in inner region.
1817 for (auto *VarRef : Clause->children()) {
1818 if (auto *E = cast_or_null<Expr>(VarRef)) {
1819 MarkDeclarationsReferencedInExpr(E);
1822 DSAStack->setForceVarCapturing(/*V=*/false);
1823 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
1824 // Mark all variables in private list clauses as used in inner region.
1825 // Required for proper codegen of combined directives.
1826 // TODO: add processing for other clauses.
1827 if (auto *C = OMPClauseWithPreInit::get(Clause)) {
1828 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1829 for (auto *D : DS->decls())
1830 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1833 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1834 if (auto *E = C->getPostUpdateExpr())
1835 MarkDeclarationsReferencedInExpr(E);
1838 if (Clause->getClauseKind() == OMPC_schedule)
1839 SC = cast<OMPScheduleClause>(Clause);
1840 else if (Clause->getClauseKind() == OMPC_ordered)
1841 OC = cast<OMPOrderedClause>(Clause);
1842 else if (Clause->getClauseKind() == OMPC_linear)
1843 LCs.push_back(cast<OMPLinearClause>(Clause));
1845 bool ErrorFound = false;
1846 // OpenMP, 2.7.1 Loop Construct, Restrictions
1847 // The nonmonotonic modifier cannot be specified if an ordered clause is
1850 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1851 SC->getSecondScheduleModifier() ==
1852 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1854 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1855 ? SC->getFirstScheduleModifierLoc()
1856 : SC->getSecondScheduleModifierLoc(),
1857 diag::err_omp_schedule_nonmonotonic_ordered)
1858 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1861 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1862 for (auto *C : LCs) {
1863 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1864 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1868 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1869 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1870 OC->getNumForLoops()) {
1871 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1872 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1876 ActOnCapturedRegionError();
1879 return ActOnCapturedRegionEnd(S.get());
1882 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1883 OpenMPDirectiveKind CurrentRegion,
1884 const DeclarationNameInfo &CurrentName,
1885 OpenMPDirectiveKind CancelRegion,
1886 SourceLocation StartLoc) {
1887 if (Stack->getCurScope()) {
1888 auto ParentRegion = Stack->getParentDirective();
1889 auto OffendingRegion = ParentRegion;
1890 bool NestingProhibited = false;
1891 bool CloseNesting = true;
1892 bool OrphanSeen = false;
1895 ShouldBeInParallelRegion,
1896 ShouldBeInOrderedRegion,
1897 ShouldBeInTargetRegion,
1898 ShouldBeInTeamsRegion
1899 } Recommend = NoRecommend;
1900 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
1901 // OpenMP [2.16, Nesting of Regions]
1902 // OpenMP constructs may not be nested inside a simd region.
1903 // OpenMP [2.8.1,simd Construct, Restrictions]
1904 // An ordered construct with the simd clause is the only OpenMP
1905 // construct that can appear in the simd region.
1906 // Allowing a SIMD construct nested in another SIMD construct is an
1907 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
1909 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
1910 ? diag::err_omp_prohibited_region_simd
1911 : diag::warn_omp_nesting_simd);
1912 return CurrentRegion != OMPD_simd;
1914 if (ParentRegion == OMPD_atomic) {
1915 // OpenMP [2.16, Nesting of Regions]
1916 // OpenMP constructs may not be nested inside an atomic region.
1917 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1920 if (CurrentRegion == OMPD_section) {
1921 // OpenMP [2.7.2, sections Construct, Restrictions]
1922 // Orphaned section directives are prohibited. That is, the section
1923 // directives must appear within the sections construct and must not be
1924 // encountered elsewhere in the sections region.
1925 if (ParentRegion != OMPD_sections &&
1926 ParentRegion != OMPD_parallel_sections) {
1927 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1928 << (ParentRegion != OMPD_unknown)
1929 << getOpenMPDirectiveName(ParentRegion);
1934 // Allow some constructs (except teams) to be orphaned (they could be
1935 // used in functions, called from OpenMP regions with the required
1937 if (ParentRegion == OMPD_unknown &&
1938 !isOpenMPNestingTeamsDirective(CurrentRegion))
1940 if (CurrentRegion == OMPD_cancellation_point ||
1941 CurrentRegion == OMPD_cancel) {
1942 // OpenMP [2.16, Nesting of Regions]
1943 // A cancellation point construct for which construct-type-clause is
1944 // taskgroup must be nested inside a task construct. A cancellation
1945 // point construct for which construct-type-clause is not taskgroup must
1946 // be closely nested inside an OpenMP construct that matches the type
1947 // specified in construct-type-clause.
1948 // A cancel construct for which construct-type-clause is taskgroup must be
1949 // nested inside a task construct. A cancel construct for which
1950 // construct-type-clause is not taskgroup must be closely nested inside an
1951 // OpenMP construct that matches the type specified in
1952 // construct-type-clause.
1954 !((CancelRegion == OMPD_parallel &&
1955 (ParentRegion == OMPD_parallel ||
1956 ParentRegion == OMPD_target_parallel)) ||
1957 (CancelRegion == OMPD_for &&
1958 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
1959 ParentRegion == OMPD_target_parallel_for)) ||
1960 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
1961 (CancelRegion == OMPD_sections &&
1962 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
1963 ParentRegion == OMPD_parallel_sections)));
1964 } else if (CurrentRegion == OMPD_master) {
1965 // OpenMP [2.16, Nesting of Regions]
1966 // A master region may not be closely nested inside a worksharing,
1967 // atomic, or explicit task region.
1968 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1969 isOpenMPTaskingDirective(ParentRegion);
1970 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1971 // OpenMP [2.16, Nesting of Regions]
1972 // A critical region may not be nested (closely or otherwise) inside a
1973 // critical region with the same name. Note that this restriction is not
1974 // sufficient to prevent deadlock.
1975 SourceLocation PreviousCriticalLoc;
1976 bool DeadLock = Stack->hasDirective(
1977 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
1978 const DeclarationNameInfo &DNI,
1979 SourceLocation Loc) -> bool {
1980 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
1981 PreviousCriticalLoc = Loc;
1986 false /* skip top directive */);
1988 SemaRef.Diag(StartLoc,
1989 diag::err_omp_prohibited_region_critical_same_name)
1990 << CurrentName.getName();
1991 if (PreviousCriticalLoc.isValid())
1992 SemaRef.Diag(PreviousCriticalLoc,
1993 diag::note_omp_previous_critical_region);
1996 } else if (CurrentRegion == OMPD_barrier) {
1997 // OpenMP [2.16, Nesting of Regions]
1998 // A barrier region may not be closely nested inside a worksharing,
1999 // explicit task, critical, ordered, atomic, or master region.
2000 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2001 isOpenMPTaskingDirective(ParentRegion) ||
2002 ParentRegion == OMPD_master ||
2003 ParentRegion == OMPD_critical ||
2004 ParentRegion == OMPD_ordered;
2005 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
2006 !isOpenMPParallelDirective(CurrentRegion) &&
2007 !isOpenMPTeamsDirective(CurrentRegion)) {
2008 // OpenMP [2.16, Nesting of Regions]
2009 // A worksharing region may not be closely nested inside a worksharing,
2010 // explicit task, critical, ordered, atomic, or master region.
2011 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2012 isOpenMPTaskingDirective(ParentRegion) ||
2013 ParentRegion == OMPD_master ||
2014 ParentRegion == OMPD_critical ||
2015 ParentRegion == OMPD_ordered;
2016 Recommend = ShouldBeInParallelRegion;
2017 } else if (CurrentRegion == OMPD_ordered) {
2018 // OpenMP [2.16, Nesting of Regions]
2019 // An ordered region may not be closely nested inside a critical,
2020 // atomic, or explicit task region.
2021 // An ordered region must be closely nested inside a loop region (or
2022 // parallel loop region) with an ordered clause.
2023 // OpenMP [2.8.1,simd Construct, Restrictions]
2024 // An ordered construct with the simd clause is the only OpenMP construct
2025 // that can appear in the simd region.
2026 NestingProhibited = ParentRegion == OMPD_critical ||
2027 isOpenMPTaskingDirective(ParentRegion) ||
2028 !(isOpenMPSimdDirective(ParentRegion) ||
2029 Stack->isParentOrderedRegion());
2030 Recommend = ShouldBeInOrderedRegion;
2031 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
2032 // OpenMP [2.16, Nesting of Regions]
2033 // If specified, a teams construct must be contained within a target
2035 NestingProhibited = ParentRegion != OMPD_target;
2036 OrphanSeen = ParentRegion == OMPD_unknown;
2037 Recommend = ShouldBeInTargetRegion;
2038 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2040 if (!NestingProhibited &&
2041 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2042 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2043 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
2044 // OpenMP [2.16, Nesting of Regions]
2045 // distribute, parallel, parallel sections, parallel workshare, and the
2046 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2047 // constructs that can be closely nested in the teams region.
2048 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2049 !isOpenMPDistributeDirective(CurrentRegion);
2050 Recommend = ShouldBeInParallelRegion;
2052 if (!NestingProhibited &&
2053 isOpenMPNestingDistributeDirective(CurrentRegion)) {
2054 // OpenMP 4.5 [2.17 Nesting of Regions]
2055 // The region associated with the distribute construct must be strictly
2056 // nested inside a teams region
2058 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
2059 Recommend = ShouldBeInTeamsRegion;
2061 if (!NestingProhibited &&
2062 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2063 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2064 // OpenMP 4.5 [2.17 Nesting of Regions]
2065 // If a target, target update, target data, target enter data, or
2066 // target exit data construct is encountered during execution of a
2067 // target region, the behavior is unspecified.
2068 NestingProhibited = Stack->hasDirective(
2069 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2070 SourceLocation) -> bool {
2071 if (isOpenMPTargetExecutionDirective(K)) {
2072 OffendingRegion = K;
2077 false /* don't skip top directive */);
2078 CloseNesting = false;
2080 if (NestingProhibited) {
2082 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2083 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2085 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2086 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2087 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2095 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2096 ArrayRef<OMPClause *> Clauses,
2097 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2098 bool ErrorFound = false;
2099 unsigned NamedModifiersNumber = 0;
2100 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2102 SmallVector<SourceLocation, 4> NameModifierLoc;
2103 for (const auto *C : Clauses) {
2104 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2105 // At most one if clause without a directive-name-modifier can appear on
2107 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2108 if (FoundNameModifiers[CurNM]) {
2109 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2110 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2111 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2113 } else if (CurNM != OMPD_unknown) {
2114 NameModifierLoc.push_back(IC->getNameModifierLoc());
2115 ++NamedModifiersNumber;
2117 FoundNameModifiers[CurNM] = IC;
2118 if (CurNM == OMPD_unknown)
2120 // Check if the specified name modifier is allowed for the current
2122 // At most one if clause with the particular directive-name-modifier can
2123 // appear on the directive.
2124 bool MatchFound = false;
2125 for (auto NM : AllowedNameModifiers) {
2132 S.Diag(IC->getNameModifierLoc(),
2133 diag::err_omp_wrong_if_directive_name_modifier)
2134 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2139 // If any if clause on the directive includes a directive-name-modifier then
2140 // all if clauses on the directive must include a directive-name-modifier.
2141 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2142 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2143 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2144 diag::err_omp_no_more_if_clause);
2147 std::string Sep(", ");
2148 unsigned AllowedCnt = 0;
2149 unsigned TotalAllowedNum =
2150 AllowedNameModifiers.size() - NamedModifiersNumber;
2151 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2153 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2154 if (!FoundNameModifiers[NM]) {
2156 Values += getOpenMPDirectiveName(NM);
2158 if (AllowedCnt + 2 == TotalAllowedNum)
2160 else if (AllowedCnt + 1 != TotalAllowedNum)
2165 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2166 diag::err_omp_unnamed_if_clause)
2167 << (TotalAllowedNum > 1) << Values;
2169 for (auto Loc : NameModifierLoc) {
2170 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2177 StmtResult Sema::ActOnOpenMPExecutableDirective(
2178 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2179 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2180 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
2181 StmtResult Res = StmtError();
2182 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2186 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
2187 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
2188 bool ErrorFound = false;
2189 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
2191 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2193 // Check default data sharing attributes for referenced variables.
2194 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2195 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2196 if (DSAChecker.isErrorFound())
2198 // Generate list of implicitly defined firstprivate variables.
2199 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
2201 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2202 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2203 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2204 SourceLocation(), SourceLocation())) {
2205 ClausesWithImplicit.push_back(Implicit);
2206 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2207 DSAChecker.getImplicitFirstprivate().size();
2213 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
2216 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2218 AllowedNameModifiers.push_back(OMPD_parallel);
2221 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2222 VarsWithInheritedDSA);
2225 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2226 VarsWithInheritedDSA);
2229 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2230 EndLoc, VarsWithInheritedDSA);
2233 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2237 assert(ClausesWithImplicit.empty() &&
2238 "No clauses are allowed for 'omp section' directive");
2239 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2242 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2246 assert(ClausesWithImplicit.empty() &&
2247 "No clauses are allowed for 'omp master' directive");
2248 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2251 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2254 case OMPD_parallel_for:
2255 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2256 EndLoc, VarsWithInheritedDSA);
2257 AllowedNameModifiers.push_back(OMPD_parallel);
2259 case OMPD_parallel_for_simd:
2260 Res = ActOnOpenMPParallelForSimdDirective(
2261 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2262 AllowedNameModifiers.push_back(OMPD_parallel);
2264 case OMPD_parallel_sections:
2265 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2267 AllowedNameModifiers.push_back(OMPD_parallel);
2271 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2272 AllowedNameModifiers.push_back(OMPD_task);
2274 case OMPD_taskyield:
2275 assert(ClausesWithImplicit.empty() &&
2276 "No clauses are allowed for 'omp taskyield' directive");
2277 assert(AStmt == nullptr &&
2278 "No associated statement allowed for 'omp taskyield' directive");
2279 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2282 assert(ClausesWithImplicit.empty() &&
2283 "No clauses are allowed for 'omp barrier' directive");
2284 assert(AStmt == nullptr &&
2285 "No associated statement allowed for 'omp barrier' directive");
2286 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2289 assert(ClausesWithImplicit.empty() &&
2290 "No clauses are allowed for 'omp taskwait' directive");
2291 assert(AStmt == nullptr &&
2292 "No associated statement allowed for 'omp taskwait' directive");
2293 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2295 case OMPD_taskgroup:
2296 assert(ClausesWithImplicit.empty() &&
2297 "No clauses are allowed for 'omp taskgroup' directive");
2298 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2301 assert(AStmt == nullptr &&
2302 "No associated statement allowed for 'omp flush' directive");
2303 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2306 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2310 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2315 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2318 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2320 AllowedNameModifiers.push_back(OMPD_target);
2322 case OMPD_target_parallel:
2323 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2325 AllowedNameModifiers.push_back(OMPD_target);
2326 AllowedNameModifiers.push_back(OMPD_parallel);
2328 case OMPD_target_parallel_for:
2329 Res = ActOnOpenMPTargetParallelForDirective(
2330 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2331 AllowedNameModifiers.push_back(OMPD_target);
2332 AllowedNameModifiers.push_back(OMPD_parallel);
2334 case OMPD_cancellation_point:
2335 assert(ClausesWithImplicit.empty() &&
2336 "No clauses are allowed for 'omp cancellation point' directive");
2337 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2338 "cancellation point' directive");
2339 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2342 assert(AStmt == nullptr &&
2343 "No associated statement allowed for 'omp cancel' directive");
2344 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2346 AllowedNameModifiers.push_back(OMPD_cancel);
2348 case OMPD_target_data:
2349 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2351 AllowedNameModifiers.push_back(OMPD_target_data);
2353 case OMPD_target_enter_data:
2354 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2356 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2358 case OMPD_target_exit_data:
2359 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2361 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2364 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2365 EndLoc, VarsWithInheritedDSA);
2366 AllowedNameModifiers.push_back(OMPD_taskloop);
2368 case OMPD_taskloop_simd:
2369 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2370 EndLoc, VarsWithInheritedDSA);
2371 AllowedNameModifiers.push_back(OMPD_taskloop);
2373 case OMPD_distribute:
2374 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2375 EndLoc, VarsWithInheritedDSA);
2377 case OMPD_target_update:
2378 assert(!AStmt && "Statement is not allowed for target update");
2380 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2381 AllowedNameModifiers.push_back(OMPD_target_update);
2383 case OMPD_distribute_parallel_for:
2384 Res = ActOnOpenMPDistributeParallelForDirective(
2385 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2386 AllowedNameModifiers.push_back(OMPD_parallel);
2388 case OMPD_distribute_parallel_for_simd:
2389 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2390 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2391 AllowedNameModifiers.push_back(OMPD_parallel);
2393 case OMPD_distribute_simd:
2394 Res = ActOnOpenMPDistributeSimdDirective(
2395 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2397 case OMPD_target_parallel_for_simd:
2398 Res = ActOnOpenMPTargetParallelForSimdDirective(
2399 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2400 AllowedNameModifiers.push_back(OMPD_target);
2401 AllowedNameModifiers.push_back(OMPD_parallel);
2403 case OMPD_target_simd:
2404 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2405 EndLoc, VarsWithInheritedDSA);
2406 AllowedNameModifiers.push_back(OMPD_target);
2408 case OMPD_teams_distribute:
2409 Res = ActOnOpenMPTeamsDistributeDirective(
2410 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2412 case OMPD_teams_distribute_simd:
2413 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2414 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2416 case OMPD_teams_distribute_parallel_for_simd:
2417 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2418 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2419 AllowedNameModifiers.push_back(OMPD_parallel);
2421 case OMPD_teams_distribute_parallel_for:
2422 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2423 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2424 AllowedNameModifiers.push_back(OMPD_parallel);
2426 case OMPD_target_teams:
2427 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2429 AllowedNameModifiers.push_back(OMPD_target);
2431 case OMPD_target_teams_distribute:
2432 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2433 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2434 AllowedNameModifiers.push_back(OMPD_target);
2436 case OMPD_target_teams_distribute_parallel_for:
2437 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2438 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2439 AllowedNameModifiers.push_back(OMPD_target);
2440 AllowedNameModifiers.push_back(OMPD_parallel);
2442 case OMPD_declare_target:
2443 case OMPD_end_declare_target:
2444 case OMPD_threadprivate:
2445 case OMPD_declare_reduction:
2446 case OMPD_declare_simd:
2447 llvm_unreachable("OpenMP Directive is not allowed");
2449 llvm_unreachable("Unknown OpenMP directive");
2452 for (auto P : VarsWithInheritedDSA) {
2453 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2454 << P.first << P.second->getSourceRange();
2456 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2458 if (!AllowedNameModifiers.empty())
2459 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2467 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2468 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
2469 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
2470 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2471 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
2472 assert(Aligneds.size() == Alignments.size());
2473 assert(Linears.size() == LinModifiers.size());
2474 assert(Linears.size() == Steps.size());
2475 if (!DG || DG.get().isNull())
2476 return DeclGroupPtrTy();
2478 if (!DG.get().isSingleDecl()) {
2479 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
2482 auto *ADecl = DG.get().getSingleDecl();
2483 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2484 ADecl = FTD->getTemplatedDecl();
2486 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2488 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
2489 return DeclGroupPtrTy();
2492 // OpenMP [2.8.2, declare simd construct, Description]
2493 // The parameter of the simdlen clause must be a constant positive integer
2497 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
2498 // OpenMP [2.8.2, declare simd construct, Description]
2499 // The special this pointer can be used as if was one of the arguments to the
2500 // function in any of the linear, aligned, or uniform clauses.
2501 // The uniform clause declares one or more arguments to have an invariant
2502 // value for all concurrent invocations of the function in the execution of a
2503 // single SIMD loop.
2504 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2505 Expr *UniformedLinearThis = nullptr;
2506 for (auto *E : Uniforms) {
2507 E = E->IgnoreParenImpCasts();
2508 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2509 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2510 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2511 FD->getParamDecl(PVD->getFunctionScopeIndex())
2512 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2513 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
2516 if (isa<CXXThisExpr>(E)) {
2517 UniformedLinearThis = E;
2520 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2521 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2523 // OpenMP [2.8.2, declare simd construct, Description]
2524 // The aligned clause declares that the object to which each list item points
2525 // is aligned to the number of bytes expressed in the optional parameter of
2526 // the aligned clause.
2527 // The special this pointer can be used as if was one of the arguments to the
2528 // function in any of the linear, aligned, or uniform clauses.
2529 // The type of list items appearing in the aligned clause must be array,
2530 // pointer, reference to array, or reference to pointer.
2531 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2532 Expr *AlignedThis = nullptr;
2533 for (auto *E : Aligneds) {
2534 E = E->IgnoreParenImpCasts();
2535 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2536 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2537 auto *CanonPVD = PVD->getCanonicalDecl();
2538 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2539 FD->getParamDecl(PVD->getFunctionScopeIndex())
2540 ->getCanonicalDecl() == CanonPVD) {
2541 // OpenMP [2.8.1, simd construct, Restrictions]
2542 // A list-item cannot appear in more than one aligned clause.
2543 if (AlignedArgs.count(CanonPVD) > 0) {
2544 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2545 << 1 << E->getSourceRange();
2546 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2547 diag::note_omp_explicit_dsa)
2548 << getOpenMPClauseName(OMPC_aligned);
2551 AlignedArgs[CanonPVD] = E;
2552 QualType QTy = PVD->getType()
2553 .getNonReferenceType()
2554 .getUnqualifiedType()
2555 .getCanonicalType();
2556 const Type *Ty = QTy.getTypePtrOrNull();
2557 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2558 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2559 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2560 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2565 if (isa<CXXThisExpr>(E)) {
2567 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2568 << 2 << E->getSourceRange();
2569 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2570 << getOpenMPClauseName(OMPC_aligned);
2575 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2576 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2578 // The optional parameter of the aligned clause, alignment, must be a constant
2579 // positive integer expression. If no optional parameter is specified,
2580 // implementation-defined default alignments for SIMD instructions on the
2581 // target platforms are assumed.
2582 SmallVector<Expr *, 4> NewAligns;
2583 for (auto *E : Alignments) {
2586 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2587 NewAligns.push_back(Align.get());
2589 // OpenMP [2.8.2, declare simd construct, Description]
2590 // The linear clause declares one or more list items to be private to a SIMD
2591 // lane and to have a linear relationship with respect to the iteration space
2593 // The special this pointer can be used as if was one of the arguments to the
2594 // function in any of the linear, aligned, or uniform clauses.
2595 // When a linear-step expression is specified in a linear clause it must be
2596 // either a constant integer expression or an integer-typed parameter that is
2597 // specified in a uniform clause on the directive.
2598 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2599 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2600 auto MI = LinModifiers.begin();
2601 for (auto *E : Linears) {
2602 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2604 E = E->IgnoreParenImpCasts();
2605 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2606 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2607 auto *CanonPVD = PVD->getCanonicalDecl();
2608 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2609 FD->getParamDecl(PVD->getFunctionScopeIndex())
2610 ->getCanonicalDecl() == CanonPVD) {
2611 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2612 // A list-item cannot appear in more than one linear clause.
2613 if (LinearArgs.count(CanonPVD) > 0) {
2614 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2615 << getOpenMPClauseName(OMPC_linear)
2616 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2617 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2618 diag::note_omp_explicit_dsa)
2619 << getOpenMPClauseName(OMPC_linear);
2622 // Each argument can appear in at most one uniform or linear clause.
2623 if (UniformedArgs.count(CanonPVD) > 0) {
2624 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2625 << getOpenMPClauseName(OMPC_linear)
2626 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2627 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2628 diag::note_omp_explicit_dsa)
2629 << getOpenMPClauseName(OMPC_uniform);
2632 LinearArgs[CanonPVD] = E;
2633 if (E->isValueDependent() || E->isTypeDependent() ||
2634 E->isInstantiationDependent() ||
2635 E->containsUnexpandedParameterPack())
2637 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2638 PVD->getOriginalType());
2642 if (isa<CXXThisExpr>(E)) {
2643 if (UniformedLinearThis) {
2644 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2645 << getOpenMPClauseName(OMPC_linear)
2646 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2647 << E->getSourceRange();
2648 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2649 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2653 UniformedLinearThis = E;
2654 if (E->isValueDependent() || E->isTypeDependent() ||
2655 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2657 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2661 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2662 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2664 Expr *Step = nullptr;
2665 Expr *NewStep = nullptr;
2666 SmallVector<Expr *, 4> NewSteps;
2667 for (auto *E : Steps) {
2668 // Skip the same step expression, it was checked already.
2669 if (Step == E || !E) {
2670 NewSteps.push_back(E ? NewStep : nullptr);
2674 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2675 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2676 auto *CanonPVD = PVD->getCanonicalDecl();
2677 if (UniformedArgs.count(CanonPVD) == 0) {
2678 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2679 << Step->getSourceRange();
2680 } else if (E->isValueDependent() || E->isTypeDependent() ||
2681 E->isInstantiationDependent() ||
2682 E->containsUnexpandedParameterPack() ||
2683 CanonPVD->getType()->hasIntegerRepresentation())
2684 NewSteps.push_back(Step);
2686 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2687 << Step->getSourceRange();
2692 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2693 !Step->isInstantiationDependent() &&
2694 !Step->containsUnexpandedParameterPack()) {
2695 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2698 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2700 NewSteps.push_back(NewStep);
2702 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2703 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
2704 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
2705 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2706 const_cast<Expr **>(Linears.data()), Linears.size(),
2707 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2708 NewSteps.data(), NewSteps.size(), SR);
2709 ADecl->addAttr(NewAttr);
2710 return ConvertDeclToDeclGroup(ADecl);
2713 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2715 SourceLocation StartLoc,
2716 SourceLocation EndLoc) {
2720 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2721 // 1.2.2 OpenMP Language Terminology
2722 // Structured block - An executable statement with a single entry at the
2723 // top and a single exit at the bottom.
2724 // The point of exit cannot be a branch out of the structured block.
2725 // longjmp() and throw() must not violate the entry/exit criteria.
2726 CS->getCapturedDecl()->setNothrow();
2728 getCurFunction()->setHasBranchProtectedScope();
2730 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2731 DSAStack->isCancelRegion());
2735 /// \brief Helper class for checking canonical form of the OpenMP loops and
2736 /// extracting iteration space of each loop in the loop nest, that will be used
2737 /// for IR generation.
2738 class OpenMPIterationSpaceChecker {
2739 /// \brief Reference to Sema.
2741 /// \brief A location for diagnostics (when there is no some better location).
2742 SourceLocation DefaultLoc;
2743 /// \brief A location for diagnostics (when increment is not compatible).
2744 SourceLocation ConditionLoc;
2745 /// \brief A source location for referring to loop init later.
2746 SourceRange InitSrcRange;
2747 /// \brief A source location for referring to condition later.
2748 SourceRange ConditionSrcRange;
2749 /// \brief A source location for referring to increment later.
2750 SourceRange IncrementSrcRange;
2751 /// \brief Loop variable.
2752 ValueDecl *LCDecl = nullptr;
2753 /// \brief Reference to loop variable.
2754 Expr *LCRef = nullptr;
2755 /// \brief Lower bound (initializer for the var).
2757 /// \brief Upper bound.
2759 /// \brief Loop step (increment).
2760 Expr *Step = nullptr;
2761 /// \brief This flag is true when condition is one of:
2766 bool TestIsLessOp = false;
2767 /// \brief This flag is true when condition is strict ( < or > ).
2768 bool TestIsStrictOp = false;
2769 /// \brief This flag is true when step is subtracted on each iteration.
2770 bool SubtractStep = false;
2773 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2774 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
2775 /// \brief Check init-expr for canonical loop form and save loop counter
2776 /// variable - #Var and its initialization value - #LB.
2777 bool CheckInit(Stmt *S, bool EmitDiags = true);
2778 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2779 /// for less/greater and for strict/non-strict comparison.
2780 bool CheckCond(Expr *S);
2781 /// \brief Check incr-expr for canonical loop form and return true if it
2782 /// does not conform, otherwise save loop step (#Step).
2783 bool CheckInc(Expr *S);
2784 /// \brief Return the loop counter variable.
2785 ValueDecl *GetLoopDecl() const { return LCDecl; }
2786 /// \brief Return the reference expression to loop counter variable.
2787 Expr *GetLoopDeclRefExpr() const { return LCRef; }
2788 /// \brief Source range of the loop init.
2789 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2790 /// \brief Source range of the loop condition.
2791 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2792 /// \brief Source range of the loop increment.
2793 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2794 /// \brief True if the step should be subtracted.
2795 bool ShouldSubtractStep() const { return SubtractStep; }
2796 /// \brief Build the expression to calculate the number of iterations.
2798 BuildNumIterations(Scope *S, const bool LimitedType,
2799 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
2800 /// \brief Build the precondition expression for the loops.
2801 Expr *BuildPreCond(Scope *S, Expr *Cond,
2802 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
2803 /// \brief Build reference expression to the counter be used for codegen.
2804 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2805 DSAStackTy &DSA) const;
2806 /// \brief Build reference expression to the private counter be used for
2808 Expr *BuildPrivateCounterVar() const;
2809 /// \brief Build initialization of the counter be used for codegen.
2810 Expr *BuildCounterInit() const;
2811 /// \brief Build step of the counter be used for codegen.
2812 Expr *BuildCounterStep() const;
2813 /// \brief Return true if any expression is dependent.
2814 bool Dependent() const;
2817 /// \brief Check the right-hand side of an assignment in the increment
2819 bool CheckIncRHS(Expr *RHS);
2820 /// \brief Helper to set loop counter variable and its initializer.
2821 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
2822 /// \brief Helper to set upper bound.
2823 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
2825 /// \brief Helper to set loop increment.
2826 bool SetStep(Expr *NewStep, bool Subtract);
2829 bool OpenMPIterationSpaceChecker::Dependent() const {
2831 assert(!LB && !UB && !Step);
2834 return LCDecl->getType()->isDependentType() ||
2835 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2836 (Step && Step->isValueDependent());
2839 static Expr *getExprAsWritten(Expr *E) {
2840 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2841 E = ExprTemp->getSubExpr();
2843 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2844 E = MTE->GetTemporaryExpr();
2846 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2847 E = Binder->getSubExpr();
2849 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2850 E = ICE->getSubExprAsWritten();
2851 return E->IgnoreParens();
2854 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2857 // State consistency checking to ensure correct usage.
2858 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
2859 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2860 if (!NewLCDecl || !NewLB)
2862 LCDecl = getCanonicalDecl(NewLCDecl);
2863 LCRef = NewLCRefExpr;
2864 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2865 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2866 if ((Ctor->isCopyOrMoveConstructor() ||
2867 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2868 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
2869 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
2874 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2875 SourceRange SR, SourceLocation SL) {
2876 // State consistency checking to ensure correct usage.
2877 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2878 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2882 TestIsLessOp = LessOp;
2883 TestIsStrictOp = StrictOp;
2884 ConditionSrcRange = SR;
2889 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2890 // State consistency checking to ensure correct usage.
2891 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
2894 if (!NewStep->isValueDependent()) {
2895 // Check that the step is integer expression.
2896 SourceLocation StepLoc = NewStep->getLocStart();
2898 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2899 if (Val.isInvalid())
2901 NewStep = Val.get();
2903 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2904 // If test-expr is of form var relational-op b and relational-op is < or
2905 // <= then incr-expr must cause var to increase on each iteration of the
2906 // loop. If test-expr is of form var relational-op b and relational-op is
2907 // > or >= then incr-expr must cause var to decrease on each iteration of
2909 // If test-expr is of form b relational-op var and relational-op is < or
2910 // <= then incr-expr must cause var to decrease on each iteration of the
2911 // loop. If test-expr is of form b relational-op var and relational-op is
2912 // > or >= then incr-expr must cause var to increase on each iteration of
2914 llvm::APSInt Result;
2915 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2916 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2918 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
2920 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
2921 bool IsConstZero = IsConstant && !Result.getBoolValue();
2922 if (UB && (IsConstZero ||
2923 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
2924 : (IsConstPos || (IsUnsigned && !Subtract))))) {
2925 SemaRef.Diag(NewStep->getExprLoc(),
2926 diag::err_omp_loop_incr_not_compatible)
2927 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
2928 SemaRef.Diag(ConditionLoc,
2929 diag::note_omp_loop_cond_requres_compatible_incr)
2930 << TestIsLessOp << ConditionSrcRange;
2933 if (TestIsLessOp == Subtract) {
2935 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
2937 Subtract = !Subtract;
2942 SubtractStep = Subtract;
2946 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
2947 // Check init-expr for canonical loop form and save loop counter
2948 // variable - #Var and its initialization value - #LB.
2949 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2951 // integer-type var = lb
2952 // random-access-iterator-type var = lb
2953 // pointer-type var = lb
2957 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2961 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
2962 if (!ExprTemp->cleanupsHaveSideEffects())
2963 S = ExprTemp->getSubExpr();
2965 InitSrcRange = S->getSourceRange();
2966 if (Expr *E = dyn_cast<Expr>(S))
2967 S = E->IgnoreParens();
2968 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
2969 if (BO->getOpcode() == BO_Assign) {
2970 auto *LHS = BO->getLHS()->IgnoreParens();
2971 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
2972 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
2973 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2974 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2975 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
2977 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
2978 if (ME->isArrow() &&
2979 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
2980 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2983 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
2984 if (DS->isSingleDecl()) {
2985 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2986 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
2987 // Accept non-canonical init form here but emit ext. warning.
2988 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
2989 SemaRef.Diag(S->getLocStart(),
2990 diag::ext_omp_loop_not_canonical_init)
2991 << S->getSourceRange();
2992 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
2996 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2997 if (CE->getOperator() == OO_Equal) {
2998 auto *LHS = CE->getArg(0);
2999 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3000 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3001 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3002 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3003 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3005 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3006 if (ME->isArrow() &&
3007 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3008 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3013 if (Dependent() || SemaRef.CurContext->isDependentContext())
3016 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3017 << S->getSourceRange();
3022 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
3023 /// variable (which may be the loop variable) if possible.
3024 static const ValueDecl *GetInitLCDecl(Expr *E) {
3027 E = getExprAsWritten(E);
3028 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3029 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3030 if ((Ctor->isCopyOrMoveConstructor() ||
3031 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3032 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3033 E = CE->getArg(0)->IgnoreParenImpCasts();
3034 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3035 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3036 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3037 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3038 return getCanonicalDecl(ME->getMemberDecl());
3039 return getCanonicalDecl(VD);
3042 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3043 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3044 return getCanonicalDecl(ME->getMemberDecl());
3048 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3049 // Check test-expr for canonical form, save upper-bound UB, flags for
3050 // less/greater and for strict/non-strict comparison.
3051 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3052 // var relational-op b
3053 // b relational-op var
3056 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
3059 S = getExprAsWritten(S);
3060 SourceLocation CondLoc = S->getLocStart();
3061 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3062 if (BO->isRelationalOp()) {
3063 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3064 return SetUB(BO->getRHS(),
3065 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3066 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3067 BO->getSourceRange(), BO->getOperatorLoc());
3068 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
3069 return SetUB(BO->getLHS(),
3070 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3071 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3072 BO->getSourceRange(), BO->getOperatorLoc());
3074 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3075 if (CE->getNumArgs() == 2) {
3076 auto Op = CE->getOperator();
3079 case OO_GreaterEqual:
3082 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3083 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3084 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3085 CE->getOperatorLoc());
3086 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
3087 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3088 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3089 CE->getOperatorLoc());
3096 if (Dependent() || SemaRef.CurContext->isDependentContext())
3098 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
3099 << S->getSourceRange() << LCDecl;
3103 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3104 // RHS of canonical loop form increment can be:
3109 RHS = RHS->IgnoreParenImpCasts();
3110 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
3111 if (BO->isAdditiveOp()) {
3112 bool IsAdd = BO->getOpcode() == BO_Add;
3113 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3114 return SetStep(BO->getRHS(), !IsAdd);
3115 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
3116 return SetStep(BO->getLHS(), false);
3118 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
3119 bool IsAdd = CE->getOperator() == OO_Plus;
3120 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
3121 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3122 return SetStep(CE->getArg(1), !IsAdd);
3123 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
3124 return SetStep(CE->getArg(0), false);
3127 if (Dependent() || SemaRef.CurContext->isDependentContext())
3129 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3130 << RHS->getSourceRange() << LCDecl;
3134 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3135 // Check incr-expr for canonical loop form and return true if it
3136 // does not conform.
3137 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3149 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
3152 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3153 if (!ExprTemp->cleanupsHaveSideEffects())
3154 S = ExprTemp->getSubExpr();
3156 IncrementSrcRange = S->getSourceRange();
3157 S = S->IgnoreParens();
3158 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
3159 if (UO->isIncrementDecrementOp() &&
3160 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
3161 return SetStep(SemaRef
3162 .ActOnIntegerConstant(UO->getLocStart(),
3163 (UO->isDecrementOp() ? -1 : 1))
3166 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3167 switch (BO->getOpcode()) {
3170 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3171 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3174 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3175 return CheckIncRHS(BO->getRHS());
3180 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3181 switch (CE->getOperator()) {
3184 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3185 return SetStep(SemaRef
3186 .ActOnIntegerConstant(
3188 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3194 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3195 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3198 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3199 return CheckIncRHS(CE->getArg(1));
3205 if (Dependent() || SemaRef.CurContext->isDependentContext())
3207 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3208 << S->getSourceRange() << LCDecl;
3213 tryBuildCapture(Sema &SemaRef, Expr *Capture,
3214 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3215 if (SemaRef.CurContext->isDependentContext())
3216 return ExprResult(Capture);
3217 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3218 return SemaRef.PerformImplicitConversion(
3219 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3220 /*AllowExplicit=*/true);
3221 auto I = Captures.find(Capture);
3222 if (I != Captures.end())
3223 return buildCapture(SemaRef, Capture, I->second);
3224 DeclRefExpr *Ref = nullptr;
3225 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3226 Captures[Capture] = Ref;
3230 /// \brief Build the expression to calculate the number of iterations.
3231 Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3232 Scope *S, const bool LimitedType,
3233 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3235 auto VarType = LCDecl->getType().getNonReferenceType();
3236 if (VarType->isIntegerType() || VarType->isPointerType() ||
3237 SemaRef.getLangOpts().CPlusPlus) {
3239 auto *UBExpr = TestIsLessOp ? UB : LB;
3240 auto *LBExpr = TestIsLessOp ? LB : UB;
3241 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3242 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
3243 if (!Upper || !Lower)
3246 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3248 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
3249 // BuildBinOp already emitted error, this one is to point user to upper
3250 // and lower bound, and to tell what is passed to 'operator-'.
3251 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3252 << Upper->getSourceRange() << Lower->getSourceRange();
3257 if (!Diff.isUsable())
3260 // Upper - Lower [- 1]
3262 Diff = SemaRef.BuildBinOp(
3263 S, DefaultLoc, BO_Sub, Diff.get(),
3264 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3265 if (!Diff.isUsable())
3268 // Upper - Lower [- 1] + Step
3269 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3270 if (!NewStep.isUsable())
3272 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
3273 if (!Diff.isUsable())
3276 // Parentheses (for dumping/debugging purposes only).
3277 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3278 if (!Diff.isUsable())
3281 // (Upper - Lower [- 1] + Step) / Step
3282 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
3283 if (!Diff.isUsable())
3286 // OpenMP runtime requires 32-bit or 64-bit loop variables.
3287 QualType Type = Diff.get()->getType();
3288 auto &C = SemaRef.Context;
3289 bool UseVarType = VarType->hasIntegerRepresentation() &&
3290 C.getTypeSize(Type) > C.getTypeSize(VarType);
3291 if (!Type->isIntegerType() || UseVarType) {
3293 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3294 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3295 : Type->hasSignedIntegerRepresentation();
3296 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
3297 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3298 Diff = SemaRef.PerformImplicitConversion(
3299 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3300 if (!Diff.isUsable())
3305 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3306 if (NewSize != C.getTypeSize(Type)) {
3307 if (NewSize < C.getTypeSize(Type)) {
3308 assert(NewSize == 64 && "incorrect loop var size");
3309 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3310 << InitSrcRange << ConditionSrcRange;
3312 QualType NewType = C.getIntTypeForBitwidth(
3313 NewSize, Type->hasSignedIntegerRepresentation() ||
3314 C.getTypeSize(Type) < NewSize);
3315 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3316 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3317 Sema::AA_Converting, true);
3318 if (!Diff.isUsable())
3327 Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3328 Scope *S, Expr *Cond,
3329 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3330 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3331 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3332 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3334 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3335 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3336 if (!NewLB.isUsable() || !NewUB.isUsable())
3339 auto CondExpr = SemaRef.BuildBinOp(
3340 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3341 : (TestIsStrictOp ? BO_GT : BO_GE),
3342 NewLB.get(), NewUB.get());
3343 if (CondExpr.isUsable()) {
3344 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3345 SemaRef.Context.BoolTy))
3346 CondExpr = SemaRef.PerformImplicitConversion(
3347 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3348 /*AllowExplicit=*/true);
3350 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3351 // Otherwise use original loop conditon and evaluate it in runtime.
3352 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3355 /// \brief Build reference expression to the counter be used for codegen.
3356 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
3357 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
3358 auto *VD = dyn_cast<VarDecl>(LCDecl);
3360 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3361 auto *Ref = buildDeclRefExpr(
3362 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
3363 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3364 // If the loop control decl is explicitly marked as private, do not mark it
3365 // as captured again.
3366 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3367 Captures.insert(std::make_pair(LCRef, Ref));
3370 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
3374 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
3375 if (LCDecl && !LCDecl->isInvalidDecl()) {
3376 auto Type = LCDecl->getType().getNonReferenceType();
3378 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3379 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
3380 if (PrivateVar->isInvalidDecl())
3382 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3387 /// \brief Build initialization of the counter to be used for codegen.
3388 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3390 /// \brief Build step of the counter be used for codegen.
3391 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3393 /// \brief Iteration space of a single for loop.
3394 struct LoopIterationSpace final {
3395 /// \brief Condition of the loop.
3396 Expr *PreCond = nullptr;
3397 /// \brief This expression calculates the number of iterations in the loop.
3398 /// It is always possible to calculate it before starting the loop.
3399 Expr *NumIterations = nullptr;
3400 /// \brief The loop counter variable.
3401 Expr *CounterVar = nullptr;
3402 /// \brief Private loop counter variable.
3403 Expr *PrivateCounterVar = nullptr;
3404 /// \brief This is initializer for the initial value of #CounterVar.
3405 Expr *CounterInit = nullptr;
3406 /// \brief This is step for the #CounterVar used to generate its update:
3407 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
3408 Expr *CounterStep = nullptr;
3409 /// \brief Should step be subtracted?
3410 bool Subtract = false;
3411 /// \brief Source range of the loop init.
3412 SourceRange InitSrcRange;
3413 /// \brief Source range of the loop condition.
3414 SourceRange CondSrcRange;
3415 /// \brief Source range of the loop increment.
3416 SourceRange IncSrcRange;
3421 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3422 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3423 assert(Init && "Expected loop in canonical form.");
3424 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3425 if (AssociatedLoops > 0 &&
3426 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3427 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
3428 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3429 if (auto *D = ISC.GetLoopDecl()) {
3430 auto *VD = dyn_cast<VarDecl>(D);
3432 if (auto *Private = IsOpenMPCapturedDecl(D))
3435 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3436 /*WithInit=*/false);
3437 VD = cast<VarDecl>(Ref->getDecl());
3440 DSAStack->addLoopControlVariable(D, VD);
3443 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
3447 /// \brief Called on a for stmt to check and extract its iteration space
3448 /// for further processing (such as collapsing).
3449 static bool CheckOpenMPIterationSpace(
3450 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3451 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
3452 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
3453 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
3454 LoopIterationSpace &ResultIterSpace,
3455 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3456 // OpenMP [2.6, Canonical Loop Form]
3457 // for (init-expr; test-expr; incr-expr) structured-block
3458 auto *For = dyn_cast_or_null<ForStmt>(S);
3460 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
3461 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3462 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3463 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3464 if (NestedLoopCount > 1) {
3465 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3466 SemaRef.Diag(DSA.getConstructLoc(),
3467 diag::note_omp_collapse_ordered_expr)
3468 << 2 << CollapseLoopCountExpr->getSourceRange()
3469 << OrderedLoopCountExpr->getSourceRange();
3470 else if (CollapseLoopCountExpr)
3471 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3472 diag::note_omp_collapse_ordered_expr)
3473 << 0 << CollapseLoopCountExpr->getSourceRange();
3475 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3476 diag::note_omp_collapse_ordered_expr)
3477 << 1 << OrderedLoopCountExpr->getSourceRange();
3481 assert(For->getBody());
3483 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3486 auto Init = For->getInit();
3487 if (ISC.CheckInit(Init))
3490 bool HasErrors = false;
3492 // Check loop variable's type.
3493 if (auto *LCDecl = ISC.GetLoopDecl()) {
3494 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
3496 // OpenMP [2.6, Canonical Loop Form]
3497 // Var is one of the following:
3498 // A variable of signed or unsigned integer type.
3499 // For C++, a variable of a random access iterator type.
3500 // For C, a variable of a pointer type.
3501 auto VarType = LCDecl->getType().getNonReferenceType();
3502 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3503 !VarType->isPointerType() &&
3504 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3505 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3506 << SemaRef.getLangOpts().CPlusPlus;
3510 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3512 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3513 // parallel for construct is (are) private.
3514 // The loop iteration variable in the associated for-loop of a simd
3515 // construct with just one associated for-loop is linear with a
3516 // constant-linear-step that is the increment of the associated for-loop.
3517 // Exclude loop var from the list of variables with implicitly defined data
3518 // sharing attributes.
3519 VarsWithImplicitDSA.erase(LCDecl);
3521 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3522 // in a Construct, C/C++].
3523 // The loop iteration variable in the associated for-loop of a simd
3524 // construct with just one associated for-loop may be listed in a linear
3525 // clause with a constant-linear-step that is the increment of the
3526 // associated for-loop.
3527 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3528 // parallel for construct may be listed in a private or lastprivate clause.
3529 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3530 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3531 // declared in the loop and it is predetermined as a private.
3532 auto PredeterminedCKind =
3533 isOpenMPSimdDirective(DKind)
3534 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3536 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3537 DVar.CKind != PredeterminedCKind) ||
3538 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3539 isOpenMPDistributeDirective(DKind)) &&
3540 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3541 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3542 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3543 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3544 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3545 << getOpenMPClauseName(PredeterminedCKind);
3546 if (DVar.RefExpr == nullptr)
3547 DVar.CKind = PredeterminedCKind;
3548 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3550 } else if (LoopDeclRefExpr != nullptr) {
3551 // Make the loop iteration variable private (for worksharing constructs),
3552 // linear (for simd directives with the only one associated loop) or
3553 // lastprivate (for simd directives with several collapsed or ordered
3555 if (DVar.CKind == OMPC_unknown)
3556 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3557 [](OpenMPDirectiveKind) -> bool { return true; },
3558 /*FromParent=*/false);
3559 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3562 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3565 HasErrors |= ISC.CheckCond(For->getCond());
3568 HasErrors |= ISC.CheckInc(For->getInc());
3571 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
3574 // Build the loop's iteration space representation.
3575 ResultIterSpace.PreCond =
3576 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
3577 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
3579 (isOpenMPWorksharingDirective(DKind) ||
3580 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3582 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
3583 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
3584 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3585 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3586 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3587 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3588 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3589 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3591 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3592 ResultIterSpace.NumIterations == nullptr ||
3593 ResultIterSpace.CounterVar == nullptr ||
3594 ResultIterSpace.PrivateCounterVar == nullptr ||
3595 ResultIterSpace.CounterInit == nullptr ||
3596 ResultIterSpace.CounterStep == nullptr);
3601 /// \brief Build 'VarRef = Start.
3603 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3605 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3606 // Build 'VarRef = Start.
3607 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3608 if (!NewStart.isUsable())
3610 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
3611 VarRef.get()->getType())) {
3612 NewStart = SemaRef.PerformImplicitConversion(
3613 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3614 /*AllowExplicit=*/true);
3615 if (!NewStart.isUsable())
3620 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3624 /// \brief Build 'VarRef = Start + Iter * Step'.
3626 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3627 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3628 ExprResult Step, bool Subtract,
3629 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
3630 // Add parentheses (for debugging purposes only).
3631 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3632 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3636 ExprResult NewStep = Step;
3638 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
3639 if (NewStep.isInvalid())
3642 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
3643 if (!Update.isUsable())
3646 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3647 // 'VarRef = Start (+|-) Iter * Step'.
3648 ExprResult NewStart = Start;
3650 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
3651 if (NewStart.isInvalid())
3654 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3655 ExprResult SavedUpdate = Update;
3656 ExprResult UpdateVal;
3657 if (VarRef.get()->getType()->isOverloadableType() ||
3658 NewStart.get()->getType()->isOverloadableType() ||
3659 Update.get()->getType()->isOverloadableType()) {
3660 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3661 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3663 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3664 if (Update.isUsable()) {
3666 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3667 VarRef.get(), SavedUpdate.get());
3668 if (UpdateVal.isUsable()) {
3669 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3673 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3676 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3677 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3678 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3679 NewStart.get(), SavedUpdate.get());
3680 if (!Update.isUsable())
3683 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3684 VarRef.get()->getType())) {
3685 Update = SemaRef.PerformImplicitConversion(
3686 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3687 if (!Update.isUsable())
3691 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3696 /// \brief Convert integer expression \a E to make it have at least \a Bits
3698 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
3701 auto &C = SemaRef.Context;
3702 QualType OldType = E->getType();
3703 unsigned HasBits = C.getTypeSize(OldType);
3704 if (HasBits >= Bits)
3705 return ExprResult(E);
3706 // OK to convert to signed, because new type has more bits than old.
3707 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3708 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3712 /// \brief Check if the given expression \a E is a constant integer that fits
3713 /// into \a Bits bits.
3714 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3717 llvm::APSInt Result;
3718 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3719 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3723 /// Build preinits statement for the given declarations.
3724 static Stmt *buildPreInits(ASTContext &Context,
3725 SmallVectorImpl<Decl *> &PreInits) {
3726 if (!PreInits.empty()) {
3727 return new (Context) DeclStmt(
3728 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3729 SourceLocation(), SourceLocation());
3734 /// Build preinits statement for the given declarations.
3735 static Stmt *buildPreInits(ASTContext &Context,
3736 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3737 if (!Captures.empty()) {
3738 SmallVector<Decl *, 16> PreInits;
3739 for (auto &Pair : Captures)
3740 PreInits.push_back(Pair.second->getDecl());
3741 return buildPreInits(Context, PreInits);
3746 /// Build postupdate expression for the given list of postupdates expressions.
3747 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3748 Expr *PostUpdate = nullptr;
3749 if (!PostUpdates.empty()) {
3750 for (auto *E : PostUpdates) {
3751 Expr *ConvE = S.BuildCStyleCastExpr(
3753 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3756 PostUpdate = PostUpdate
3757 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3766 /// \brief Called on a for stmt to check itself and nested loops (if any).
3767 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3768 /// number of collapsed loops otherwise.
3770 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3771 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3773 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
3774 OMPLoopDirective::HelperExprs &Built) {
3775 unsigned NestedLoopCount = 1;
3776 if (CollapseLoopCountExpr) {
3777 // Found 'collapse' clause - calculate collapse number.
3778 llvm::APSInt Result;
3779 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
3780 NestedLoopCount = Result.getLimitedValue();
3782 if (OrderedLoopCountExpr) {
3783 // Found 'ordered' clause - calculate collapse number.
3784 llvm::APSInt Result;
3785 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3786 if (Result.getLimitedValue() < NestedLoopCount) {
3787 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3788 diag::err_omp_wrong_ordered_loop_count)
3789 << OrderedLoopCountExpr->getSourceRange();
3790 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3791 diag::note_collapse_loop_count)
3792 << CollapseLoopCountExpr->getSourceRange();
3794 NestedLoopCount = Result.getLimitedValue();
3797 // This is helper routine for loop directives (e.g., 'for', 'simd',
3798 // 'for simd', etc.).
3799 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
3800 SmallVector<LoopIterationSpace, 4> IterSpaces;
3801 IterSpaces.resize(NestedLoopCount);
3802 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
3803 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
3804 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
3805 NestedLoopCount, CollapseLoopCountExpr,
3806 OrderedLoopCountExpr, VarsWithImplicitDSA,
3807 IterSpaces[Cnt], Captures))
3809 // Move on to the next nested for loop, or to the loop body.
3810 // OpenMP [2.8.1, simd construct, Restrictions]
3811 // All loops associated with the construct must be perfectly nested; that
3812 // is, there must be no intervening code nor any OpenMP directive between
3814 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
3817 Built.clear(/* size */ NestedLoopCount);
3819 if (SemaRef.CurContext->isDependentContext())
3820 return NestedLoopCount;
3822 // An example of what is generated for the following code:
3824 // #pragma omp simd collapse(2) ordered(2)
3825 // for (i = 0; i < NI; ++i)
3826 // for (k = 0; k < NK; ++k)
3827 // for (j = J0; j < NJ; j+=2) {
3831 // We generate the code below.
3832 // Note: the loop body may be outlined in CodeGen.
3833 // Note: some counters may be C++ classes, operator- is used to find number of
3834 // iterations and operator+= to calculate counter value.
3835 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3836 // or i64 is currently supported).
3838 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3839 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3840 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3841 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3842 // // similar updates for vars in clauses (e.g. 'linear')
3843 // <loop body (using local i and j)>
3845 // i = NI; // assign final values of counters
3849 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3850 // the iteration counts of the collapsed for loops.
3851 // Precondition tests if there is at least one iteration (all conditions are
3853 auto PreCond = ExprResult(IterSpaces[0].PreCond);
3854 auto N0 = IterSpaces[0].NumIterations;
3855 ExprResult LastIteration32 = WidenIterationCount(
3856 32 /* Bits */, SemaRef
3857 .PerformImplicitConversion(
3858 N0->IgnoreImpCasts(), N0->getType(),
3859 Sema::AA_Converting, /*AllowExplicit=*/true)
3862 ExprResult LastIteration64 = WidenIterationCount(
3863 64 /* Bits */, SemaRef
3864 .PerformImplicitConversion(
3865 N0->IgnoreImpCasts(), N0->getType(),
3866 Sema::AA_Converting, /*AllowExplicit=*/true)
3870 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3871 return NestedLoopCount;
3873 auto &C = SemaRef.Context;
3874 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3876 Scope *CurScope = DSA.getCurScope();
3877 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
3878 if (PreCond.isUsable()) {
3880 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
3881 PreCond.get(), IterSpaces[Cnt].PreCond);
3883 auto N = IterSpaces[Cnt].NumIterations;
3884 SourceLocation Loc = N->getExprLoc();
3885 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3886 if (LastIteration32.isUsable())
3887 LastIteration32 = SemaRef.BuildBinOp(
3888 CurScope, Loc, BO_Mul, LastIteration32.get(),
3890 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3891 Sema::AA_Converting,
3892 /*AllowExplicit=*/true)
3894 if (LastIteration64.isUsable())
3895 LastIteration64 = SemaRef.BuildBinOp(
3896 CurScope, Loc, BO_Mul, LastIteration64.get(),
3898 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3899 Sema::AA_Converting,
3900 /*AllowExplicit=*/true)
3904 // Choose either the 32-bit or 64-bit version.
3905 ExprResult LastIteration = LastIteration64;
3906 if (LastIteration32.isUsable() &&
3907 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3908 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3911 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3912 LastIteration64.get(), SemaRef)))
3913 LastIteration = LastIteration32;
3914 QualType VType = LastIteration.get()->getType();
3915 QualType RealVType = VType;
3916 QualType StrideVType = VType;
3917 if (isOpenMPTaskLoopDirective(DKind)) {
3919 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3921 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3924 if (!LastIteration.isUsable())
3927 // Save the number of iterations.
3928 ExprResult NumIterations = LastIteration;
3930 LastIteration = SemaRef.BuildBinOp(
3931 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
3932 LastIteration.get(),
3933 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3934 if (!LastIteration.isUsable())
3938 // Calculate the last iteration number beforehand instead of doing this on
3939 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3940 llvm::APSInt Result;
3942 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3943 ExprResult CalcLastIteration;
3945 ExprResult SaveRef =
3946 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
3947 LastIteration = SaveRef;
3949 // Prepare SaveRef + 1.
3950 NumIterations = SemaRef.BuildBinOp(
3951 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
3952 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3953 if (!NumIterations.isUsable())
3957 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3959 // Build variables passed into runtime, necessary for worksharing directives.
3960 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
3961 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
3962 isOpenMPDistributeDirective(DKind)) {
3963 // Lower bound variable, initialized with zero.
3964 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3965 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
3966 SemaRef.AddInitializerToDecl(
3967 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3968 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3970 // Upper bound variable, initialized with last iteration number.
3971 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3972 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
3973 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3974 /*DirectInit*/ false,
3975 /*TypeMayContainAuto*/ false);
3977 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3978 // This will be used to implement clause 'lastprivate'.
3979 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
3980 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3981 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
3982 SemaRef.AddInitializerToDecl(
3983 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3984 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3986 // Stride variable returned by runtime (we initialize it to 1 by default).
3988 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
3989 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
3990 SemaRef.AddInitializerToDecl(
3991 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3992 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3994 // Build expression: UB = min(UB, LastIteration)
3995 // It is necessary for CodeGen of directives with static scheduling.
3996 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3997 UB.get(), LastIteration.get());
3998 ExprResult CondOp = SemaRef.ActOnConditionalOp(
3999 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4000 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4002 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
4004 // If we have a combined directive that combines 'distribute', 'for' or
4005 // 'simd' we need to be able to access the bounds of the schedule of the
4006 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4007 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4008 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4009 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4011 // We expect to have at least 2 more parameters than the 'parallel'
4012 // directive does - the lower and upper bounds of the previous schedule.
4013 assert(CD->getNumParams() >= 4 &&
4014 "Unexpected number of parameters in loop combined directive");
4016 // Set the proper type for the bounds given what we learned from the
4018 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4019 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4021 // Previous lower and upper bounds are obtained from the region
4024 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4026 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4030 // Build the iteration variable and its initialization before loop.
4034 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4035 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
4037 (isOpenMPWorksharingDirective(DKind) ||
4038 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4040 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4041 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4042 Init = SemaRef.ActOnFinishFullExpr(Init.get());
4045 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
4046 SourceLocation CondLoc;
4048 (isOpenMPWorksharingDirective(DKind) ||
4049 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4050 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4051 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4052 NumIterations.get());
4054 // Loop increment (IV = IV + 1)
4055 SourceLocation IncLoc;
4057 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4058 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4059 if (!Inc.isUsable())
4061 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
4062 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4063 if (!Inc.isUsable())
4066 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4067 // Used for directives with static scheduling.
4068 ExprResult NextLB, NextUB;
4069 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4070 isOpenMPDistributeDirective(DKind)) {
4072 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4073 if (!NextLB.isUsable())
4077 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4078 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4079 if (!NextLB.isUsable())
4082 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4083 if (!NextUB.isUsable())
4087 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4088 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4089 if (!NextUB.isUsable())
4093 // Build updates and final values of the loop counters.
4094 bool HasErrors = false;
4095 Built.Counters.resize(NestedLoopCount);
4096 Built.Inits.resize(NestedLoopCount);
4097 Built.Updates.resize(NestedLoopCount);
4098 Built.Finals.resize(NestedLoopCount);
4099 SmallVector<Expr *, 4> LoopMultipliers;
4102 // Go from inner nested loop to outer.
4103 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4104 LoopIterationSpace &IS = IterSpaces[Cnt];
4105 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4106 // Build: Iter = (IV / Div) % IS.NumIters
4107 // where Div is product of previous iterations' IS.NumIters.
4109 if (Div.isUsable()) {
4111 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4114 assert((Cnt == (int)NestedLoopCount - 1) &&
4115 "unusable div expected on first iteration only");
4118 if (Cnt != 0 && Iter.isUsable())
4119 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4121 if (!Iter.isUsable()) {
4126 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
4127 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4128 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4129 IS.CounterVar->getExprLoc(),
4130 /*RefersToCapture=*/true);
4131 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
4132 IS.CounterInit, Captures);
4133 if (!Init.isUsable()) {
4137 ExprResult Update = BuildCounterUpdate(
4138 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4139 IS.CounterStep, IS.Subtract, &Captures);
4140 if (!Update.isUsable()) {
4145 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4146 ExprResult Final = BuildCounterUpdate(
4147 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
4148 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
4149 if (!Final.isUsable()) {
4154 // Build Div for the next iteration: Div <- Div * IS.NumIters
4157 Div = IS.NumIterations;
4159 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4162 // Add parentheses (for debugging purposes only).
4164 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
4165 if (!Div.isUsable()) {
4169 LoopMultipliers.push_back(Div.get());
4171 if (!Update.isUsable() || !Final.isUsable()) {
4176 Built.Counters[Cnt] = IS.CounterVar;
4177 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
4178 Built.Inits[Cnt] = Init.get();
4179 Built.Updates[Cnt] = Update.get();
4180 Built.Finals[Cnt] = Final.get();
4188 Built.IterationVarRef = IV.get();
4189 Built.LastIteration = LastIteration.get();
4190 Built.NumIterations = NumIterations.get();
4191 Built.CalcLastIteration =
4192 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
4193 Built.PreCond = PreCond.get();
4194 Built.PreInits = buildPreInits(C, Captures);
4195 Built.Cond = Cond.get();
4196 Built.Init = Init.get();
4197 Built.Inc = Inc.get();
4198 Built.LB = LB.get();
4199 Built.UB = UB.get();
4200 Built.IL = IL.get();
4201 Built.ST = ST.get();
4202 Built.EUB = EUB.get();
4203 Built.NLB = NextLB.get();
4204 Built.NUB = NextUB.get();
4205 Built.PrevLB = PrevLB.get();
4206 Built.PrevUB = PrevUB.get();
4208 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4209 // Fill data for doacross depend clauses.
4210 for (auto Pair : DSA.getDoacrossDependClauses()) {
4211 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4212 Pair.first->setCounterValue(CounterVal);
4214 if (NestedLoopCount != Pair.second.size() ||
4215 NestedLoopCount != LoopMultipliers.size() + 1) {
4216 // Erroneous case - clause has some problems.
4217 Pair.first->setCounterValue(CounterVal);
4220 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4221 auto I = Pair.second.rbegin();
4222 auto IS = IterSpaces.rbegin();
4223 auto ILM = LoopMultipliers.rbegin();
4224 Expr *UpCounterVal = CounterVal;
4225 Expr *Multiplier = nullptr;
4226 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4228 assert(IS->CounterStep);
4229 Expr *NormalizedOffset =
4231 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4232 I->first, IS->CounterStep)
4237 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4238 NormalizedOffset, Multiplier)
4241 assert(I->second == OO_Plus || I->second == OO_Minus);
4242 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
4243 UpCounterVal = SemaRef
4244 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4245 UpCounterVal, NormalizedOffset)
4253 Pair.first->setCounterValue(UpCounterVal);
4257 return NestedLoopCount;
4260 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
4261 auto CollapseClauses =
4262 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4263 if (CollapseClauses.begin() != CollapseClauses.end())
4264 return (*CollapseClauses.begin())->getNumForLoops();
4268 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
4269 auto OrderedClauses =
4270 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4271 if (OrderedClauses.begin() != OrderedClauses.end())
4272 return (*OrderedClauses.begin())->getNumForLoops();
4276 static bool checkSimdlenSafelenSpecified(Sema &S,
4277 const ArrayRef<OMPClause *> Clauses) {
4278 OMPSafelenClause *Safelen = nullptr;
4279 OMPSimdlenClause *Simdlen = nullptr;
4281 for (auto *Clause : Clauses) {
4282 if (Clause->getClauseKind() == OMPC_safelen)
4283 Safelen = cast<OMPSafelenClause>(Clause);
4284 else if (Clause->getClauseKind() == OMPC_simdlen)
4285 Simdlen = cast<OMPSimdlenClause>(Clause);
4286 if (Safelen && Simdlen)
4290 if (Simdlen && Safelen) {
4291 llvm::APSInt SimdlenRes, SafelenRes;
4292 auto SimdlenLength = Simdlen->getSimdlen();
4293 auto SafelenLength = Safelen->getSafelen();
4294 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4295 SimdlenLength->isInstantiationDependent() ||
4296 SimdlenLength->containsUnexpandedParameterPack())
4298 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4299 SafelenLength->isInstantiationDependent() ||
4300 SafelenLength->containsUnexpandedParameterPack())
4302 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4303 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4304 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4305 // If both simdlen and safelen clauses are specified, the value of the
4306 // simdlen parameter must be less than or equal to the value of the safelen
4308 if (SimdlenRes > SafelenRes) {
4309 S.Diag(SimdlenLength->getExprLoc(),
4310 diag::err_omp_wrong_simdlen_safelen_values)
4311 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4318 StmtResult Sema::ActOnOpenMPSimdDirective(
4319 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4320 SourceLocation EndLoc,
4321 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4325 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4326 OMPLoopDirective::HelperExprs B;
4327 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4328 // define the nested loops number.
4329 unsigned NestedLoopCount = CheckOpenMPLoop(
4330 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4331 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4332 if (NestedLoopCount == 0)
4335 assert((CurContext->isDependentContext() || B.builtAll()) &&
4336 "omp simd loop exprs were not built");
4338 if (!CurContext->isDependentContext()) {
4339 // Finalize the clauses that need pre-built expressions for CodeGen.
4340 for (auto C : Clauses) {
4341 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4342 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4343 B.NumIterations, *this, CurScope,
4349 if (checkSimdlenSafelenSpecified(*this, Clauses))
4352 getCurFunction()->setHasBranchProtectedScope();
4353 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4357 StmtResult Sema::ActOnOpenMPForDirective(
4358 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4359 SourceLocation EndLoc,
4360 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4364 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4365 OMPLoopDirective::HelperExprs B;
4366 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4367 // define the nested loops number.
4368 unsigned NestedLoopCount = CheckOpenMPLoop(
4369 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4370 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4371 if (NestedLoopCount == 0)
4374 assert((CurContext->isDependentContext() || B.builtAll()) &&
4375 "omp for loop exprs were not built");
4377 if (!CurContext->isDependentContext()) {
4378 // Finalize the clauses that need pre-built expressions for CodeGen.
4379 for (auto C : Clauses) {
4380 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4381 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4382 B.NumIterations, *this, CurScope,
4388 getCurFunction()->setHasBranchProtectedScope();
4389 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4390 Clauses, AStmt, B, DSAStack->isCancelRegion());
4393 StmtResult Sema::ActOnOpenMPForSimdDirective(
4394 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4395 SourceLocation EndLoc,
4396 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4400 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4401 OMPLoopDirective::HelperExprs B;
4402 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4403 // define the nested loops number.
4404 unsigned NestedLoopCount =
4405 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4406 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4407 VarsWithImplicitDSA, B);
4408 if (NestedLoopCount == 0)
4411 assert((CurContext->isDependentContext() || B.builtAll()) &&
4412 "omp for simd loop exprs were not built");
4414 if (!CurContext->isDependentContext()) {
4415 // Finalize the clauses that need pre-built expressions for CodeGen.
4416 for (auto C : Clauses) {
4417 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4418 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4419 B.NumIterations, *this, CurScope,
4425 if (checkSimdlenSafelenSpecified(*this, Clauses))
4428 getCurFunction()->setHasBranchProtectedScope();
4429 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4433 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4435 SourceLocation StartLoc,
4436 SourceLocation EndLoc) {
4440 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4441 auto BaseStmt = AStmt;
4442 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4443 BaseStmt = CS->getCapturedStmt();
4444 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4445 auto S = C->children();
4446 if (S.begin() == S.end())
4448 // All associated statements must be '#pragma omp section' except for
4450 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4451 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4453 Diag(SectionStmt->getLocStart(),
4454 diag::err_omp_sections_substmt_not_section);
4457 cast<OMPSectionDirective>(SectionStmt)
4458 ->setHasCancel(DSAStack->isCancelRegion());
4461 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4465 getCurFunction()->setHasBranchProtectedScope();
4467 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4468 DSAStack->isCancelRegion());
4471 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4472 SourceLocation StartLoc,
4473 SourceLocation EndLoc) {
4477 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4479 getCurFunction()->setHasBranchProtectedScope();
4480 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
4482 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4483 DSAStack->isCancelRegion());
4486 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4488 SourceLocation StartLoc,
4489 SourceLocation EndLoc) {
4493 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4495 getCurFunction()->setHasBranchProtectedScope();
4497 // OpenMP [2.7.3, single Construct, Restrictions]
4498 // The copyprivate clause must not be used with the nowait clause.
4499 OMPClause *Nowait = nullptr;
4500 OMPClause *Copyprivate = nullptr;
4501 for (auto *Clause : Clauses) {
4502 if (Clause->getClauseKind() == OMPC_nowait)
4504 else if (Clause->getClauseKind() == OMPC_copyprivate)
4505 Copyprivate = Clause;
4506 if (Copyprivate && Nowait) {
4507 Diag(Copyprivate->getLocStart(),
4508 diag::err_omp_single_copyprivate_with_nowait);
4509 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4514 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4517 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4518 SourceLocation StartLoc,
4519 SourceLocation EndLoc) {
4523 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4525 getCurFunction()->setHasBranchProtectedScope();
4527 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4530 StmtResult Sema::ActOnOpenMPCriticalDirective(
4531 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4532 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
4536 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4538 bool ErrorFound = false;
4540 SourceLocation HintLoc;
4541 bool DependentHint = false;
4542 for (auto *C : Clauses) {
4543 if (C->getClauseKind() == OMPC_hint) {
4544 if (!DirName.getName()) {
4545 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4548 Expr *E = cast<OMPHintClause>(C)->getHint();
4549 if (E->isTypeDependent() || E->isValueDependent() ||
4550 E->isInstantiationDependent())
4551 DependentHint = true;
4553 Hint = E->EvaluateKnownConstInt(Context);
4554 HintLoc = C->getLocStart();
4560 auto Pair = DSAStack->getCriticalWithHint(DirName);
4561 if (Pair.first && DirName.getName() && !DependentHint) {
4562 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4563 Diag(StartLoc, diag::err_omp_critical_with_hint);
4564 if (HintLoc.isValid()) {
4565 Diag(HintLoc, diag::note_omp_critical_hint_here)
4566 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4568 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4569 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4570 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4572 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4573 /*Radix=*/10, /*Signed=*/false);
4575 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4579 getCurFunction()->setHasBranchProtectedScope();
4581 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4583 if (!Pair.first && DirName.getName() && !DependentHint)
4584 DSAStack->addCriticalWithHint(Dir, Hint);
4588 StmtResult Sema::ActOnOpenMPParallelForDirective(
4589 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4590 SourceLocation EndLoc,
4591 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4595 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4596 // 1.2.2 OpenMP Language Terminology
4597 // Structured block - An executable statement with a single entry at the
4598 // top and a single exit at the bottom.
4599 // The point of exit cannot be a branch out of the structured block.
4600 // longjmp() and throw() must not violate the entry/exit criteria.
4601 CS->getCapturedDecl()->setNothrow();
4603 OMPLoopDirective::HelperExprs B;
4604 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4605 // define the nested loops number.
4606 unsigned NestedLoopCount =
4607 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4608 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4609 VarsWithImplicitDSA, B);
4610 if (NestedLoopCount == 0)
4613 assert((CurContext->isDependentContext() || B.builtAll()) &&
4614 "omp parallel for loop exprs were not built");
4616 if (!CurContext->isDependentContext()) {
4617 // Finalize the clauses that need pre-built expressions for CodeGen.
4618 for (auto C : Clauses) {
4619 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4620 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4621 B.NumIterations, *this, CurScope,
4627 getCurFunction()->setHasBranchProtectedScope();
4628 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
4629 NestedLoopCount, Clauses, AStmt, B,
4630 DSAStack->isCancelRegion());
4633 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4634 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4635 SourceLocation EndLoc,
4636 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4640 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4641 // 1.2.2 OpenMP Language Terminology
4642 // Structured block - An executable statement with a single entry at the
4643 // top and a single exit at the bottom.
4644 // The point of exit cannot be a branch out of the structured block.
4645 // longjmp() and throw() must not violate the entry/exit criteria.
4646 CS->getCapturedDecl()->setNothrow();
4648 OMPLoopDirective::HelperExprs B;
4649 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4650 // define the nested loops number.
4651 unsigned NestedLoopCount =
4652 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4653 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4654 VarsWithImplicitDSA, B);
4655 if (NestedLoopCount == 0)
4658 if (!CurContext->isDependentContext()) {
4659 // Finalize the clauses that need pre-built expressions for CodeGen.
4660 for (auto C : Clauses) {
4661 if (auto *LC = dyn_cast<OMPLinearClause>(C))
4662 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4663 B.NumIterations, *this, CurScope,
4669 if (checkSimdlenSafelenSpecified(*this, Clauses))
4672 getCurFunction()->setHasBranchProtectedScope();
4673 return OMPParallelForSimdDirective::Create(
4674 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
4678 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4679 Stmt *AStmt, SourceLocation StartLoc,
4680 SourceLocation EndLoc) {
4684 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4685 auto BaseStmt = AStmt;
4686 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4687 BaseStmt = CS->getCapturedStmt();
4688 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4689 auto S = C->children();
4690 if (S.begin() == S.end())
4692 // All associated statements must be '#pragma omp section' except for
4694 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4695 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4697 Diag(SectionStmt->getLocStart(),
4698 diag::err_omp_parallel_sections_substmt_not_section);
4701 cast<OMPSectionDirective>(SectionStmt)
4702 ->setHasCancel(DSAStack->isCancelRegion());
4705 Diag(AStmt->getLocStart(),
4706 diag::err_omp_parallel_sections_not_compound_stmt);
4710 getCurFunction()->setHasBranchProtectedScope();
4712 return OMPParallelSectionsDirective::Create(
4713 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
4716 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4717 Stmt *AStmt, SourceLocation StartLoc,
4718 SourceLocation EndLoc) {
4722 auto *CS = cast<CapturedStmt>(AStmt);
4723 // 1.2.2 OpenMP Language Terminology
4724 // Structured block - An executable statement with a single entry at the
4725 // top and a single exit at the bottom.
4726 // The point of exit cannot be a branch out of the structured block.
4727 // longjmp() and throw() must not violate the entry/exit criteria.
4728 CS->getCapturedDecl()->setNothrow();
4730 getCurFunction()->setHasBranchProtectedScope();
4732 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4733 DSAStack->isCancelRegion());
4736 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4737 SourceLocation EndLoc) {
4738 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4741 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4742 SourceLocation EndLoc) {
4743 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4746 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4747 SourceLocation EndLoc) {
4748 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4751 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4752 SourceLocation StartLoc,
4753 SourceLocation EndLoc) {
4757 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4759 getCurFunction()->setHasBranchProtectedScope();
4761 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4764 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4765 SourceLocation StartLoc,
4766 SourceLocation EndLoc) {
4767 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4768 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4771 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4773 SourceLocation StartLoc,
4774 SourceLocation EndLoc) {
4775 OMPClause *DependFound = nullptr;
4776 OMPClause *DependSourceClause = nullptr;
4777 OMPClause *DependSinkClause = nullptr;
4778 bool ErrorFound = false;
4779 OMPThreadsClause *TC = nullptr;
4780 OMPSIMDClause *SC = nullptr;
4781 for (auto *C : Clauses) {
4782 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4784 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4785 if (DependSourceClause) {
4786 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4787 << getOpenMPDirectiveName(OMPD_ordered)
4788 << getOpenMPClauseName(OMPC_depend) << 2;
4791 DependSourceClause = C;
4792 if (DependSinkClause) {
4793 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4797 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4798 if (DependSourceClause) {
4799 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4803 DependSinkClause = C;
4805 } else if (C->getClauseKind() == OMPC_threads)
4806 TC = cast<OMPThreadsClause>(C);
4807 else if (C->getClauseKind() == OMPC_simd)
4808 SC = cast<OMPSIMDClause>(C);
4810 if (!ErrorFound && !SC &&
4811 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
4812 // OpenMP [2.8.1,simd Construct, Restrictions]
4813 // An ordered construct with the simd clause is the only OpenMP construct
4814 // that can appear in the simd region.
4815 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
4817 } else if (DependFound && (TC || SC)) {
4818 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4819 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4821 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4822 Diag(DependFound->getLocStart(),
4823 diag::err_omp_ordered_directive_without_param);
4825 } else if (TC || Clauses.empty()) {
4826 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4827 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4828 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4830 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4834 if ((!AStmt && !DependFound) || ErrorFound)
4838 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4840 getCurFunction()->setHasBranchProtectedScope();
4843 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4847 /// \brief Helper class for checking expression in 'omp atomic [update]'
4849 class OpenMPAtomicUpdateChecker {
4850 /// \brief Error results for atomic update expressions.
4851 enum ExprAnalysisErrorCode {
4852 /// \brief A statement is not an expression statement.
4854 /// \brief Expression is not builtin binary or unary operation.
4855 NotABinaryOrUnaryExpression,
4856 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4857 NotAnUnaryIncDecExpression,
4858 /// \brief An expression is not of scalar type.
4860 /// \brief A binary operation is not an assignment operation.
4862 /// \brief RHS part of the binary operation is not a binary expression.
4863 NotABinaryExpression,
4864 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4867 /// \brief RHS binary operation does not have reference to the updated LHS
4869 NotAnUpdateExpression,
4870 /// \brief No errors is found.
4873 /// \brief Reference to Sema.
4875 /// \brief A location for note diagnostics (when error is found).
4876 SourceLocation NoteLoc;
4877 /// \brief 'x' lvalue part of the source atomic expression.
4879 /// \brief 'expr' rvalue part of the source atomic expression.
4881 /// \brief Helper expression of the form
4882 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4883 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4885 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4886 /// important for non-associative operations.
4887 bool IsXLHSInRHSPart;
4888 BinaryOperatorKind Op;
4889 SourceLocation OpLoc;
4890 /// \brief true if the source expression is a postfix unary operation, false
4891 /// if it is a prefix unary operation.
4892 bool IsPostfixUpdate;
4895 OpenMPAtomicUpdateChecker(Sema &SemaRef)
4896 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
4897 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
4898 /// \brief Check specified statement that it is suitable for 'atomic update'
4899 /// constructs and extract 'x', 'expr' and Operation from the original
4900 /// expression. If DiagId and NoteId == 0, then only check is performed
4901 /// without error notification.
4902 /// \param DiagId Diagnostic which should be emitted if error is found.
4903 /// \param NoteId Diagnostic note for the main error message.
4904 /// \return true if statement is not an update expression, false otherwise.
4905 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
4906 /// \brief Return the 'x' lvalue part of the source atomic expression.
4907 Expr *getX() const { return X; }
4908 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4909 Expr *getExpr() const { return E; }
4910 /// \brief Return the update expression used in calculation of the updated
4911 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4912 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4913 Expr *getUpdateExpr() const { return UpdateExpr; }
4914 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4915 /// false otherwise.
4916 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4918 /// \brief true if the source expression is a postfix unary operation, false
4919 /// if it is a prefix unary operation.
4920 bool isPostfixUpdate() const { return IsPostfixUpdate; }
4923 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4924 unsigned NoteId = 0);
4928 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4929 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4930 ExprAnalysisErrorCode ErrorFound = NoError;
4931 SourceLocation ErrorLoc, NoteLoc;
4932 SourceRange ErrorRange, NoteRange;
4933 // Allowed constructs are:
4934 // x = x binop expr;
4935 // x = expr binop x;
4936 if (AtomicBinOp->getOpcode() == BO_Assign) {
4937 X = AtomicBinOp->getLHS();
4938 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4939 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4940 if (AtomicInnerBinOp->isMultiplicativeOp() ||
4941 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4942 AtomicInnerBinOp->isBitwiseOp()) {
4943 Op = AtomicInnerBinOp->getOpcode();
4944 OpLoc = AtomicInnerBinOp->getOperatorLoc();
4945 auto *LHS = AtomicInnerBinOp->getLHS();
4946 auto *RHS = AtomicInnerBinOp->getRHS();
4947 llvm::FoldingSetNodeID XId, LHSId, RHSId;
4948 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4949 /*Canonical=*/true);
4950 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4951 /*Canonical=*/true);
4952 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4953 /*Canonical=*/true);
4956 IsXLHSInRHSPart = true;
4957 } else if (XId == RHSId) {
4959 IsXLHSInRHSPart = false;
4961 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4962 ErrorRange = AtomicInnerBinOp->getSourceRange();
4963 NoteLoc = X->getExprLoc();
4964 NoteRange = X->getSourceRange();
4965 ErrorFound = NotAnUpdateExpression;
4968 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4969 ErrorRange = AtomicInnerBinOp->getSourceRange();
4970 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4971 NoteRange = SourceRange(NoteLoc, NoteLoc);
4972 ErrorFound = NotABinaryOperator;
4975 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4976 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4977 ErrorFound = NotABinaryExpression;
4980 ErrorLoc = AtomicBinOp->getExprLoc();
4981 ErrorRange = AtomicBinOp->getSourceRange();
4982 NoteLoc = AtomicBinOp->getOperatorLoc();
4983 NoteRange = SourceRange(NoteLoc, NoteLoc);
4984 ErrorFound = NotAnAssignmentOp;
4986 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
4987 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4988 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4990 } else if (SemaRef.CurContext->isDependentContext())
4991 E = X = UpdateExpr = nullptr;
4992 return ErrorFound != NoError;
4995 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
4997 ExprAnalysisErrorCode ErrorFound = NoError;
4998 SourceLocation ErrorLoc, NoteLoc;
4999 SourceRange ErrorRange, NoteRange;
5000 // Allowed constructs are:
5006 // x = x binop expr;
5007 // x = expr binop x;
5008 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5009 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5010 if (AtomicBody->getType()->isScalarType() ||
5011 AtomicBody->isInstantiationDependent()) {
5012 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5013 AtomicBody->IgnoreParenImpCasts())) {
5014 // Check for Compound Assignment Operation
5015 Op = BinaryOperator::getOpForCompoundAssignment(
5016 AtomicCompAssignOp->getOpcode());
5017 OpLoc = AtomicCompAssignOp->getOperatorLoc();
5018 E = AtomicCompAssignOp->getRHS();
5019 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
5020 IsXLHSInRHSPart = true;
5021 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5022 AtomicBody->IgnoreParenImpCasts())) {
5023 // Check for Binary Operation
5024 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
5026 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5027 AtomicBody->IgnoreParenImpCasts())) {
5028 // Check for Unary Operation
5029 if (AtomicUnaryOp->isIncrementDecrementOp()) {
5030 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
5031 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5032 OpLoc = AtomicUnaryOp->getOperatorLoc();
5033 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
5034 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5035 IsXLHSInRHSPart = true;
5037 ErrorFound = NotAnUnaryIncDecExpression;
5038 ErrorLoc = AtomicUnaryOp->getExprLoc();
5039 ErrorRange = AtomicUnaryOp->getSourceRange();
5040 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5041 NoteRange = SourceRange(NoteLoc, NoteLoc);
5043 } else if (!AtomicBody->isInstantiationDependent()) {
5044 ErrorFound = NotABinaryOrUnaryExpression;
5045 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5046 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5049 ErrorFound = NotAScalarType;
5050 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5051 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5054 ErrorFound = NotAnExpression;
5055 NoteLoc = ErrorLoc = S->getLocStart();
5056 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5058 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5059 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5060 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5062 } else if (SemaRef.CurContext->isDependentContext())
5063 E = X = UpdateExpr = nullptr;
5064 if (ErrorFound == NoError && E && X) {
5065 // Build an update expression of form 'OpaqueValueExpr(x) binop
5066 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5067 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5068 auto *OVEX = new (SemaRef.getASTContext())
5069 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5070 auto *OVEExpr = new (SemaRef.getASTContext())
5071 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5073 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5074 IsXLHSInRHSPart ? OVEExpr : OVEX);
5075 if (Update.isInvalid())
5077 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5079 if (Update.isInvalid())
5081 UpdateExpr = Update.get();
5083 return ErrorFound != NoError;
5086 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5088 SourceLocation StartLoc,
5089 SourceLocation EndLoc) {
5093 auto *CS = cast<CapturedStmt>(AStmt);
5094 // 1.2.2 OpenMP Language Terminology
5095 // Structured block - An executable statement with a single entry at the
5096 // top and a single exit at the bottom.
5097 // The point of exit cannot be a branch out of the structured block.
5098 // longjmp() and throw() must not violate the entry/exit criteria.
5099 OpenMPClauseKind AtomicKind = OMPC_unknown;
5100 SourceLocation AtomicKindLoc;
5101 for (auto *C : Clauses) {
5102 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
5103 C->getClauseKind() == OMPC_update ||
5104 C->getClauseKind() == OMPC_capture) {
5105 if (AtomicKind != OMPC_unknown) {
5106 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5107 << SourceRange(C->getLocStart(), C->getLocEnd());
5108 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5109 << getOpenMPClauseName(AtomicKind);
5111 AtomicKind = C->getClauseKind();
5112 AtomicKindLoc = C->getLocStart();
5117 auto Body = CS->getCapturedStmt();
5118 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5119 Body = EWC->getSubExpr();
5125 bool IsXLHSInRHSPart = false;
5126 bool IsPostfixUpdate = false;
5127 // OpenMP [2.12.6, atomic Construct]
5128 // In the next expressions:
5129 // * x and v (as applicable) are both l-value expressions with scalar type.
5130 // * During the execution of an atomic region, multiple syntactic
5131 // occurrences of x must designate the same storage location.
5132 // * Neither of v and expr (as applicable) may access the storage location
5134 // * Neither of x and expr (as applicable) may access the storage location
5136 // * expr is an expression with scalar type.
5137 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5138 // * binop, binop=, ++, and -- are not overloaded operators.
5139 // * The expression x binop expr must be numerically equivalent to x binop
5140 // (expr). This requirement is satisfied if the operators in expr have
5141 // precedence greater than binop, or by using parentheses around expr or
5142 // subexpressions of expr.
5143 // * The expression expr binop x must be numerically equivalent to (expr)
5144 // binop x. This requirement is satisfied if the operators in expr have
5145 // precedence equal to or greater than binop, or by using parentheses around
5146 // expr or subexpressions of expr.
5147 // * For forms that allow multiple occurrences of x, the number of times
5148 // that x is evaluated is unspecified.
5149 if (AtomicKind == OMPC_read) {
5156 } ErrorFound = NoError;
5157 SourceLocation ErrorLoc, NoteLoc;
5158 SourceRange ErrorRange, NoteRange;
5159 // If clause is read:
5161 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5163 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5164 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5165 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5166 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5167 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5168 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5169 if (!X->isLValue() || !V->isLValue()) {
5170 auto NotLValueExpr = X->isLValue() ? V : X;
5171 ErrorFound = NotAnLValue;
5172 ErrorLoc = AtomicBinOp->getExprLoc();
5173 ErrorRange = AtomicBinOp->getSourceRange();
5174 NoteLoc = NotLValueExpr->getExprLoc();
5175 NoteRange = NotLValueExpr->getSourceRange();
5177 } else if (!X->isInstantiationDependent() ||
5178 !V->isInstantiationDependent()) {
5179 auto NotScalarExpr =
5180 (X->isInstantiationDependent() || X->getType()->isScalarType())
5183 ErrorFound = NotAScalarType;
5184 ErrorLoc = AtomicBinOp->getExprLoc();
5185 ErrorRange = AtomicBinOp->getSourceRange();
5186 NoteLoc = NotScalarExpr->getExprLoc();
5187 NoteRange = NotScalarExpr->getSourceRange();
5189 } else if (!AtomicBody->isInstantiationDependent()) {
5190 ErrorFound = NotAnAssignmentOp;
5191 ErrorLoc = AtomicBody->getExprLoc();
5192 ErrorRange = AtomicBody->getSourceRange();
5193 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5194 : AtomicBody->getExprLoc();
5195 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5196 : AtomicBody->getSourceRange();
5199 ErrorFound = NotAnExpression;
5200 NoteLoc = ErrorLoc = Body->getLocStart();
5201 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5203 if (ErrorFound != NoError) {
5204 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5206 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5209 } else if (CurContext->isDependentContext())
5211 } else if (AtomicKind == OMPC_write) {
5218 } ErrorFound = NoError;
5219 SourceLocation ErrorLoc, NoteLoc;
5220 SourceRange ErrorRange, NoteRange;
5221 // If clause is write:
5223 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5225 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5226 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5227 X = AtomicBinOp->getLHS();
5228 E = AtomicBinOp->getRHS();
5229 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5230 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5231 if (!X->isLValue()) {
5232 ErrorFound = NotAnLValue;
5233 ErrorLoc = AtomicBinOp->getExprLoc();
5234 ErrorRange = AtomicBinOp->getSourceRange();
5235 NoteLoc = X->getExprLoc();
5236 NoteRange = X->getSourceRange();
5238 } else if (!X->isInstantiationDependent() ||
5239 !E->isInstantiationDependent()) {
5240 auto NotScalarExpr =
5241 (X->isInstantiationDependent() || X->getType()->isScalarType())
5244 ErrorFound = NotAScalarType;
5245 ErrorLoc = AtomicBinOp->getExprLoc();
5246 ErrorRange = AtomicBinOp->getSourceRange();
5247 NoteLoc = NotScalarExpr->getExprLoc();
5248 NoteRange = NotScalarExpr->getSourceRange();
5250 } else if (!AtomicBody->isInstantiationDependent()) {
5251 ErrorFound = NotAnAssignmentOp;
5252 ErrorLoc = AtomicBody->getExprLoc();
5253 ErrorRange = AtomicBody->getSourceRange();
5254 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5255 : AtomicBody->getExprLoc();
5256 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5257 : AtomicBody->getSourceRange();
5260 ErrorFound = NotAnExpression;
5261 NoteLoc = ErrorLoc = Body->getLocStart();
5262 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5264 if (ErrorFound != NoError) {
5265 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5267 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5270 } else if (CurContext->isDependentContext())
5272 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
5273 // If clause is update:
5279 // x = x binop expr;
5280 // x = expr binop x;
5281 OpenMPAtomicUpdateChecker Checker(*this);
5282 if (Checker.checkStatement(
5283 Body, (AtomicKind == OMPC_update)
5284 ? diag::err_omp_atomic_update_not_expression_statement
5285 : diag::err_omp_atomic_not_expression_statement,
5286 diag::note_omp_atomic_update))
5288 if (!CurContext->isDependentContext()) {
5289 E = Checker.getExpr();
5291 UE = Checker.getUpdateExpr();
5292 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5294 } else if (AtomicKind == OMPC_capture) {
5297 NotACompoundStatement,
5298 NotTwoSubstatements,
5299 NotASpecificExpression,
5301 } ErrorFound = NoError;
5302 SourceLocation ErrorLoc, NoteLoc;
5303 SourceRange ErrorRange, NoteRange;
5304 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5305 // If clause is a capture:
5310 // v = x binop= expr;
5311 // v = x = x binop expr;
5312 // v = x = expr binop x;
5314 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5315 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5316 V = AtomicBinOp->getLHS();
5317 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5318 OpenMPAtomicUpdateChecker Checker(*this);
5319 if (Checker.checkStatement(
5320 Body, diag::err_omp_atomic_capture_not_expression_statement,
5321 diag::note_omp_atomic_update))
5323 E = Checker.getExpr();
5325 UE = Checker.getUpdateExpr();
5326 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5327 IsPostfixUpdate = Checker.isPostfixUpdate();
5328 } else if (!AtomicBody->isInstantiationDependent()) {
5329 ErrorLoc = AtomicBody->getExprLoc();
5330 ErrorRange = AtomicBody->getSourceRange();
5331 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5332 : AtomicBody->getExprLoc();
5333 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5334 : AtomicBody->getSourceRange();
5335 ErrorFound = NotAnAssignmentOp;
5337 if (ErrorFound != NoError) {
5338 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5340 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5342 } else if (CurContext->isDependentContext()) {
5343 UE = V = E = X = nullptr;
5346 // If clause is a capture:
5347 // { v = x; x = expr; }
5352 // { v = x; x binop= expr; }
5353 // { v = x; x = x binop expr; }
5354 // { v = x; x = expr binop x; }
5359 // { x binop= expr; v = x; }
5360 // { x = x binop expr; v = x; }
5361 // { x = expr binop x; v = x; }
5362 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5363 // Check that this is { expr1; expr2; }
5364 if (CS->size() == 2) {
5365 auto *First = CS->body_front();
5366 auto *Second = CS->body_back();
5367 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5368 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5369 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5370 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5371 // Need to find what subexpression is 'v' and what is 'x'.
5372 OpenMPAtomicUpdateChecker Checker(*this);
5373 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5374 BinaryOperator *BinOp = nullptr;
5375 if (IsUpdateExprFound) {
5376 BinOp = dyn_cast<BinaryOperator>(First);
5377 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5379 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5384 // { v = x; x binop= expr; }
5385 // { v = x; x = x binop expr; }
5386 // { v = x; x = expr binop x; }
5387 // Check that the first expression has form v = x.
5388 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5389 llvm::FoldingSetNodeID XId, PossibleXId;
5390 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5391 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5392 IsUpdateExprFound = XId == PossibleXId;
5393 if (IsUpdateExprFound) {
5394 V = BinOp->getLHS();
5396 E = Checker.getExpr();
5397 UE = Checker.getUpdateExpr();
5398 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5399 IsPostfixUpdate = true;
5402 if (!IsUpdateExprFound) {
5403 IsUpdateExprFound = !Checker.checkStatement(First);
5405 if (IsUpdateExprFound) {
5406 BinOp = dyn_cast<BinaryOperator>(Second);
5407 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5409 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5414 // { x binop= expr; v = x; }
5415 // { x = x binop expr; v = x; }
5416 // { x = expr binop x; v = x; }
5417 // Check that the second expression has form v = x.
5418 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5419 llvm::FoldingSetNodeID XId, PossibleXId;
5420 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5421 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5422 IsUpdateExprFound = XId == PossibleXId;
5423 if (IsUpdateExprFound) {
5424 V = BinOp->getLHS();
5426 E = Checker.getExpr();
5427 UE = Checker.getUpdateExpr();
5428 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5429 IsPostfixUpdate = false;
5433 if (!IsUpdateExprFound) {
5434 // { v = x; x = expr; }
5435 auto *FirstExpr = dyn_cast<Expr>(First);
5436 auto *SecondExpr = dyn_cast<Expr>(Second);
5437 if (!FirstExpr || !SecondExpr ||
5438 !(FirstExpr->isInstantiationDependent() ||
5439 SecondExpr->isInstantiationDependent())) {
5440 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5441 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
5442 ErrorFound = NotAnAssignmentOp;
5443 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5444 : First->getLocStart();
5445 NoteRange = ErrorRange = FirstBinOp
5446 ? FirstBinOp->getSourceRange()
5447 : SourceRange(ErrorLoc, ErrorLoc);
5449 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5450 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5451 ErrorFound = NotAnAssignmentOp;
5452 NoteLoc = ErrorLoc = SecondBinOp
5453 ? SecondBinOp->getOperatorLoc()
5454 : Second->getLocStart();
5455 NoteRange = ErrorRange =
5456 SecondBinOp ? SecondBinOp->getSourceRange()
5457 : SourceRange(ErrorLoc, ErrorLoc);
5459 auto *PossibleXRHSInFirst =
5460 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5461 auto *PossibleXLHSInSecond =
5462 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5463 llvm::FoldingSetNodeID X1Id, X2Id;
5464 PossibleXRHSInFirst->Profile(X1Id, Context,
5465 /*Canonical=*/true);
5466 PossibleXLHSInSecond->Profile(X2Id, Context,
5467 /*Canonical=*/true);
5468 IsUpdateExprFound = X1Id == X2Id;
5469 if (IsUpdateExprFound) {
5470 V = FirstBinOp->getLHS();
5471 X = SecondBinOp->getLHS();
5472 E = SecondBinOp->getRHS();
5474 IsXLHSInRHSPart = false;
5475 IsPostfixUpdate = true;
5477 ErrorFound = NotASpecificExpression;
5478 ErrorLoc = FirstBinOp->getExprLoc();
5479 ErrorRange = FirstBinOp->getSourceRange();
5480 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5481 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5488 NoteLoc = ErrorLoc = Body->getLocStart();
5489 NoteRange = ErrorRange =
5490 SourceRange(Body->getLocStart(), Body->getLocStart());
5491 ErrorFound = NotTwoSubstatements;
5494 NoteLoc = ErrorLoc = Body->getLocStart();
5495 NoteRange = ErrorRange =
5496 SourceRange(Body->getLocStart(), Body->getLocStart());
5497 ErrorFound = NotACompoundStatement;
5499 if (ErrorFound != NoError) {
5500 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5502 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5504 } else if (CurContext->isDependentContext()) {
5505 UE = V = E = X = nullptr;
5510 getCurFunction()->setHasBranchProtectedScope();
5512 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5513 X, V, E, UE, IsXLHSInRHSPart,
5517 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5519 SourceLocation StartLoc,
5520 SourceLocation EndLoc) {
5524 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5525 // 1.2.2 OpenMP Language Terminology
5526 // Structured block - An executable statement with a single entry at the
5527 // top and a single exit at the bottom.
5528 // The point of exit cannot be a branch out of the structured block.
5529 // longjmp() and throw() must not violate the entry/exit criteria.
5530 CS->getCapturedDecl()->setNothrow();
5532 // OpenMP [2.16, Nesting of Regions]
5533 // If specified, a teams construct must be contained within a target
5534 // construct. That target construct must contain no statements or directives
5535 // outside of the teams construct.
5536 if (DSAStack->hasInnerTeamsRegion()) {
5537 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5538 bool OMPTeamsFound = true;
5539 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5540 auto I = CS->body_begin();
5541 while (I != CS->body_end()) {
5542 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
5543 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5544 OMPTeamsFound = false;
5549 assert(I != CS->body_end() && "Not found statement");
5552 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5553 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
5555 if (!OMPTeamsFound) {
5556 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5557 Diag(DSAStack->getInnerTeamsRegionLoc(),
5558 diag::note_omp_nested_teams_construct_here);
5559 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5560 << isa<OMPExecutableDirective>(S);
5565 getCurFunction()->setHasBranchProtectedScope();
5567 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5571 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5572 Stmt *AStmt, SourceLocation StartLoc,
5573 SourceLocation EndLoc) {
5577 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5578 // 1.2.2 OpenMP Language Terminology
5579 // Structured block - An executable statement with a single entry at the
5580 // top and a single exit at the bottom.
5581 // The point of exit cannot be a branch out of the structured block.
5582 // longjmp() and throw() must not violate the entry/exit criteria.
5583 CS->getCapturedDecl()->setNothrow();
5585 getCurFunction()->setHasBranchProtectedScope();
5587 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5591 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5592 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5593 SourceLocation EndLoc,
5594 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5598 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5599 // 1.2.2 OpenMP Language Terminology
5600 // Structured block - An executable statement with a single entry at the
5601 // top and a single exit at the bottom.
5602 // The point of exit cannot be a branch out of the structured block.
5603 // longjmp() and throw() must not violate the entry/exit criteria.
5604 CS->getCapturedDecl()->setNothrow();
5606 OMPLoopDirective::HelperExprs B;
5607 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5608 // define the nested loops number.
5609 unsigned NestedLoopCount =
5610 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5611 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5612 VarsWithImplicitDSA, B);
5613 if (NestedLoopCount == 0)
5616 assert((CurContext->isDependentContext() || B.builtAll()) &&
5617 "omp target parallel for loop exprs were not built");
5619 if (!CurContext->isDependentContext()) {
5620 // Finalize the clauses that need pre-built expressions for CodeGen.
5621 for (auto C : Clauses) {
5622 if (auto *LC = dyn_cast<OMPLinearClause>(C))
5623 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5624 B.NumIterations, *this, CurScope,
5630 getCurFunction()->setHasBranchProtectedScope();
5631 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5632 NestedLoopCount, Clauses, AStmt,
5633 B, DSAStack->isCancelRegion());
5636 /// \brief Check for existence of a map clause in the list of clauses.
5637 static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5638 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5640 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5648 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5650 SourceLocation StartLoc,
5651 SourceLocation EndLoc) {
5655 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5657 // OpenMP [2.10.1, Restrictions, p. 97]
5658 // At least one map clause must appear on the directive.
5659 if (!HasMapClause(Clauses)) {
5660 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5661 << getOpenMPDirectiveName(OMPD_target_data);
5665 getCurFunction()->setHasBranchProtectedScope();
5667 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5672 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5673 SourceLocation StartLoc,
5674 SourceLocation EndLoc) {
5675 // OpenMP [2.10.2, Restrictions, p. 99]
5676 // At least one map clause must appear on the directive.
5677 if (!HasMapClause(Clauses)) {
5678 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5679 << getOpenMPDirectiveName(OMPD_target_enter_data);
5683 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5688 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5689 SourceLocation StartLoc,
5690 SourceLocation EndLoc) {
5691 // OpenMP [2.10.3, Restrictions, p. 102]
5692 // At least one map clause must appear on the directive.
5693 if (!HasMapClause(Clauses)) {
5694 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5695 << getOpenMPDirectiveName(OMPD_target_exit_data);
5699 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5702 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5703 SourceLocation StartLoc,
5704 SourceLocation EndLoc) {
5705 bool seenMotionClause = false;
5706 for (auto *C : Clauses) {
5707 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
5708 seenMotionClause = true;
5710 if (!seenMotionClause) {
5711 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5714 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5717 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5718 Stmt *AStmt, SourceLocation StartLoc,
5719 SourceLocation EndLoc) {
5723 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5724 // 1.2.2 OpenMP Language Terminology
5725 // Structured block - An executable statement with a single entry at the
5726 // top and a single exit at the bottom.
5727 // The point of exit cannot be a branch out of the structured block.
5728 // longjmp() and throw() must not violate the entry/exit criteria.
5729 CS->getCapturedDecl()->setNothrow();
5731 getCurFunction()->setHasBranchProtectedScope();
5733 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5737 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5738 SourceLocation EndLoc,
5739 OpenMPDirectiveKind CancelRegion) {
5740 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5741 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5742 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5743 << getOpenMPDirectiveName(CancelRegion);
5746 if (DSAStack->isParentNowaitRegion()) {
5747 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5750 if (DSAStack->isParentOrderedRegion()) {
5751 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5754 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5758 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5759 SourceLocation StartLoc,
5760 SourceLocation EndLoc,
5761 OpenMPDirectiveKind CancelRegion) {
5762 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5763 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5764 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5765 << getOpenMPDirectiveName(CancelRegion);
5768 if (DSAStack->isParentNowaitRegion()) {
5769 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5772 if (DSAStack->isParentOrderedRegion()) {
5773 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5776 DSAStack->setParentCancelRegion(/*Cancel=*/true);
5777 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5781 static bool checkGrainsizeNumTasksClauses(Sema &S,
5782 ArrayRef<OMPClause *> Clauses) {
5783 OMPClause *PrevClause = nullptr;
5784 bool ErrorFound = false;
5785 for (auto *C : Clauses) {
5786 if (C->getClauseKind() == OMPC_grainsize ||
5787 C->getClauseKind() == OMPC_num_tasks) {
5790 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5791 S.Diag(C->getLocStart(),
5792 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5793 << getOpenMPClauseName(C->getClauseKind())
5794 << getOpenMPClauseName(PrevClause->getClauseKind());
5795 S.Diag(PrevClause->getLocStart(),
5796 diag::note_omp_previous_grainsize_num_tasks)
5797 << getOpenMPClauseName(PrevClause->getClauseKind());
5805 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5806 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5807 SourceLocation EndLoc,
5808 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5812 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5813 OMPLoopDirective::HelperExprs B;
5814 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5815 // define the nested loops number.
5816 unsigned NestedLoopCount =
5817 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
5818 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5819 VarsWithImplicitDSA, B);
5820 if (NestedLoopCount == 0)
5823 assert((CurContext->isDependentContext() || B.builtAll()) &&
5824 "omp for loop exprs were not built");
5826 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5827 // The grainsize clause and num_tasks clause are mutually exclusive and may
5828 // not appear on the same taskloop directive.
5829 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5832 getCurFunction()->setHasBranchProtectedScope();
5833 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5834 NestedLoopCount, Clauses, AStmt, B);
5837 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5838 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5839 SourceLocation EndLoc,
5840 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5844 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5845 OMPLoopDirective::HelperExprs B;
5846 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5847 // define the nested loops number.
5848 unsigned NestedLoopCount =
5849 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5850 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5851 VarsWithImplicitDSA, B);
5852 if (NestedLoopCount == 0)
5855 assert((CurContext->isDependentContext() || B.builtAll()) &&
5856 "omp for loop exprs were not built");
5858 if (!CurContext->isDependentContext()) {
5859 // Finalize the clauses that need pre-built expressions for CodeGen.
5860 for (auto C : Clauses) {
5861 if (auto *LC = dyn_cast<OMPLinearClause>(C))
5862 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5863 B.NumIterations, *this, CurScope,
5869 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5870 // The grainsize clause and num_tasks clause are mutually exclusive and may
5871 // not appear on the same taskloop directive.
5872 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5875 getCurFunction()->setHasBranchProtectedScope();
5876 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5877 NestedLoopCount, Clauses, AStmt, B);
5880 StmtResult Sema::ActOnOpenMPDistributeDirective(
5881 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5882 SourceLocation EndLoc,
5883 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5887 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5888 OMPLoopDirective::HelperExprs B;
5889 // In presence of clause 'collapse' with number of loops, it will
5890 // define the nested loops number.
5891 unsigned NestedLoopCount =
5892 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5893 nullptr /*ordered not a clause on distribute*/, AStmt,
5894 *this, *DSAStack, VarsWithImplicitDSA, B);
5895 if (NestedLoopCount == 0)
5898 assert((CurContext->isDependentContext() || B.builtAll()) &&
5899 "omp for loop exprs were not built");
5901 getCurFunction()->setHasBranchProtectedScope();
5902 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5903 NestedLoopCount, Clauses, AStmt, B);
5906 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
5907 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5908 SourceLocation EndLoc,
5909 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5913 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5914 // 1.2.2 OpenMP Language Terminology
5915 // Structured block - An executable statement with a single entry at the
5916 // top and a single exit at the bottom.
5917 // The point of exit cannot be a branch out of the structured block.
5918 // longjmp() and throw() must not violate the entry/exit criteria.
5919 CS->getCapturedDecl()->setNothrow();
5921 OMPLoopDirective::HelperExprs B;
5922 // In presence of clause 'collapse' with number of loops, it will
5923 // define the nested loops number.
5924 unsigned NestedLoopCount = CheckOpenMPLoop(
5925 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
5926 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5927 VarsWithImplicitDSA, B);
5928 if (NestedLoopCount == 0)
5931 assert((CurContext->isDependentContext() || B.builtAll()) &&
5932 "omp for loop exprs were not built");
5934 getCurFunction()->setHasBranchProtectedScope();
5935 return OMPDistributeParallelForDirective::Create(
5936 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5939 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
5940 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5941 SourceLocation EndLoc,
5942 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5946 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5947 // 1.2.2 OpenMP Language Terminology
5948 // Structured block - An executable statement with a single entry at the
5949 // top and a single exit at the bottom.
5950 // The point of exit cannot be a branch out of the structured block.
5951 // longjmp() and throw() must not violate the entry/exit criteria.
5952 CS->getCapturedDecl()->setNothrow();
5954 OMPLoopDirective::HelperExprs B;
5955 // In presence of clause 'collapse' with number of loops, it will
5956 // define the nested loops number.
5957 unsigned NestedLoopCount = CheckOpenMPLoop(
5958 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
5959 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5960 VarsWithImplicitDSA, B);
5961 if (NestedLoopCount == 0)
5964 assert((CurContext->isDependentContext() || B.builtAll()) &&
5965 "omp for loop exprs were not built");
5967 if (checkSimdlenSafelenSpecified(*this, Clauses))
5970 getCurFunction()->setHasBranchProtectedScope();
5971 return OMPDistributeParallelForSimdDirective::Create(
5972 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5975 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
5976 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5977 SourceLocation EndLoc,
5978 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5982 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5983 // 1.2.2 OpenMP Language Terminology
5984 // Structured block - An executable statement with a single entry at the
5985 // top and a single exit at the bottom.
5986 // The point of exit cannot be a branch out of the structured block.
5987 // longjmp() and throw() must not violate the entry/exit criteria.
5988 CS->getCapturedDecl()->setNothrow();
5990 OMPLoopDirective::HelperExprs B;
5991 // In presence of clause 'collapse' with number of loops, it will
5992 // define the nested loops number.
5993 unsigned NestedLoopCount =
5994 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
5995 nullptr /*ordered not a clause on distribute*/, AStmt,
5996 *this, *DSAStack, VarsWithImplicitDSA, B);
5997 if (NestedLoopCount == 0)
6000 assert((CurContext->isDependentContext() || B.builtAll()) &&
6001 "omp for loop exprs were not built");
6003 if (checkSimdlenSafelenSpecified(*this, Clauses))
6006 getCurFunction()->setHasBranchProtectedScope();
6007 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6008 NestedLoopCount, Clauses, AStmt, B);
6011 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6012 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6013 SourceLocation EndLoc,
6014 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6018 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6019 // 1.2.2 OpenMP Language Terminology
6020 // Structured block - An executable statement with a single entry at the
6021 // top and a single exit at the bottom.
6022 // The point of exit cannot be a branch out of the structured block.
6023 // longjmp() and throw() must not violate the entry/exit criteria.
6024 CS->getCapturedDecl()->setNothrow();
6026 OMPLoopDirective::HelperExprs B;
6027 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6028 // define the nested loops number.
6029 unsigned NestedLoopCount = CheckOpenMPLoop(
6030 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6031 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6032 VarsWithImplicitDSA, B);
6033 if (NestedLoopCount == 0)
6036 assert((CurContext->isDependentContext() || B.builtAll()) &&
6037 "omp target parallel for simd loop exprs were not built");
6039 if (!CurContext->isDependentContext()) {
6040 // Finalize the clauses that need pre-built expressions for CodeGen.
6041 for (auto C : Clauses) {
6042 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6043 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6044 B.NumIterations, *this, CurScope,
6049 if (checkSimdlenSafelenSpecified(*this, Clauses))
6052 getCurFunction()->setHasBranchProtectedScope();
6053 return OMPTargetParallelForSimdDirective::Create(
6054 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6057 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6058 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6059 SourceLocation EndLoc,
6060 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6064 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6065 // 1.2.2 OpenMP Language Terminology
6066 // Structured block - An executable statement with a single entry at the
6067 // top and a single exit at the bottom.
6068 // The point of exit cannot be a branch out of the structured block.
6069 // longjmp() and throw() must not violate the entry/exit criteria.
6070 CS->getCapturedDecl()->setNothrow();
6072 OMPLoopDirective::HelperExprs B;
6073 // In presence of clause 'collapse' with number of loops, it will define the
6074 // nested loops number.
6075 unsigned NestedLoopCount =
6076 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6077 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6078 VarsWithImplicitDSA, B);
6079 if (NestedLoopCount == 0)
6082 assert((CurContext->isDependentContext() || B.builtAll()) &&
6083 "omp target simd loop exprs were not built");
6085 if (!CurContext->isDependentContext()) {
6086 // Finalize the clauses that need pre-built expressions for CodeGen.
6087 for (auto C : Clauses) {
6088 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6089 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6090 B.NumIterations, *this, CurScope,
6096 if (checkSimdlenSafelenSpecified(*this, Clauses))
6099 getCurFunction()->setHasBranchProtectedScope();
6100 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6101 NestedLoopCount, Clauses, AStmt, B);
6104 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6105 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6106 SourceLocation EndLoc,
6107 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6111 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6112 // 1.2.2 OpenMP Language Terminology
6113 // Structured block - An executable statement with a single entry at the
6114 // top and a single exit at the bottom.
6115 // The point of exit cannot be a branch out of the structured block.
6116 // longjmp() and throw() must not violate the entry/exit criteria.
6117 CS->getCapturedDecl()->setNothrow();
6119 OMPLoopDirective::HelperExprs B;
6120 // In presence of clause 'collapse' with number of loops, it will
6121 // define the nested loops number.
6122 unsigned NestedLoopCount =
6123 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6124 nullptr /*ordered not a clause on distribute*/, AStmt,
6125 *this, *DSAStack, VarsWithImplicitDSA, B);
6126 if (NestedLoopCount == 0)
6129 assert((CurContext->isDependentContext() || B.builtAll()) &&
6130 "omp teams distribute loop exprs were not built");
6132 getCurFunction()->setHasBranchProtectedScope();
6133 return OMPTeamsDistributeDirective::Create(
6134 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6137 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6138 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6139 SourceLocation EndLoc,
6140 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6144 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6145 // 1.2.2 OpenMP Language Terminology
6146 // Structured block - An executable statement with a single entry at the
6147 // top and a single exit at the bottom.
6148 // The point of exit cannot be a branch out of the structured block.
6149 // longjmp() and throw() must not violate the entry/exit criteria.
6150 CS->getCapturedDecl()->setNothrow();
6152 OMPLoopDirective::HelperExprs B;
6153 // In presence of clause 'collapse' with number of loops, it will
6154 // define the nested loops number.
6155 unsigned NestedLoopCount = CheckOpenMPLoop(
6156 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6157 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6158 VarsWithImplicitDSA, B);
6160 if (NestedLoopCount == 0)
6163 assert((CurContext->isDependentContext() || B.builtAll()) &&
6164 "omp teams distribute simd loop exprs were not built");
6166 if (!CurContext->isDependentContext()) {
6167 // Finalize the clauses that need pre-built expressions for CodeGen.
6168 for (auto C : Clauses) {
6169 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6170 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6171 B.NumIterations, *this, CurScope,
6177 if (checkSimdlenSafelenSpecified(*this, Clauses))
6180 getCurFunction()->setHasBranchProtectedScope();
6181 return OMPTeamsDistributeSimdDirective::Create(
6182 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6185 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6186 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6187 SourceLocation EndLoc,
6188 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6192 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6193 // 1.2.2 OpenMP Language Terminology
6194 // Structured block - An executable statement with a single entry at the
6195 // top and a single exit at the bottom.
6196 // The point of exit cannot be a branch out of the structured block.
6197 // longjmp() and throw() must not violate the entry/exit criteria.
6198 CS->getCapturedDecl()->setNothrow();
6200 OMPLoopDirective::HelperExprs B;
6201 // In presence of clause 'collapse' with number of loops, it will
6202 // define the nested loops number.
6203 auto NestedLoopCount = CheckOpenMPLoop(
6204 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6205 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6206 VarsWithImplicitDSA, B);
6208 if (NestedLoopCount == 0)
6211 assert((CurContext->isDependentContext() || B.builtAll()) &&
6212 "omp for loop exprs were not built");
6214 if (!CurContext->isDependentContext()) {
6215 // Finalize the clauses that need pre-built expressions for CodeGen.
6216 for (auto C : Clauses) {
6217 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6218 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6219 B.NumIterations, *this, CurScope,
6225 if (checkSimdlenSafelenSpecified(*this, Clauses))
6228 getCurFunction()->setHasBranchProtectedScope();
6229 return OMPTeamsDistributeParallelForSimdDirective::Create(
6230 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6233 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6234 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6235 SourceLocation EndLoc,
6236 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6240 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6241 // 1.2.2 OpenMP Language Terminology
6242 // Structured block - An executable statement with a single entry at the
6243 // top and a single exit at the bottom.
6244 // The point of exit cannot be a branch out of the structured block.
6245 // longjmp() and throw() must not violate the entry/exit criteria.
6246 CS->getCapturedDecl()->setNothrow();
6248 OMPLoopDirective::HelperExprs B;
6249 // In presence of clause 'collapse' with number of loops, it will
6250 // define the nested loops number.
6251 unsigned NestedLoopCount = CheckOpenMPLoop(
6252 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6253 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6254 VarsWithImplicitDSA, B);
6256 if (NestedLoopCount == 0)
6259 assert((CurContext->isDependentContext() || B.builtAll()) &&
6260 "omp for loop exprs were not built");
6262 if (!CurContext->isDependentContext()) {
6263 // Finalize the clauses that need pre-built expressions for CodeGen.
6264 for (auto C : Clauses) {
6265 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6266 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6267 B.NumIterations, *this, CurScope,
6273 getCurFunction()->setHasBranchProtectedScope();
6274 return OMPTeamsDistributeParallelForDirective::Create(
6275 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6278 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6280 SourceLocation StartLoc,
6281 SourceLocation EndLoc) {
6285 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6286 // 1.2.2 OpenMP Language Terminology
6287 // Structured block - An executable statement with a single entry at the
6288 // top and a single exit at the bottom.
6289 // The point of exit cannot be a branch out of the structured block.
6290 // longjmp() and throw() must not violate the entry/exit criteria.
6291 CS->getCapturedDecl()->setNothrow();
6293 getCurFunction()->setHasBranchProtectedScope();
6295 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6299 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6300 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6301 SourceLocation EndLoc,
6302 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6306 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6307 // 1.2.2 OpenMP Language Terminology
6308 // Structured block - An executable statement with a single entry at the
6309 // top and a single exit at the bottom.
6310 // The point of exit cannot be a branch out of the structured block.
6311 // longjmp() and throw() must not violate the entry/exit criteria.
6312 CS->getCapturedDecl()->setNothrow();
6314 OMPLoopDirective::HelperExprs B;
6315 // In presence of clause 'collapse' with number of loops, it will
6316 // define the nested loops number.
6317 auto NestedLoopCount = CheckOpenMPLoop(
6318 OMPD_target_teams_distribute,
6319 getCollapseNumberExpr(Clauses),
6320 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6321 VarsWithImplicitDSA, B);
6322 if (NestedLoopCount == 0)
6325 assert((CurContext->isDependentContext() || B.builtAll()) &&
6326 "omp target teams distribute loop exprs were not built");
6328 getCurFunction()->setHasBranchProtectedScope();
6329 return OMPTargetTeamsDistributeDirective::Create(
6330 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6333 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6334 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6335 SourceLocation EndLoc,
6336 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6340 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6341 // 1.2.2 OpenMP Language Terminology
6342 // Structured block - An executable statement with a single entry at the
6343 // top and a single exit at the bottom.
6344 // The point of exit cannot be a branch out of the structured block.
6345 // longjmp() and throw() must not violate the entry/exit criteria.
6346 CS->getCapturedDecl()->setNothrow();
6348 OMPLoopDirective::HelperExprs B;
6349 // In presence of clause 'collapse' with number of loops, it will
6350 // define the nested loops number.
6351 auto NestedLoopCount = CheckOpenMPLoop(
6352 OMPD_target_teams_distribute_parallel_for,
6353 getCollapseNumberExpr(Clauses),
6354 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6355 VarsWithImplicitDSA, B);
6356 if (NestedLoopCount == 0)
6359 assert((CurContext->isDependentContext() || B.builtAll()) &&
6360 "omp target teams distribute parallel for loop exprs were not built");
6362 if (!CurContext->isDependentContext()) {
6363 // Finalize the clauses that need pre-built expressions for CodeGen.
6364 for (auto C : Clauses) {
6365 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6366 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6367 B.NumIterations, *this, CurScope,
6373 getCurFunction()->setHasBranchProtectedScope();
6374 return OMPTargetTeamsDistributeParallelForDirective::Create(
6375 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6378 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
6379 SourceLocation StartLoc,
6380 SourceLocation LParenLoc,
6381 SourceLocation EndLoc) {
6382 OMPClause *Res = nullptr;
6385 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6387 case OMPC_num_threads:
6388 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6391 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6394 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6397 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6400 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6403 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6405 case OMPC_num_teams:
6406 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6408 case OMPC_thread_limit:
6409 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6412 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6414 case OMPC_grainsize:
6415 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6417 case OMPC_num_tasks:
6418 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6421 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6425 case OMPC_proc_bind:
6428 case OMPC_firstprivate:
6429 case OMPC_lastprivate:
6431 case OMPC_reduction:
6435 case OMPC_copyprivate:
6438 case OMPC_mergeable:
6439 case OMPC_threadprivate:
6451 case OMPC_dist_schedule:
6452 case OMPC_defaultmap:
6457 case OMPC_use_device_ptr:
6458 case OMPC_is_device_ptr:
6459 llvm_unreachable("Clause is not allowed.");
6464 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6465 Expr *Condition, SourceLocation StartLoc,
6466 SourceLocation LParenLoc,
6467 SourceLocation NameModifierLoc,
6468 SourceLocation ColonLoc,
6469 SourceLocation EndLoc) {
6470 Expr *ValExpr = Condition;
6471 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6472 !Condition->isInstantiationDependent() &&
6473 !Condition->containsUnexpandedParameterPack()) {
6474 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
6475 if (Val.isInvalid())
6478 ValExpr = MakeFullExpr(Val.get()).get();
6481 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
6482 NameModifierLoc, ColonLoc, EndLoc);
6485 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6486 SourceLocation StartLoc,
6487 SourceLocation LParenLoc,
6488 SourceLocation EndLoc) {
6489 Expr *ValExpr = Condition;
6490 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6491 !Condition->isInstantiationDependent() &&
6492 !Condition->containsUnexpandedParameterPack()) {
6493 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
6494 if (Val.isInvalid())
6497 ValExpr = MakeFullExpr(Val.get()).get();
6500 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6502 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6507 class IntConvertDiagnoser : public ICEConvertDiagnoser {
6509 IntConvertDiagnoser()
6510 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
6511 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6512 QualType T) override {
6513 return S.Diag(Loc, diag::err_omp_not_integral) << T;
6515 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6516 QualType T) override {
6517 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6519 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6521 QualType ConvTy) override {
6522 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6524 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6525 QualType ConvTy) override {
6526 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
6527 << ConvTy->isEnumeralType() << ConvTy;
6529 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6530 QualType T) override {
6531 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6533 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6534 QualType ConvTy) override {
6535 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
6536 << ConvTy->isEnumeralType() << ConvTy;
6538 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6539 QualType) override {
6540 llvm_unreachable("conversion functions are permitted");
6543 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6546 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
6547 OpenMPClauseKind CKind,
6548 bool StrictlyPositive) {
6549 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6550 !ValExpr->isInstantiationDependent()) {
6551 SourceLocation Loc = ValExpr->getExprLoc();
6553 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6554 if (Value.isInvalid())
6557 ValExpr = Value.get();
6558 // The expression must evaluate to a non-negative integer value.
6559 llvm::APSInt Result;
6560 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
6561 Result.isSigned() &&
6562 !((!StrictlyPositive && Result.isNonNegative()) ||
6563 (StrictlyPositive && Result.isStrictlyPositive()))) {
6564 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
6565 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6566 << ValExpr->getSourceRange();
6573 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6574 SourceLocation StartLoc,
6575 SourceLocation LParenLoc,
6576 SourceLocation EndLoc) {
6577 Expr *ValExpr = NumThreads;
6579 // OpenMP [2.5, Restrictions]
6580 // The num_threads expression must evaluate to a positive integer value.
6581 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6582 /*StrictlyPositive=*/true))
6585 return new (Context)
6586 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6589 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
6590 OpenMPClauseKind CKind,
6591 bool StrictlyPositive) {
6594 if (E->isValueDependent() || E->isTypeDependent() ||
6595 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
6597 llvm::APSInt Result;
6598 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6599 if (ICE.isInvalid())
6601 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6602 (!StrictlyPositive && !Result.isNonNegative())) {
6603 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
6604 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6605 << E->getSourceRange();
6608 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6609 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6610 << E->getSourceRange();
6613 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6614 DSAStack->setAssociatedLoops(Result.getExtValue());
6615 else if (CKind == OMPC_ordered)
6616 DSAStack->setAssociatedLoops(Result.getExtValue());
6620 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
6621 SourceLocation LParenLoc,
6622 SourceLocation EndLoc) {
6623 // OpenMP [2.8.1, simd construct, Description]
6624 // The parameter of the safelen clause must be a constant
6625 // positive integer expression.
6626 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
6627 if (Safelen.isInvalid())
6629 return new (Context)
6630 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
6633 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
6634 SourceLocation LParenLoc,
6635 SourceLocation EndLoc) {
6636 // OpenMP [2.8.1, simd construct, Description]
6637 // The parameter of the simdlen clause must be a constant
6638 // positive integer expression.
6639 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
6640 if (Simdlen.isInvalid())
6642 return new (Context)
6643 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
6646 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6647 SourceLocation StartLoc,
6648 SourceLocation LParenLoc,
6649 SourceLocation EndLoc) {
6650 // OpenMP [2.7.1, loop construct, Description]
6651 // OpenMP [2.8.1, simd construct, Description]
6652 // OpenMP [2.9.6, distribute construct, Description]
6653 // The parameter of the collapse clause must be a constant
6654 // positive integer expression.
6655 ExprResult NumForLoopsResult =
6656 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6657 if (NumForLoopsResult.isInvalid())
6659 return new (Context)
6660 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
6663 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6664 SourceLocation EndLoc,
6665 SourceLocation LParenLoc,
6666 Expr *NumForLoops) {
6667 // OpenMP [2.7.1, loop construct, Description]
6668 // OpenMP [2.8.1, simd construct, Description]
6669 // OpenMP [2.9.6, distribute construct, Description]
6670 // The parameter of the ordered clause must be a constant
6671 // positive integer expression if any.
6672 if (NumForLoops && LParenLoc.isValid()) {
6673 ExprResult NumForLoopsResult =
6674 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
6675 if (NumForLoopsResult.isInvalid())
6677 NumForLoops = NumForLoopsResult.get();
6679 NumForLoops = nullptr;
6680 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
6681 return new (Context)
6682 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6685 OMPClause *Sema::ActOnOpenMPSimpleClause(
6686 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6687 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
6688 OMPClause *Res = nullptr;
6692 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
6693 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
6695 case OMPC_proc_bind:
6696 Res = ActOnOpenMPProcBindClause(
6697 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
6702 case OMPC_num_threads:
6708 case OMPC_firstprivate:
6709 case OMPC_lastprivate:
6711 case OMPC_reduction:
6715 case OMPC_copyprivate:
6719 case OMPC_mergeable:
6720 case OMPC_threadprivate:
6732 case OMPC_num_teams:
6733 case OMPC_thread_limit:
6735 case OMPC_grainsize:
6737 case OMPC_num_tasks:
6739 case OMPC_dist_schedule:
6740 case OMPC_defaultmap:
6745 case OMPC_use_device_ptr:
6746 case OMPC_is_device_ptr:
6747 llvm_unreachable("Clause is not allowed.");
6753 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
6754 ArrayRef<unsigned> Exclude = llvm::None) {
6756 unsigned Bound = Last >= 2 ? Last - 2 : 0;
6757 unsigned Skipped = Exclude.size();
6758 auto S = Exclude.begin(), E = Exclude.end();
6759 for (unsigned i = First; i < Last; ++i) {
6760 if (std::find(S, E, i) != E) {
6765 Values += getOpenMPSimpleClauseTypeName(K, i);
6767 if (i == Bound - Skipped)
6769 else if (i != Bound + 1 - Skipped)
6775 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6776 SourceLocation KindKwLoc,
6777 SourceLocation StartLoc,
6778 SourceLocation LParenLoc,
6779 SourceLocation EndLoc) {
6780 if (Kind == OMPC_DEFAULT_unknown) {
6781 static_assert(OMPC_DEFAULT_unknown > 0,
6782 "OMPC_DEFAULT_unknown not greater than 0");
6783 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
6784 << getListOfPossibleValues(OMPC_default, /*First=*/0,
6785 /*Last=*/OMPC_DEFAULT_unknown)
6786 << getOpenMPClauseName(OMPC_default);
6790 case OMPC_DEFAULT_none:
6791 DSAStack->setDefaultDSANone(KindKwLoc);
6793 case OMPC_DEFAULT_shared:
6794 DSAStack->setDefaultDSAShared(KindKwLoc);
6796 case OMPC_DEFAULT_unknown:
6797 llvm_unreachable("Clause kind is not allowed.");
6800 return new (Context)
6801 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
6804 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6805 SourceLocation KindKwLoc,
6806 SourceLocation StartLoc,
6807 SourceLocation LParenLoc,
6808 SourceLocation EndLoc) {
6809 if (Kind == OMPC_PROC_BIND_unknown) {
6810 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
6811 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6812 /*Last=*/OMPC_PROC_BIND_unknown)
6813 << getOpenMPClauseName(OMPC_proc_bind);
6816 return new (Context)
6817 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
6820 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
6821 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
6822 SourceLocation StartLoc, SourceLocation LParenLoc,
6823 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
6824 SourceLocation EndLoc) {
6825 OMPClause *Res = nullptr;
6828 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
6829 assert(Argument.size() == NumberOfElements &&
6830 ArgumentLoc.size() == NumberOfElements);
6831 Res = ActOnOpenMPScheduleClause(
6832 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
6833 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
6834 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
6835 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
6836 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
6839 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
6840 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
6841 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
6844 case OMPC_dist_schedule:
6845 Res = ActOnOpenMPDistScheduleClause(
6846 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
6847 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
6849 case OMPC_defaultmap:
6850 enum { Modifier, DefaultmapKind };
6851 Res = ActOnOpenMPDefaultmapClause(
6852 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
6853 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
6854 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
6858 case OMPC_num_threads:
6863 case OMPC_proc_bind:
6865 case OMPC_firstprivate:
6866 case OMPC_lastprivate:
6868 case OMPC_reduction:
6872 case OMPC_copyprivate:
6876 case OMPC_mergeable:
6877 case OMPC_threadprivate:
6889 case OMPC_num_teams:
6890 case OMPC_thread_limit:
6892 case OMPC_grainsize:
6894 case OMPC_num_tasks:
6900 case OMPC_use_device_ptr:
6901 case OMPC_is_device_ptr:
6902 llvm_unreachable("Clause is not allowed.");
6907 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
6908 OpenMPScheduleClauseModifier M2,
6909 SourceLocation M1Loc, SourceLocation M2Loc) {
6910 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
6911 SmallVector<unsigned, 2> Excluded;
6912 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
6913 Excluded.push_back(M2);
6914 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
6915 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
6916 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
6917 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
6918 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
6919 << getListOfPossibleValues(OMPC_schedule,
6920 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
6921 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6923 << getOpenMPClauseName(OMPC_schedule);
6929 OMPClause *Sema::ActOnOpenMPScheduleClause(
6930 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
6931 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
6932 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
6933 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
6934 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
6935 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
6937 // OpenMP, 2.7.1, Loop Construct, Restrictions
6938 // Either the monotonic modifier or the nonmonotonic modifier can be specified
6940 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
6941 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
6942 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
6943 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
6944 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
6945 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
6946 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
6947 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
6950 if (Kind == OMPC_SCHEDULE_unknown) {
6952 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
6953 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
6954 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6955 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6958 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6959 /*Last=*/OMPC_SCHEDULE_unknown);
6961 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
6962 << Values << getOpenMPClauseName(OMPC_schedule);
6965 // OpenMP, 2.7.1, Loop Construct, Restrictions
6966 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
6967 // schedule(guided).
6968 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
6969 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
6970 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
6971 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
6972 diag::err_omp_schedule_nonmonotonic_static);
6975 Expr *ValExpr = ChunkSize;
6976 Stmt *HelperValStmt = nullptr;
6978 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
6979 !ChunkSize->isInstantiationDependent() &&
6980 !ChunkSize->containsUnexpandedParameterPack()) {
6981 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
6983 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
6984 if (Val.isInvalid())
6987 ValExpr = Val.get();
6989 // OpenMP [2.7.1, Restrictions]
6990 // chunk_size must be a loop invariant integer expression with a positive
6992 llvm::APSInt Result;
6993 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
6994 if (Result.isSigned() && !Result.isStrictlyPositive()) {
6995 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
6996 << "schedule" << 1 << ChunkSize->getSourceRange();
6999 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7000 !CurContext->isDependentContext()) {
7001 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7002 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7003 HelperValStmt = buildPreInits(Context, Captures);
7008 return new (Context)
7009 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
7010 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
7013 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7014 SourceLocation StartLoc,
7015 SourceLocation EndLoc) {
7016 OMPClause *Res = nullptr;
7019 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7022 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7025 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7027 case OMPC_mergeable:
7028 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7031 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7034 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7037 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7040 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7043 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7046 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7049 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7052 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7056 case OMPC_num_threads:
7062 case OMPC_firstprivate:
7063 case OMPC_lastprivate:
7065 case OMPC_reduction:
7069 case OMPC_copyprivate:
7071 case OMPC_proc_bind:
7072 case OMPC_threadprivate:
7077 case OMPC_num_teams:
7078 case OMPC_thread_limit:
7080 case OMPC_grainsize:
7081 case OMPC_num_tasks:
7083 case OMPC_dist_schedule:
7084 case OMPC_defaultmap:
7089 case OMPC_use_device_ptr:
7090 case OMPC_is_device_ptr:
7091 llvm_unreachable("Clause is not allowed.");
7096 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7097 SourceLocation EndLoc) {
7098 DSAStack->setNowaitRegion();
7099 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7102 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7103 SourceLocation EndLoc) {
7104 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7107 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7108 SourceLocation EndLoc) {
7109 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7112 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7113 SourceLocation EndLoc) {
7114 return new (Context) OMPReadClause(StartLoc, EndLoc);
7117 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7118 SourceLocation EndLoc) {
7119 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7122 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7123 SourceLocation EndLoc) {
7124 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7127 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7128 SourceLocation EndLoc) {
7129 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7132 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7133 SourceLocation EndLoc) {
7134 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7137 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7138 SourceLocation EndLoc) {
7139 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7142 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7143 SourceLocation EndLoc) {
7144 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7147 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7148 SourceLocation EndLoc) {
7149 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7152 OMPClause *Sema::ActOnOpenMPVarListClause(
7153 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7154 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7155 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
7156 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
7157 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7158 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7159 SourceLocation DepLinMapLoc) {
7160 OMPClause *Res = nullptr;
7163 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7165 case OMPC_firstprivate:
7166 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7168 case OMPC_lastprivate:
7169 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7172 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7174 case OMPC_reduction:
7175 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7176 EndLoc, ReductionIdScopeSpec, ReductionId);
7179 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
7180 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
7183 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7187 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7189 case OMPC_copyprivate:
7190 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7193 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7196 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
7197 StartLoc, LParenLoc, EndLoc);
7200 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7201 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7205 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7208 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7210 case OMPC_use_device_ptr:
7211 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7213 case OMPC_is_device_ptr:
7214 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7218 case OMPC_num_threads:
7223 case OMPC_proc_bind:
7228 case OMPC_mergeable:
7229 case OMPC_threadprivate:
7238 case OMPC_num_teams:
7239 case OMPC_thread_limit:
7241 case OMPC_grainsize:
7243 case OMPC_num_tasks:
7245 case OMPC_dist_schedule:
7246 case OMPC_defaultmap:
7249 llvm_unreachable("Clause is not allowed.");
7254 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
7255 ExprObjectKind OK, SourceLocation Loc) {
7256 ExprResult Res = BuildDeclRefExpr(
7257 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7258 if (!Res.isUsable())
7260 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7261 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7262 if (!Res.isUsable())
7265 if (VK != VK_LValue && Res.get()->isGLValue()) {
7266 Res = DefaultLvalueConversion(Res.get());
7267 if (!Res.isUsable())
7273 static std::pair<ValueDecl *, bool>
7274 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7275 SourceRange &ERange, bool AllowArraySection = false) {
7276 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7277 RefExpr->containsUnexpandedParameterPack())
7278 return std::make_pair(nullptr, true);
7280 // OpenMP [3.1, C/C++]
7281 // A list item is a variable name.
7282 // OpenMP [2.9.3.3, Restrictions, p.1]
7283 // A variable that is part of another variable (as an array or
7284 // structure element) cannot appear in a private clause.
7285 RefExpr = RefExpr->IgnoreParens();
7290 } IsArrayExpr = NoArrayExpr;
7291 if (AllowArraySection) {
7292 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7293 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7294 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7295 Base = TempASE->getBase()->IgnoreParenImpCasts();
7297 IsArrayExpr = ArraySubscript;
7298 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7299 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7300 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7301 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7302 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7303 Base = TempASE->getBase()->IgnoreParenImpCasts();
7305 IsArrayExpr = OMPArraySection;
7308 ELoc = RefExpr->getExprLoc();
7309 ERange = RefExpr->getSourceRange();
7310 RefExpr = RefExpr->IgnoreParenImpCasts();
7311 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7312 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7313 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7314 (S.getCurrentThisType().isNull() || !ME ||
7315 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7316 !isa<FieldDecl>(ME->getMemberDecl()))) {
7317 if (IsArrayExpr != NoArrayExpr)
7318 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7323 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7324 : diag::err_omp_expected_var_name_member_expr)
7325 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7327 return std::make_pair(nullptr, false);
7329 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7332 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7333 SourceLocation StartLoc,
7334 SourceLocation LParenLoc,
7335 SourceLocation EndLoc) {
7336 SmallVector<Expr *, 8> Vars;
7337 SmallVector<Expr *, 8> PrivateCopies;
7338 for (auto &RefExpr : VarList) {
7339 assert(RefExpr && "NULL expr in OpenMP private clause.");
7340 SourceLocation ELoc;
7342 Expr *SimpleRefExpr = RefExpr;
7343 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7345 // It will be analyzed later.
7346 Vars.push_back(RefExpr);
7347 PrivateCopies.push_back(nullptr);
7349 ValueDecl *D = Res.first;
7353 QualType Type = D->getType();
7354 auto *VD = dyn_cast<VarDecl>(D);
7356 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7357 // A variable that appears in a private clause must not have an incomplete
7358 // type or a reference type.
7359 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
7361 Type = Type.getNonReferenceType();
7363 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7365 // Variables with the predetermined data-sharing attributes may not be
7366 // listed in data-sharing attributes clauses, except for the cases
7367 // listed below. For these exceptions only, listing a predetermined
7368 // variable in a data-sharing attribute clause is allowed and overrides
7369 // the variable's predetermined data-sharing attributes.
7370 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7371 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
7372 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7373 << getOpenMPClauseName(OMPC_private);
7374 ReportOriginalDSA(*this, DSAStack, D, DVar);
7378 auto CurrDir = DSAStack->getCurrentDirective();
7379 // Variably modified types are not supported for tasks.
7380 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
7381 isOpenMPTaskingDirective(CurrDir)) {
7382 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7383 << getOpenMPClauseName(OMPC_private) << Type
7384 << getOpenMPDirectiveName(CurrDir);
7387 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7388 Diag(D->getLocation(),
7389 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7394 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7395 // A list item cannot appear in both a map clause and a data-sharing
7396 // attribute clause on the same construct
7397 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
7398 CurrDir == OMPD_target_teams ||
7399 CurrDir == OMPD_target_teams_distribute ||
7400 CurrDir == OMPD_target_teams_distribute_parallel_for) {
7401 OpenMPClauseKind ConflictKind;
7402 if (DSAStack->checkMappableExprComponentListsForDecl(
7403 VD, /*CurrentRegionOnly=*/true,
7404 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7405 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7406 ConflictKind = WhereFoundClauseKind;
7409 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
7410 << getOpenMPClauseName(OMPC_private)
7411 << getOpenMPClauseName(ConflictKind)
7412 << getOpenMPDirectiveName(CurrDir);
7413 ReportOriginalDSA(*this, DSAStack, D, DVar);
7418 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7419 // A variable of class type (or array thereof) that appears in a private
7420 // clause requires an accessible, unambiguous default constructor for the
7422 // Generate helper private variable and initialize it with the default
7423 // value. The address of the original variable is replaced by the address of
7424 // the new private variable in CodeGen. This new variable is not added to
7425 // IdResolver, so the code in the OpenMP region uses original variable for
7426 // proper diagnostics.
7427 Type = Type.getUnqualifiedType();
7428 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7429 D->hasAttrs() ? &D->getAttrs() : nullptr);
7430 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
7431 if (VDPrivate->isInvalidDecl())
7433 auto VDPrivateRefExpr = buildDeclRefExpr(
7434 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
7436 DeclRefExpr *Ref = nullptr;
7437 if (!VD && !CurContext->isDependentContext())
7438 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
7439 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
7440 Vars.push_back((VD || CurContext->isDependentContext())
7441 ? RefExpr->IgnoreParens()
7443 PrivateCopies.push_back(VDPrivateRefExpr);
7449 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7454 class DiagsUninitializedSeveretyRAII {
7456 DiagnosticsEngine &Diags;
7457 SourceLocation SavedLoc;
7461 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7463 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7465 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7466 /*Map*/ diag::Severity::Ignored, Loc);
7469 ~DiagsUninitializedSeveretyRAII() {
7471 Diags.popMappings(SavedLoc);
7476 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7477 SourceLocation StartLoc,
7478 SourceLocation LParenLoc,
7479 SourceLocation EndLoc) {
7480 SmallVector<Expr *, 8> Vars;
7481 SmallVector<Expr *, 8> PrivateCopies;
7482 SmallVector<Expr *, 8> Inits;
7483 SmallVector<Decl *, 4> ExprCaptures;
7484 bool IsImplicitClause =
7485 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7486 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7488 for (auto &RefExpr : VarList) {
7489 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
7490 SourceLocation ELoc;
7492 Expr *SimpleRefExpr = RefExpr;
7493 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7495 // It will be analyzed later.
7496 Vars.push_back(RefExpr);
7497 PrivateCopies.push_back(nullptr);
7498 Inits.push_back(nullptr);
7500 ValueDecl *D = Res.first;
7504 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
7505 QualType Type = D->getType();
7506 auto *VD = dyn_cast<VarDecl>(D);
7508 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7509 // A variable that appears in a private clause must not have an incomplete
7510 // type or a reference type.
7511 if (RequireCompleteType(ELoc, Type,
7512 diag::err_omp_firstprivate_incomplete_type))
7514 Type = Type.getNonReferenceType();
7516 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7517 // A variable of class type (or array thereof) that appears in a private
7518 // clause requires an accessible, unambiguous copy constructor for the
7520 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
7522 // If an implicit firstprivate variable found it was checked already.
7523 DSAStackTy::DSAVarData TopDVar;
7524 if (!IsImplicitClause) {
7525 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7527 bool IsConstant = ElemType.isConstant(Context);
7528 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7529 // A list item that specifies a given variable may not appear in more
7530 // than one clause on the same directive, except that a variable may be
7531 // specified in both firstprivate and lastprivate clauses.
7532 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
7533 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
7534 Diag(ELoc, diag::err_omp_wrong_dsa)
7535 << getOpenMPClauseName(DVar.CKind)
7536 << getOpenMPClauseName(OMPC_firstprivate);
7537 ReportOriginalDSA(*this, DSAStack, D, DVar);
7541 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7543 // Variables with the predetermined data-sharing attributes may not be
7544 // listed in data-sharing attributes clauses, except for the cases
7545 // listed below. For these exceptions only, listing a predetermined
7546 // variable in a data-sharing attribute clause is allowed and overrides
7547 // the variable's predetermined data-sharing attributes.
7548 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7549 // in a Construct, C/C++, p.2]
7550 // Variables with const-qualified type having no mutable member may be
7551 // listed in a firstprivate clause, even if they are static data members.
7552 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
7553 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7554 Diag(ELoc, diag::err_omp_wrong_dsa)
7555 << getOpenMPClauseName(DVar.CKind)
7556 << getOpenMPClauseName(OMPC_firstprivate);
7557 ReportOriginalDSA(*this, DSAStack, D, DVar);
7561 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7562 // OpenMP [2.9.3.4, Restrictions, p.2]
7563 // A list item that is private within a parallel region must not appear
7564 // in a firstprivate clause on a worksharing construct if any of the
7565 // worksharing regions arising from the worksharing construct ever bind
7566 // to any of the parallel regions arising from the parallel construct.
7567 if (isOpenMPWorksharingDirective(CurrDir) &&
7568 !isOpenMPParallelDirective(CurrDir) &&
7569 !isOpenMPTeamsDirective(CurrDir)) {
7570 DVar = DSAStack->getImplicitDSA(D, true);
7571 if (DVar.CKind != OMPC_shared &&
7572 (isOpenMPParallelDirective(DVar.DKind) ||
7573 DVar.DKind == OMPD_unknown)) {
7574 Diag(ELoc, diag::err_omp_required_access)
7575 << getOpenMPClauseName(OMPC_firstprivate)
7576 << getOpenMPClauseName(OMPC_shared);
7577 ReportOriginalDSA(*this, DSAStack, D, DVar);
7581 // OpenMP [2.9.3.4, Restrictions, p.3]
7582 // A list item that appears in a reduction clause of a parallel construct
7583 // must not appear in a firstprivate clause on a worksharing or task
7584 // construct if any of the worksharing or task regions arising from the
7585 // worksharing or task construct ever bind to any of the parallel regions
7586 // arising from the parallel construct.
7587 // OpenMP [2.9.3.4, Restrictions, p.4]
7588 // A list item that appears in a reduction clause in worksharing
7589 // construct must not appear in a firstprivate clause in a task construct
7590 // encountered during execution of any of the worksharing regions arising
7591 // from the worksharing construct.
7592 if (isOpenMPTaskingDirective(CurrDir)) {
7593 DVar = DSAStack->hasInnermostDSA(
7594 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7595 [](OpenMPDirectiveKind K) -> bool {
7596 return isOpenMPParallelDirective(K) ||
7597 isOpenMPWorksharingDirective(K);
7600 if (DVar.CKind == OMPC_reduction &&
7601 (isOpenMPParallelDirective(DVar.DKind) ||
7602 isOpenMPWorksharingDirective(DVar.DKind))) {
7603 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7604 << getOpenMPDirectiveName(DVar.DKind);
7605 ReportOriginalDSA(*this, DSAStack, D, DVar);
7610 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7611 // A list item that is private within a teams region must not appear in a
7612 // firstprivate clause on a distribute construct if any of the distribute
7613 // regions arising from the distribute construct ever bind to any of the
7614 // teams regions arising from the teams construct.
7615 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7616 // A list item that appears in a reduction clause of a teams construct
7617 // must not appear in a firstprivate clause on a distribute construct if
7618 // any of the distribute regions arising from the distribute construct
7619 // ever bind to any of the teams regions arising from the teams construct.
7620 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7621 // A list item may appear in a firstprivate or lastprivate clause but not
7623 if (CurrDir == OMPD_distribute) {
7624 DVar = DSAStack->hasInnermostDSA(
7625 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
7626 [](OpenMPDirectiveKind K) -> bool {
7627 return isOpenMPTeamsDirective(K);
7630 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7631 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
7632 ReportOriginalDSA(*this, DSAStack, D, DVar);
7635 DVar = DSAStack->hasInnermostDSA(
7636 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7637 [](OpenMPDirectiveKind K) -> bool {
7638 return isOpenMPTeamsDirective(K);
7641 if (DVar.CKind == OMPC_reduction &&
7642 isOpenMPTeamsDirective(DVar.DKind)) {
7643 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
7644 ReportOriginalDSA(*this, DSAStack, D, DVar);
7647 DVar = DSAStack->getTopDSA(D, false);
7648 if (DVar.CKind == OMPC_lastprivate) {
7649 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7650 ReportOriginalDSA(*this, DSAStack, D, DVar);
7654 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7655 // A list item cannot appear in both a map clause and a data-sharing
7656 // attribute clause on the same construct
7657 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
7658 CurrDir == OMPD_target_teams ||
7659 CurrDir == OMPD_target_teams_distribute ||
7660 CurrDir == OMPD_target_teams_distribute_parallel_for) {
7661 OpenMPClauseKind ConflictKind;
7662 if (DSAStack->checkMappableExprComponentListsForDecl(
7663 VD, /*CurrentRegionOnly=*/true,
7664 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7665 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7666 ConflictKind = WhereFoundClauseKind;
7669 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
7670 << getOpenMPClauseName(OMPC_firstprivate)
7671 << getOpenMPClauseName(ConflictKind)
7672 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7673 ReportOriginalDSA(*this, DSAStack, D, DVar);
7679 // Variably modified types are not supported for tasks.
7680 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
7681 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
7682 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7683 << getOpenMPClauseName(OMPC_firstprivate) << Type
7684 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7687 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7688 Diag(D->getLocation(),
7689 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7694 Type = Type.getUnqualifiedType();
7695 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7696 D->hasAttrs() ? &D->getAttrs() : nullptr);
7697 // Generate helper private variable and initialize it with the value of the
7698 // original variable. The address of the original variable is replaced by
7699 // the address of the new private variable in the CodeGen. This new variable
7700 // is not added to IdResolver, so the code in the OpenMP region uses
7701 // original variable for proper diagnostics and variable capturing.
7702 Expr *VDInitRefExpr = nullptr;
7703 // For arrays generate initializer for single element and replace it by the
7704 // original array element in CodeGen.
7705 if (Type->isArrayType()) {
7707 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
7708 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
7709 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
7710 ElemType = ElemType.getUnqualifiedType();
7711 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
7712 ".firstprivate.temp");
7713 InitializedEntity Entity =
7714 InitializedEntity::InitializeVariable(VDInitTemp);
7715 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
7717 InitializationSequence InitSeq(*this, Entity, Kind, Init);
7718 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
7719 if (Result.isInvalid())
7720 VDPrivate->setInvalidDecl();
7722 VDPrivate->setInit(Result.getAs<Expr>());
7723 // Remove temp variable declaration.
7724 Context.Deallocate(VDInitTemp);
7726 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
7727 ".firstprivate.temp");
7728 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
7729 RefExpr->getExprLoc());
7730 AddInitializerToDecl(VDPrivate,
7731 DefaultLvalueConversion(VDInitRefExpr).get(),
7732 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
7734 if (VDPrivate->isInvalidDecl()) {
7735 if (IsImplicitClause) {
7736 Diag(RefExpr->getExprLoc(),
7737 diag::note_omp_task_predetermined_firstprivate_here);
7741 CurContext->addDecl(VDPrivate);
7742 auto VDPrivateRefExpr = buildDeclRefExpr(
7743 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
7744 RefExpr->getExprLoc());
7745 DeclRefExpr *Ref = nullptr;
7746 if (!VD && !CurContext->isDependentContext()) {
7747 if (TopDVar.CKind == OMPC_lastprivate)
7748 Ref = TopDVar.PrivateCopy;
7750 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
7751 if (!IsOpenMPCapturedDecl(D))
7752 ExprCaptures.push_back(Ref->getDecl());
7755 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
7756 Vars.push_back((VD || CurContext->isDependentContext())
7757 ? RefExpr->IgnoreParens()
7759 PrivateCopies.push_back(VDPrivateRefExpr);
7760 Inits.push_back(VDInitRefExpr);
7766 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
7767 Vars, PrivateCopies, Inits,
7768 buildPreInits(Context, ExprCaptures));
7771 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7772 SourceLocation StartLoc,
7773 SourceLocation LParenLoc,
7774 SourceLocation EndLoc) {
7775 SmallVector<Expr *, 8> Vars;
7776 SmallVector<Expr *, 8> SrcExprs;
7777 SmallVector<Expr *, 8> DstExprs;
7778 SmallVector<Expr *, 8> AssignmentOps;
7779 SmallVector<Decl *, 4> ExprCaptures;
7780 SmallVector<Expr *, 4> ExprPostUpdates;
7781 for (auto &RefExpr : VarList) {
7782 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
7783 SourceLocation ELoc;
7785 Expr *SimpleRefExpr = RefExpr;
7786 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7788 // It will be analyzed later.
7789 Vars.push_back(RefExpr);
7790 SrcExprs.push_back(nullptr);
7791 DstExprs.push_back(nullptr);
7792 AssignmentOps.push_back(nullptr);
7794 ValueDecl *D = Res.first;
7798 QualType Type = D->getType();
7799 auto *VD = dyn_cast<VarDecl>(D);
7801 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
7802 // A variable that appears in a lastprivate clause must not have an
7803 // incomplete type or a reference type.
7804 if (RequireCompleteType(ELoc, Type,
7805 diag::err_omp_lastprivate_incomplete_type))
7807 Type = Type.getNonReferenceType();
7809 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
7811 // Variables with the predetermined data-sharing attributes may not be
7812 // listed in data-sharing attributes clauses, except for the cases
7814 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7815 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
7816 DVar.CKind != OMPC_firstprivate &&
7817 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
7818 Diag(ELoc, diag::err_omp_wrong_dsa)
7819 << getOpenMPClauseName(DVar.CKind)
7820 << getOpenMPClauseName(OMPC_lastprivate);
7821 ReportOriginalDSA(*this, DSAStack, D, DVar);
7825 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7826 // OpenMP [2.14.3.5, Restrictions, p.2]
7827 // A list item that is private within a parallel region, or that appears in
7828 // the reduction clause of a parallel construct, must not appear in a
7829 // lastprivate clause on a worksharing construct if any of the corresponding
7830 // worksharing regions ever binds to any of the corresponding parallel
7832 DSAStackTy::DSAVarData TopDVar = DVar;
7833 if (isOpenMPWorksharingDirective(CurrDir) &&
7834 !isOpenMPParallelDirective(CurrDir) &&
7835 !isOpenMPTeamsDirective(CurrDir)) {
7836 DVar = DSAStack->getImplicitDSA(D, true);
7837 if (DVar.CKind != OMPC_shared) {
7838 Diag(ELoc, diag::err_omp_required_access)
7839 << getOpenMPClauseName(OMPC_lastprivate)
7840 << getOpenMPClauseName(OMPC_shared);
7841 ReportOriginalDSA(*this, DSAStack, D, DVar);
7846 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7847 // A list item may appear in a firstprivate or lastprivate clause but not
7849 if (CurrDir == OMPD_distribute) {
7850 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7851 if (DVar.CKind == OMPC_firstprivate) {
7852 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7853 ReportOriginalDSA(*this, DSAStack, D, DVar);
7858 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
7859 // A variable of class type (or array thereof) that appears in a
7860 // lastprivate clause requires an accessible, unambiguous default
7861 // constructor for the class type, unless the list item is also specified
7862 // in a firstprivate clause.
7863 // A variable of class type (or array thereof) that appears in a
7864 // lastprivate clause requires an accessible, unambiguous copy assignment
7865 // operator for the class type.
7866 Type = Context.getBaseElementType(Type).getNonReferenceType();
7867 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
7868 Type.getUnqualifiedType(), ".lastprivate.src",
7869 D->hasAttrs() ? &D->getAttrs() : nullptr);
7870 auto *PseudoSrcExpr =
7871 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
7873 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
7874 D->hasAttrs() ? &D->getAttrs() : nullptr);
7875 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
7876 // For arrays generate assignment operation for single element and replace
7877 // it by the original array element in CodeGen.
7878 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
7879 PseudoDstExpr, PseudoSrcExpr);
7880 if (AssignmentOp.isInvalid())
7882 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
7883 /*DiscardedValue=*/true);
7884 if (AssignmentOp.isInvalid())
7887 DeclRefExpr *Ref = nullptr;
7888 if (!VD && !CurContext->isDependentContext()) {
7889 if (TopDVar.CKind == OMPC_firstprivate)
7890 Ref = TopDVar.PrivateCopy;
7892 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
7893 if (!IsOpenMPCapturedDecl(D))
7894 ExprCaptures.push_back(Ref->getDecl());
7896 if (TopDVar.CKind == OMPC_firstprivate ||
7897 (!IsOpenMPCapturedDecl(D) &&
7898 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
7899 ExprResult RefRes = DefaultLvalueConversion(Ref);
7900 if (!RefRes.isUsable())
7902 ExprResult PostUpdateRes =
7903 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
7905 if (!PostUpdateRes.isUsable())
7907 ExprPostUpdates.push_back(
7908 IgnoredValueConversions(PostUpdateRes.get()).get());
7911 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
7912 Vars.push_back((VD || CurContext->isDependentContext())
7913 ? RefExpr->IgnoreParens()
7915 SrcExprs.push_back(PseudoSrcExpr);
7916 DstExprs.push_back(PseudoDstExpr);
7917 AssignmentOps.push_back(AssignmentOp.get());
7923 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
7924 Vars, SrcExprs, DstExprs, AssignmentOps,
7925 buildPreInits(Context, ExprCaptures),
7926 buildPostUpdate(*this, ExprPostUpdates));
7929 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7930 SourceLocation StartLoc,
7931 SourceLocation LParenLoc,
7932 SourceLocation EndLoc) {
7933 SmallVector<Expr *, 8> Vars;
7934 for (auto &RefExpr : VarList) {
7935 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
7936 SourceLocation ELoc;
7938 Expr *SimpleRefExpr = RefExpr;
7939 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7941 // It will be analyzed later.
7942 Vars.push_back(RefExpr);
7944 ValueDecl *D = Res.first;
7948 auto *VD = dyn_cast<VarDecl>(D);
7949 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7951 // Variables with the predetermined data-sharing attributes may not be
7952 // listed in data-sharing attributes clauses, except for the cases
7953 // listed below. For these exceptions only, listing a predetermined
7954 // variable in a data-sharing attribute clause is allowed and overrides
7955 // the variable's predetermined data-sharing attributes.
7956 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7957 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
7959 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7960 << getOpenMPClauseName(OMPC_shared);
7961 ReportOriginalDSA(*this, DSAStack, D, DVar);
7965 DeclRefExpr *Ref = nullptr;
7966 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
7967 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
7968 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
7969 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
7970 ? RefExpr->IgnoreParens()
7977 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
7981 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
7985 bool VisitDeclRefExpr(DeclRefExpr *E) {
7986 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
7987 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
7988 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
7990 if (DVar.CKind != OMPC_unknown)
7992 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
7993 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
7995 if (DVarPrivate.CKind != OMPC_unknown)
8001 bool VisitStmt(Stmt *S) {
8002 for (auto Child : S->children()) {
8003 if (Child && Visit(Child))
8008 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
8013 // Transform MemberExpression for specified FieldDecl of current class to
8014 // DeclRefExpr to specified OMPCapturedExprDecl.
8015 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8016 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8018 DeclRefExpr *CapturedExpr;
8021 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8022 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8024 ExprResult TransformMemberExpr(MemberExpr *E) {
8025 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8026 E->getMemberDecl() == Field) {
8027 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
8028 return CapturedExpr;
8030 return BaseTransform::TransformMemberExpr(E);
8032 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8036 template <typename T>
8037 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8038 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8039 for (auto &Set : Lookups) {
8040 for (auto *D : Set) {
8041 if (auto Res = Gen(cast<ValueDecl>(D)))
8049 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8050 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8051 const DeclarationNameInfo &ReductionId, QualType Ty,
8052 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8053 if (ReductionIdScopeSpec.isInvalid())
8055 SmallVector<UnresolvedSet<8>, 4> Lookups;
8057 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8058 Lookup.suppressDiagnostics();
8059 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8060 auto *D = Lookup.getRepresentativeDecl();
8063 } while (S && !S->isDeclScope(D));
8066 Lookups.push_back(UnresolvedSet<8>());
8067 Lookups.back().append(Lookup.begin(), Lookup.end());
8070 } else if (auto *ULE =
8071 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8072 Lookups.push_back(UnresolvedSet<8>());
8073 Decl *PrevD = nullptr;
8074 for (auto *D : ULE->decls()) {
8076 Lookups.push_back(UnresolvedSet<8>());
8077 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8078 Lookups.back().addDecl(DRD);
8082 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8083 Ty->containsUnexpandedParameterPack() ||
8084 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8085 return !D->isInvalidDecl() &&
8086 (D->getType()->isDependentType() ||
8087 D->getType()->isInstantiationDependentType() ||
8088 D->getType()->containsUnexpandedParameterPack());
8090 UnresolvedSet<8> ResSet;
8091 for (auto &Set : Lookups) {
8092 ResSet.append(Set.begin(), Set.end());
8093 // The last item marks the end of all declarations at the specified scope.
8094 ResSet.addDecl(Set[Set.size() - 1]);
8096 return UnresolvedLookupExpr::Create(
8097 SemaRef.Context, /*NamingClass=*/nullptr,
8098 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8099 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8101 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8102 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8103 if (!D->isInvalidDecl() &&
8104 SemaRef.Context.hasSameType(D->getType(), Ty))
8108 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8109 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8110 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8111 if (!D->isInvalidDecl() &&
8112 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8113 !Ty.isMoreQualifiedThan(D->getType()))
8117 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8118 /*DetectVirtual=*/false);
8119 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8120 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8121 VD->getType().getUnqualifiedType()))) {
8122 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8124 Sema::AR_inaccessible) {
8125 SemaRef.BuildBasePathArray(Paths, BasePath);
8126 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8131 if (ReductionIdScopeSpec.isSet()) {
8132 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8138 OMPClause *Sema::ActOnOpenMPReductionClause(
8139 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8140 SourceLocation ColonLoc, SourceLocation EndLoc,
8141 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8142 ArrayRef<Expr *> UnresolvedReductions) {
8143 auto DN = ReductionId.getName();
8144 auto OOK = DN.getCXXOverloadedOperator();
8145 BinaryOperatorKind BOK = BO_Comma;
8147 // OpenMP [2.14.3.6, reduction clause]
8149 // reduction-identifier is either an identifier or one of the following
8150 // operators: +, -, *, &, |, ^, && and ||
8152 // reduction-identifier is either an id-expression or one of the following
8153 // operators: +, -, *, &, |, ^, && and ||
8154 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8181 case OO_Array_Delete:
8190 case OO_GreaterEqual:
8195 case OO_PercentEqual:
8200 case OO_GreaterGreater:
8201 case OO_LessLessEqual:
8202 case OO_GreaterGreaterEqual:
8204 case OO_ExclaimEqual:
8212 case OO_Conditional:
8214 case NUM_OVERLOADED_OPERATORS:
8215 llvm_unreachable("Unexpected reduction identifier");
8217 if (auto II = DN.getAsIdentifierInfo()) {
8218 if (II->isStr("max"))
8220 else if (II->isStr("min"))
8225 SourceRange ReductionIdRange;
8226 if (ReductionIdScopeSpec.isValid())
8227 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
8228 ReductionIdRange.setEnd(ReductionId.getEndLoc());
8230 SmallVector<Expr *, 8> Vars;
8231 SmallVector<Expr *, 8> Privates;
8232 SmallVector<Expr *, 8> LHSs;
8233 SmallVector<Expr *, 8> RHSs;
8234 SmallVector<Expr *, 8> ReductionOps;
8235 SmallVector<Decl *, 4> ExprCaptures;
8236 SmallVector<Expr *, 4> ExprPostUpdates;
8237 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8238 bool FirstIter = true;
8239 for (auto RefExpr : VarList) {
8240 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
8241 // OpenMP [2.1, C/C++]
8242 // A list item is a variable or array section, subject to the restrictions
8243 // specified in Section 2.4 on page 42 and in each of the sections
8244 // describing clauses and directives for which a list appears.
8245 // OpenMP [2.14.3.3, Restrictions, p.1]
8246 // A variable that is part of another variable (as an array or
8247 // structure element) cannot appear in a private clause.
8248 if (!FirstIter && IR != ER)
8251 SourceLocation ELoc;
8253 Expr *SimpleRefExpr = RefExpr;
8254 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8255 /*AllowArraySection=*/true);
8257 // It will be analyzed later.
8258 Vars.push_back(RefExpr);
8259 Privates.push_back(nullptr);
8260 LHSs.push_back(nullptr);
8261 RHSs.push_back(nullptr);
8262 // Try to find 'declare reduction' corresponding construct before using
8263 // builtin/overloaded operators.
8264 QualType Type = Context.DependentTy;
8265 CXXCastPath BasePath;
8266 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8267 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8268 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8269 if (CurContext->isDependentContext() &&
8270 (DeclareReductionRef.isUnset() ||
8271 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8272 ReductionOps.push_back(DeclareReductionRef.get());
8274 ReductionOps.push_back(nullptr);
8276 ValueDecl *D = Res.first;
8281 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8282 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8284 Type = ASE->getType().getNonReferenceType();
8286 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8287 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8288 Type = ATy->getElementType();
8290 Type = BaseType->getPointeeType();
8291 Type = Type.getNonReferenceType();
8293 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8294 auto *VD = dyn_cast<VarDecl>(D);
8296 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8297 // A variable that appears in a private clause must not have an incomplete
8298 // type or a reference type.
8299 if (RequireCompleteType(ELoc, Type,
8300 diag::err_omp_reduction_incomplete_type))
8302 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8303 // A list item that appears in a reduction clause must not be
8305 if (Type.getNonReferenceType().isConstant(Context)) {
8306 Diag(ELoc, diag::err_omp_const_reduction_list_item)
8307 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
8308 if (!ASE && !OASE) {
8309 bool IsDecl = !VD ||
8310 VD->isThisDeclarationADefinition(Context) ==
8311 VarDecl::DeclarationOnly;
8312 Diag(D->getLocation(),
8313 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8318 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8319 // If a list-item is a reference type then it must bind to the same object
8320 // for all threads of the team.
8321 if (!ASE && !OASE && VD) {
8322 VarDecl *VDDef = VD->getDefinition();
8323 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
8324 DSARefChecker Check(DSAStack);
8325 if (Check.Visit(VDDef->getInit())) {
8326 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8327 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8333 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8335 // Variables with the predetermined data-sharing attributes may not be
8336 // listed in data-sharing attributes clauses, except for the cases
8337 // listed below. For these exceptions only, listing a predetermined
8338 // variable in a data-sharing attribute clause is allowed and overrides
8339 // the variable's predetermined data-sharing attributes.
8340 // OpenMP [2.14.3.6, Restrictions, p.3]
8341 // Any number of reduction clauses can be specified on the directive,
8342 // but a list item can appear only once in the reduction clauses for that
8344 DSAStackTy::DSAVarData DVar;
8345 DVar = DSAStack->getTopDSA(D, false);
8346 if (DVar.CKind == OMPC_reduction) {
8347 Diag(ELoc, diag::err_omp_once_referenced)
8348 << getOpenMPClauseName(OMPC_reduction);
8350 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
8351 } else if (DVar.CKind != OMPC_unknown) {
8352 Diag(ELoc, diag::err_omp_wrong_dsa)
8353 << getOpenMPClauseName(DVar.CKind)
8354 << getOpenMPClauseName(OMPC_reduction);
8355 ReportOriginalDSA(*this, DSAStack, D, DVar);
8359 // OpenMP [2.14.3.6, Restrictions, p.1]
8360 // A list item that appears in a reduction clause of a worksharing
8361 // construct must be shared in the parallel regions to which any of the
8362 // worksharing regions arising from the worksharing construct bind.
8363 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8364 if (isOpenMPWorksharingDirective(CurrDir) &&
8365 !isOpenMPParallelDirective(CurrDir) &&
8366 !isOpenMPTeamsDirective(CurrDir)) {
8367 DVar = DSAStack->getImplicitDSA(D, true);
8368 if (DVar.CKind != OMPC_shared) {
8369 Diag(ELoc, diag::err_omp_required_access)
8370 << getOpenMPClauseName(OMPC_reduction)
8371 << getOpenMPClauseName(OMPC_shared);
8372 ReportOriginalDSA(*this, DSAStack, D, DVar);
8377 // Try to find 'declare reduction' corresponding construct before using
8378 // builtin/overloaded operators.
8379 CXXCastPath BasePath;
8380 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8381 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8382 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8383 if (DeclareReductionRef.isInvalid())
8385 if (CurContext->isDependentContext() &&
8386 (DeclareReductionRef.isUnset() ||
8387 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8388 Vars.push_back(RefExpr);
8389 Privates.push_back(nullptr);
8390 LHSs.push_back(nullptr);
8391 RHSs.push_back(nullptr);
8392 ReductionOps.push_back(DeclareReductionRef.get());
8395 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8396 // Not allowed reduction identifier is found.
8397 Diag(ReductionId.getLocStart(),
8398 diag::err_omp_unknown_reduction_identifier)
8399 << Type << ReductionIdRange;
8403 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8404 // The type of a list item that appears in a reduction clause must be valid
8405 // for the reduction-identifier. For a max or min reduction in C, the type
8406 // of the list item must be an allowed arithmetic data type: char, int,
8407 // float, double, or _Bool, possibly modified with long, short, signed, or
8408 // unsigned. For a max or min reduction in C++, the type of the list item
8409 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8410 // double, or bool, possibly modified with long, short, signed, or unsigned.
8411 if (DeclareReductionRef.isUnset()) {
8412 if ((BOK == BO_GT || BOK == BO_LT) &&
8413 !(Type->isScalarType() ||
8414 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8415 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8416 << getLangOpts().CPlusPlus;
8417 if (!ASE && !OASE) {
8418 bool IsDecl = !VD ||
8419 VD->isThisDeclarationADefinition(Context) ==
8420 VarDecl::DeclarationOnly;
8421 Diag(D->getLocation(),
8422 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8427 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8428 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8429 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8430 if (!ASE && !OASE) {
8431 bool IsDecl = !VD ||
8432 VD->isThisDeclarationADefinition(Context) ==
8433 VarDecl::DeclarationOnly;
8434 Diag(D->getLocation(),
8435 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8442 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
8443 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
8444 D->hasAttrs() ? &D->getAttrs() : nullptr);
8445 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8446 D->hasAttrs() ? &D->getAttrs() : nullptr);
8447 auto PrivateTy = Type;
8450 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
8451 // For arrays/array sections only:
8452 // Create pseudo array type for private copy. The size for this array will
8453 // be generated during codegen.
8454 // For array subscripts or single variables Private Ty is the same as Type
8455 // (type of the variable or single array element).
8456 PrivateTy = Context.getVariableArrayType(
8457 Type, new (Context) OpaqueValueExpr(SourceLocation(),
8458 Context.getSizeType(), VK_RValue),
8459 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
8460 } else if (!ASE && !OASE &&
8461 Context.getAsArrayType(D->getType().getNonReferenceType()))
8462 PrivateTy = D->getType().getNonReferenceType();
8464 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8465 D->hasAttrs() ? &D->getAttrs() : nullptr);
8466 // Add initializer for private variable.
8467 Expr *Init = nullptr;
8468 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8469 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8470 if (DeclareReductionRef.isUsable()) {
8471 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8472 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8473 if (DRD->getInitializer()) {
8475 RHSVD->setInit(DRDRef);
8476 RHSVD->setInitStyle(VarDecl::CallInit);
8484 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8485 if (Type->isScalarType() || Type->isAnyComplexType())
8486 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8490 if (Type->isScalarType() || Type->isAnyComplexType()) {
8491 // '*' and '&&' reduction ops - initializer is '1'.
8492 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
8496 // '&' reduction op - initializer is '~0'.
8497 QualType OrigType = Type;
8498 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8499 Type = ComplexTy->getElementType();
8500 if (Type->isRealFloatingType()) {
8501 llvm::APFloat InitValue =
8502 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8504 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8506 } else if (Type->isScalarType()) {
8507 auto Size = Context.getTypeSize(Type);
8508 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8509 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8510 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8512 if (Init && OrigType->isAnyComplexType()) {
8513 // Init = 0xFFFF + 0xFFFFi;
8514 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8515 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8522 // 'min' reduction op - initializer is 'Largest representable number in
8523 // the reduction list item type'.
8524 // 'max' reduction op - initializer is 'Least representable number in
8525 // the reduction list item type'.
8526 if (Type->isIntegerType() || Type->isPointerType()) {
8527 bool IsSigned = Type->hasSignedIntegerRepresentation();
8528 auto Size = Context.getTypeSize(Type);
8530 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8531 llvm::APInt InitValue =
8533 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8534 : llvm::APInt::getMinValue(Size)
8535 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8536 : llvm::APInt::getMaxValue(Size);
8537 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8538 if (Type->isPointerType()) {
8539 // Cast to pointer type.
8540 auto CastExpr = BuildCStyleCastExpr(
8541 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8542 SourceLocation(), Init);
8543 if (CastExpr.isInvalid())
8545 Init = CastExpr.get();
8547 } else if (Type->isRealFloatingType()) {
8548 llvm::APFloat InitValue = llvm::APFloat::getLargest(
8549 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8550 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8578 llvm_unreachable("Unexpected reduction operation");
8581 if (Init && DeclareReductionRef.isUnset()) {
8582 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
8583 /*TypeMayContainAuto=*/false);
8585 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
8586 if (RHSVD->isInvalidDecl())
8588 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
8589 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8590 << ReductionIdRange;
8593 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8594 Diag(D->getLocation(),
8595 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8599 // Store initializer for single element in private copy. Will be used during
8601 PrivateVD->setInit(RHSVD->getInit());
8602 PrivateVD->setInitStyle(RHSVD->getInitStyle());
8603 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
8604 ExprResult ReductionOp;
8605 if (DeclareReductionRef.isUsable()) {
8606 QualType RedTy = DeclareReductionRef.get()->getType();
8607 QualType PtrRedTy = Context.getPointerType(RedTy);
8608 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
8609 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
8610 if (!BasePath.empty()) {
8611 LHS = DefaultLvalueConversion(LHS.get());
8612 RHS = DefaultLvalueConversion(RHS.get());
8613 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8614 CK_UncheckedDerivedToBase, LHS.get(),
8615 &BasePath, LHS.get()->getValueKind());
8616 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8617 CK_UncheckedDerivedToBase, RHS.get(),
8618 &BasePath, RHS.get()->getValueKind());
8620 FunctionProtoType::ExtProtoInfo EPI;
8621 QualType Params[] = {PtrRedTy, PtrRedTy};
8622 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
8623 auto *OVE = new (Context) OpaqueValueExpr(
8624 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
8625 DefaultLvalueConversion(DeclareReductionRef.get()).get());
8626 Expr *Args[] = {LHS.get(), RHS.get()};
8627 ReductionOp = new (Context)
8628 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
8630 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
8631 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
8632 if (ReductionOp.isUsable()) {
8633 if (BOK != BO_LT && BOK != BO_GT) {
8635 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8636 BO_Assign, LHSDRE, ReductionOp.get());
8638 auto *ConditionalOp = new (Context) ConditionalOperator(
8639 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
8640 RHSDRE, Type, VK_LValue, OK_Ordinary);
8642 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8643 BO_Assign, LHSDRE, ConditionalOp);
8645 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
8647 if (ReductionOp.isInvalid())
8651 DeclRefExpr *Ref = nullptr;
8652 Expr *VarsExpr = RefExpr->IgnoreParens();
8653 if (!VD && !CurContext->isDependentContext()) {
8655 TransformExprToCaptures RebuildToCapture(*this, D);
8657 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
8658 Ref = RebuildToCapture.getCapturedExpr();
8661 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8663 if (!IsOpenMPCapturedDecl(D)) {
8664 ExprCaptures.push_back(Ref->getDecl());
8665 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8666 ExprResult RefRes = DefaultLvalueConversion(Ref);
8667 if (!RefRes.isUsable())
8669 ExprResult PostUpdateRes =
8670 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8671 SimpleRefExpr, RefRes.get());
8672 if (!PostUpdateRes.isUsable())
8674 ExprPostUpdates.push_back(
8675 IgnoredValueConversions(PostUpdateRes.get()).get());
8679 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
8680 Vars.push_back(VarsExpr);
8681 Privates.push_back(PrivateDRE);
8682 LHSs.push_back(LHSDRE);
8683 RHSs.push_back(RHSDRE);
8684 ReductionOps.push_back(ReductionOp.get());
8690 return OMPReductionClause::Create(
8691 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
8692 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
8693 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
8694 buildPostUpdate(*this, ExprPostUpdates));
8697 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8698 SourceLocation LinLoc) {
8699 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
8700 LinKind == OMPC_LINEAR_unknown) {
8701 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
8707 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8708 OpenMPLinearClauseKind LinKind,
8710 auto *VD = dyn_cast_or_null<VarDecl>(D);
8711 // A variable must not have an incomplete type or a reference type.
8712 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
8714 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
8715 !Type->isReferenceType()) {
8716 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
8717 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
8720 Type = Type.getNonReferenceType();
8722 // A list item must not be const-qualified.
8723 if (Type.isConstant(Context)) {
8724 Diag(ELoc, diag::err_omp_const_variable)
8725 << getOpenMPClauseName(OMPC_linear);
8729 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8730 Diag(D->getLocation(),
8731 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8737 // A list item must be of integral or pointer type.
8738 Type = Type.getUnqualifiedType().getCanonicalType();
8739 const auto *Ty = Type.getTypePtrOrNull();
8740 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
8741 !Ty->isPointerType())) {
8742 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
8746 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8747 Diag(D->getLocation(),
8748 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8756 OMPClause *Sema::ActOnOpenMPLinearClause(
8757 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
8758 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
8759 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
8760 SmallVector<Expr *, 8> Vars;
8761 SmallVector<Expr *, 8> Privates;
8762 SmallVector<Expr *, 8> Inits;
8763 SmallVector<Decl *, 4> ExprCaptures;
8764 SmallVector<Expr *, 4> ExprPostUpdates;
8765 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
8766 LinKind = OMPC_LINEAR_val;
8767 for (auto &RefExpr : VarList) {
8768 assert(RefExpr && "NULL expr in OpenMP linear clause.");
8769 SourceLocation ELoc;
8771 Expr *SimpleRefExpr = RefExpr;
8772 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8773 /*AllowArraySection=*/false);
8775 // It will be analyzed later.
8776 Vars.push_back(RefExpr);
8777 Privates.push_back(nullptr);
8778 Inits.push_back(nullptr);
8780 ValueDecl *D = Res.first;
8784 QualType Type = D->getType();
8785 auto *VD = dyn_cast<VarDecl>(D);
8787 // OpenMP [2.14.3.7, linear clause]
8788 // A list-item cannot appear in more than one linear clause.
8789 // A list-item that appears in a linear clause cannot appear in any
8790 // other data-sharing attribute clause.
8791 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8793 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8794 << getOpenMPClauseName(OMPC_linear);
8795 ReportOriginalDSA(*this, DSAStack, D, DVar);
8799 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
8801 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
8803 // Build private copy of original var.
8804 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
8805 D->hasAttrs() ? &D->getAttrs() : nullptr);
8806 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
8807 // Build var to save initial value.
8808 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
8810 DeclRefExpr *Ref = nullptr;
8811 if (!VD && !CurContext->isDependentContext()) {
8812 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8813 if (!IsOpenMPCapturedDecl(D)) {
8814 ExprCaptures.push_back(Ref->getDecl());
8815 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8816 ExprResult RefRes = DefaultLvalueConversion(Ref);
8817 if (!RefRes.isUsable())
8819 ExprResult PostUpdateRes =
8820 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8821 SimpleRefExpr, RefRes.get());
8822 if (!PostUpdateRes.isUsable())
8824 ExprPostUpdates.push_back(
8825 IgnoredValueConversions(PostUpdateRes.get()).get());
8829 if (LinKind == OMPC_LINEAR_uval)
8830 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
8832 InitExpr = VD ? SimpleRefExpr : Ref;
8833 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
8834 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
8835 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
8837 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
8838 Vars.push_back((VD || CurContext->isDependentContext())
8839 ? RefExpr->IgnoreParens()
8841 Privates.push_back(PrivateRef);
8842 Inits.push_back(InitRef);
8848 Expr *StepExpr = Step;
8849 Expr *CalcStepExpr = nullptr;
8850 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
8851 !Step->isInstantiationDependent() &&
8852 !Step->containsUnexpandedParameterPack()) {
8853 SourceLocation StepLoc = Step->getLocStart();
8854 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
8855 if (Val.isInvalid())
8857 StepExpr = Val.get();
8859 // Build var to save the step value.
8861 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
8862 ExprResult SaveRef =
8863 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
8864 ExprResult CalcStep =
8865 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
8866 CalcStep = ActOnFinishFullExpr(CalcStep.get());
8868 // Warn about zero linear step (it would be probably better specified as
8869 // making corresponding variables 'const').
8870 llvm::APSInt Result;
8871 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
8872 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
8873 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
8874 << (Vars.size() > 1);
8875 if (!IsConstant && CalcStep.isUsable()) {
8876 // Calculate the step beforehand instead of doing this on each iteration.
8877 // (This is not used if the number of iterations may be kfold-ed).
8878 CalcStepExpr = CalcStep.get();
8882 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
8883 ColonLoc, EndLoc, Vars, Privates, Inits,
8884 StepExpr, CalcStepExpr,
8885 buildPreInits(Context, ExprCaptures),
8886 buildPostUpdate(*this, ExprPostUpdates));
8889 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
8890 Expr *NumIterations, Sema &SemaRef,
8891 Scope *S, DSAStackTy *Stack) {
8892 // Walk the vars and build update/final expressions for the CodeGen.
8893 SmallVector<Expr *, 8> Updates;
8894 SmallVector<Expr *, 8> Finals;
8895 Expr *Step = Clause.getStep();
8896 Expr *CalcStep = Clause.getCalcStep();
8897 // OpenMP [2.14.3.7, linear clause]
8898 // If linear-step is not specified it is assumed to be 1.
8899 if (Step == nullptr)
8900 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
8901 else if (CalcStep) {
8902 Step = cast<BinaryOperator>(CalcStep)->getLHS();
8904 bool HasErrors = false;
8905 auto CurInit = Clause.inits().begin();
8906 auto CurPrivate = Clause.privates().begin();
8907 auto LinKind = Clause.getModifier();
8908 for (auto &RefExpr : Clause.varlists()) {
8909 SourceLocation ELoc;
8911 Expr *SimpleRefExpr = RefExpr;
8912 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
8913 /*AllowArraySection=*/false);
8914 ValueDecl *D = Res.first;
8915 if (Res.second || !D) {
8916 Updates.push_back(nullptr);
8917 Finals.push_back(nullptr);
8921 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
8922 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
8925 auto &&Info = Stack->isLoopControlVariable(D);
8926 Expr *InitExpr = *CurInit;
8928 // Build privatized reference to the current linear var.
8929 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
8931 if (LinKind == OMPC_LINEAR_uval)
8932 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
8935 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
8936 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
8937 /*RefersToCapture=*/true);
8939 // Build update: Var = InitExpr + IV * Step
8943 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
8944 InitExpr, IV, Step, /* Subtract */ false);
8946 Update = *CurPrivate;
8947 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
8948 /*DiscardedValue=*/true);
8950 // Build final: Var = InitExpr + NumIterations * Step
8953 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
8954 InitExpr, NumIterations, Step,
8955 /* Subtract */ false);
8957 Final = *CurPrivate;
8958 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
8959 /*DiscardedValue=*/true);
8961 if (!Update.isUsable() || !Final.isUsable()) {
8962 Updates.push_back(nullptr);
8963 Finals.push_back(nullptr);
8966 Updates.push_back(Update.get());
8967 Finals.push_back(Final.get());
8972 Clause.setUpdates(Updates);
8973 Clause.setFinals(Finals);
8977 OMPClause *Sema::ActOnOpenMPAlignedClause(
8978 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
8979 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
8981 SmallVector<Expr *, 8> Vars;
8982 for (auto &RefExpr : VarList) {
8983 assert(RefExpr && "NULL expr in OpenMP linear clause.");
8984 SourceLocation ELoc;
8986 Expr *SimpleRefExpr = RefExpr;
8987 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8988 /*AllowArraySection=*/false);
8990 // It will be analyzed later.
8991 Vars.push_back(RefExpr);
8993 ValueDecl *D = Res.first;
8997 QualType QType = D->getType();
8998 auto *VD = dyn_cast<VarDecl>(D);
9000 // OpenMP [2.8.1, simd construct, Restrictions]
9001 // The type of list items appearing in the aligned clause must be
9002 // array, pointer, reference to array, or reference to pointer.
9003 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
9004 const Type *Ty = QType.getTypePtrOrNull();
9005 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
9006 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
9007 << QType << getLangOpts().CPlusPlus << ERange;
9010 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9011 Diag(D->getLocation(),
9012 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9017 // OpenMP [2.8.1, simd construct, Restrictions]
9018 // A list-item cannot appear in more than one aligned clause.
9019 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
9020 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
9021 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9022 << getOpenMPClauseName(OMPC_aligned);
9026 DeclRefExpr *Ref = nullptr;
9027 if (!VD && IsOpenMPCapturedDecl(D))
9028 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9029 Vars.push_back(DefaultFunctionArrayConversion(
9030 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9034 // OpenMP [2.8.1, simd construct, Description]
9035 // The parameter of the aligned clause, alignment, must be a constant
9036 // positive integer expression.
9037 // If no optional parameter is specified, implementation-defined default
9038 // alignments for SIMD instructions on the target platforms are assumed.
9039 if (Alignment != nullptr) {
9040 ExprResult AlignResult =
9041 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9042 if (AlignResult.isInvalid())
9044 Alignment = AlignResult.get();
9049 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9050 EndLoc, Vars, Alignment);
9053 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9054 SourceLocation StartLoc,
9055 SourceLocation LParenLoc,
9056 SourceLocation EndLoc) {
9057 SmallVector<Expr *, 8> Vars;
9058 SmallVector<Expr *, 8> SrcExprs;
9059 SmallVector<Expr *, 8> DstExprs;
9060 SmallVector<Expr *, 8> AssignmentOps;
9061 for (auto &RefExpr : VarList) {
9062 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9063 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
9064 // It will be analyzed later.
9065 Vars.push_back(RefExpr);
9066 SrcExprs.push_back(nullptr);
9067 DstExprs.push_back(nullptr);
9068 AssignmentOps.push_back(nullptr);
9072 SourceLocation ELoc = RefExpr->getExprLoc();
9073 // OpenMP [2.1, C/C++]
9074 // A list item is a variable name.
9075 // OpenMP [2.14.4.1, Restrictions, p.1]
9076 // A list item that appears in a copyin clause must be threadprivate.
9077 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
9078 if (!DE || !isa<VarDecl>(DE->getDecl())) {
9079 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9080 << 0 << RefExpr->getSourceRange();
9084 Decl *D = DE->getDecl();
9085 VarDecl *VD = cast<VarDecl>(D);
9087 QualType Type = VD->getType();
9088 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9089 // It will be analyzed later.
9091 SrcExprs.push_back(nullptr);
9092 DstExprs.push_back(nullptr);
9093 AssignmentOps.push_back(nullptr);
9097 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9098 // A list item that appears in a copyin clause must be threadprivate.
9099 if (!DSAStack->isThreadPrivate(VD)) {
9100 Diag(ELoc, diag::err_omp_required_access)
9101 << getOpenMPClauseName(OMPC_copyin)
9102 << getOpenMPDirectiveName(OMPD_threadprivate);
9106 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9107 // A variable of class type (or array thereof) that appears in a
9108 // copyin clause requires an accessible, unambiguous copy assignment
9109 // operator for the class type.
9110 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
9112 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9113 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
9114 auto *PseudoSrcExpr = buildDeclRefExpr(
9115 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9117 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9118 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
9119 auto *PseudoDstExpr =
9120 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
9121 // For arrays generate assignment operation for single element and replace
9122 // it by the original array element in CodeGen.
9123 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9124 PseudoDstExpr, PseudoSrcExpr);
9125 if (AssignmentOp.isInvalid())
9127 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9128 /*DiscardedValue=*/true);
9129 if (AssignmentOp.isInvalid())
9132 DSAStack->addDSA(VD, DE, OMPC_copyin);
9134 SrcExprs.push_back(PseudoSrcExpr);
9135 DstExprs.push_back(PseudoDstExpr);
9136 AssignmentOps.push_back(AssignmentOp.get());
9142 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9143 SrcExprs, DstExprs, AssignmentOps);
9146 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9147 SourceLocation StartLoc,
9148 SourceLocation LParenLoc,
9149 SourceLocation EndLoc) {
9150 SmallVector<Expr *, 8> Vars;
9151 SmallVector<Expr *, 8> SrcExprs;
9152 SmallVector<Expr *, 8> DstExprs;
9153 SmallVector<Expr *, 8> AssignmentOps;
9154 for (auto &RefExpr : VarList) {
9155 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9156 SourceLocation ELoc;
9158 Expr *SimpleRefExpr = RefExpr;
9159 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9160 /*AllowArraySection=*/false);
9162 // It will be analyzed later.
9163 Vars.push_back(RefExpr);
9164 SrcExprs.push_back(nullptr);
9165 DstExprs.push_back(nullptr);
9166 AssignmentOps.push_back(nullptr);
9168 ValueDecl *D = Res.first;
9172 QualType Type = D->getType();
9173 auto *VD = dyn_cast<VarDecl>(D);
9175 // OpenMP [2.14.4.2, Restrictions, p.2]
9176 // A list item that appears in a copyprivate clause may not appear in a
9177 // private or firstprivate clause on the single construct.
9178 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9179 auto DVar = DSAStack->getTopDSA(D, false);
9180 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9182 Diag(ELoc, diag::err_omp_wrong_dsa)
9183 << getOpenMPClauseName(DVar.CKind)
9184 << getOpenMPClauseName(OMPC_copyprivate);
9185 ReportOriginalDSA(*this, DSAStack, D, DVar);
9189 // OpenMP [2.11.4.2, Restrictions, p.1]
9190 // All list items that appear in a copyprivate clause must be either
9191 // threadprivate or private in the enclosing context.
9192 if (DVar.CKind == OMPC_unknown) {
9193 DVar = DSAStack->getImplicitDSA(D, false);
9194 if (DVar.CKind == OMPC_shared) {
9195 Diag(ELoc, diag::err_omp_required_access)
9196 << getOpenMPClauseName(OMPC_copyprivate)
9197 << "threadprivate or private in the enclosing context";
9198 ReportOriginalDSA(*this, DSAStack, D, DVar);
9204 // Variably modified types are not supported.
9205 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
9206 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9207 << getOpenMPClauseName(OMPC_copyprivate) << Type
9208 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9211 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9212 Diag(D->getLocation(),
9213 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9218 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9219 // A variable of class type (or array thereof) that appears in a
9220 // copyin clause requires an accessible, unambiguous copy assignment
9221 // operator for the class type.
9222 Type = Context.getBaseElementType(Type.getNonReferenceType())
9223 .getUnqualifiedType();
9225 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9226 D->hasAttrs() ? &D->getAttrs() : nullptr);
9227 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
9229 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9230 D->hasAttrs() ? &D->getAttrs() : nullptr);
9231 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
9232 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9233 PseudoDstExpr, PseudoSrcExpr);
9234 if (AssignmentOp.isInvalid())
9236 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
9237 /*DiscardedValue=*/true);
9238 if (AssignmentOp.isInvalid())
9241 // No need to mark vars as copyprivate, they are already threadprivate or
9242 // implicitly private.
9243 assert(VD || IsOpenMPCapturedDecl(D));
9245 VD ? RefExpr->IgnoreParens()
9246 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
9247 SrcExprs.push_back(PseudoSrcExpr);
9248 DstExprs.push_back(PseudoDstExpr);
9249 AssignmentOps.push_back(AssignmentOp.get());
9255 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9256 Vars, SrcExprs, DstExprs, AssignmentOps);
9259 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9260 SourceLocation StartLoc,
9261 SourceLocation LParenLoc,
9262 SourceLocation EndLoc) {
9263 if (VarList.empty())
9266 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9270 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9271 SourceLocation DepLoc, SourceLocation ColonLoc,
9272 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9273 SourceLocation LParenLoc, SourceLocation EndLoc) {
9274 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
9275 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
9276 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
9277 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
9280 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
9281 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9282 DepKind == OMPC_DEPEND_sink)) {
9283 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
9284 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
9285 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9286 /*Last=*/OMPC_DEPEND_unknown, Except)
9287 << getOpenMPClauseName(OMPC_depend);
9290 SmallVector<Expr *, 8> Vars;
9291 DSAStackTy::OperatorOffsetTy OpsOffs;
9292 llvm::APSInt DepCounter(/*BitWidth=*/32);
9293 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9294 if (DepKind == OMPC_DEPEND_sink) {
9295 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9296 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9297 TotalDepCount.setIsUnsigned(/*Val=*/true);
9300 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9301 DSAStack->getParentOrderedRegionParam()) {
9302 for (auto &RefExpr : VarList) {
9303 assert(RefExpr && "NULL expr in OpenMP shared clause.");
9304 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
9305 // It will be analyzed later.
9306 Vars.push_back(RefExpr);
9310 SourceLocation ELoc = RefExpr->getExprLoc();
9311 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9312 if (DepKind == OMPC_DEPEND_sink) {
9313 if (DepCounter >= TotalDepCount) {
9314 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9318 // OpenMP [2.13.9, Summary]
9319 // depend(dependence-type : vec), where dependence-type is:
9320 // 'sink' and where vec is the iteration vector, which has the form:
9321 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9322 // where n is the value specified by the ordered clause in the loop
9323 // directive, xi denotes the loop iteration variable of the i-th nested
9324 // loop associated with the loop directive, and di is a constant
9325 // non-negative integer.
9326 if (CurContext->isDependentContext()) {
9327 // It will be analyzed later.
9328 Vars.push_back(RefExpr);
9331 SimpleExpr = SimpleExpr->IgnoreImplicit();
9332 OverloadedOperatorKind OOK = OO_None;
9333 SourceLocation OOLoc;
9334 Expr *LHS = SimpleExpr;
9335 Expr *RHS = nullptr;
9336 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9337 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9338 OOLoc = BO->getOperatorLoc();
9339 LHS = BO->getLHS()->IgnoreParenImpCasts();
9340 RHS = BO->getRHS()->IgnoreParenImpCasts();
9341 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9342 OOK = OCE->getOperator();
9343 OOLoc = OCE->getOperatorLoc();
9344 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9345 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9346 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9347 OOK = MCE->getMethodDecl()
9350 .getCXXOverloadedOperator();
9351 OOLoc = MCE->getCallee()->getExprLoc();
9352 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9353 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9355 SourceLocation ELoc;
9357 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9358 /*AllowArraySection=*/false);
9360 // It will be analyzed later.
9361 Vars.push_back(RefExpr);
9363 ValueDecl *D = Res.first;
9367 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9368 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9372 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9373 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9374 if (RHSRes.isInvalid())
9377 if (!CurContext->isDependentContext() &&
9378 DSAStack->getParentOrderedRegionParam() &&
9379 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9380 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9381 << DSAStack->getParentLoopControlVariable(
9382 DepCounter.getZExtValue());
9385 OpsOffs.push_back({RHS, OOK});
9387 // OpenMP [2.11.1.1, Restrictions, p.3]
9388 // A variable that is part of another variable (such as a field of a
9389 // structure) but is not an array element or an array section cannot
9390 // appear in a depend clause.
9391 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9392 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9393 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9394 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9395 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
9399 .getNonReferenceType()
9400 ->isPointerType() &&
9401 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
9402 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9403 << 0 << RefExpr->getSourceRange();
9407 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9410 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9411 TotalDepCount > VarList.size() &&
9412 DSAStack->getParentOrderedRegionParam()) {
9413 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9414 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9416 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9420 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9421 DepKind, DepLoc, ColonLoc, Vars);
9422 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9423 DSAStack->addDoacrossDependClause(C, OpsOffs);
9427 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9428 SourceLocation LParenLoc,
9429 SourceLocation EndLoc) {
9430 Expr *ValExpr = Device;
9432 // OpenMP [2.9.1, Restrictions]
9433 // The device expression must evaluate to a non-negative integer value.
9434 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9435 /*StrictlyPositive=*/false))
9438 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9441 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9442 DSAStackTy *Stack, CXXRecordDecl *RD) {
9443 if (!RD || RD->isInvalidDecl())
9446 auto QTy = SemaRef.Context.getRecordType(RD);
9447 if (RD->isDynamicClass()) {
9448 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9449 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9453 bool IsCorrect = true;
9454 for (auto *I : DC->decls()) {
9456 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9457 if (MD->isStatic()) {
9458 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9459 SemaRef.Diag(MD->getLocation(),
9460 diag::note_omp_static_member_in_target);
9463 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9464 if (VD->isStaticDataMember()) {
9465 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9466 SemaRef.Diag(VD->getLocation(),
9467 diag::note_omp_static_member_in_target);
9474 for (auto &I : RD->bases()) {
9475 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9476 I.getType()->getAsCXXRecordDecl()))
9482 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9483 DSAStackTy *Stack, QualType QTy) {
9485 if (QTy->isIncompleteType(&ND)) {
9486 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9488 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
9489 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
9495 /// \brief Return true if it can be proven that the provided array expression
9496 /// (array section or array subscript) does NOT specify the whole size of the
9497 /// array whose base type is \a BaseQTy.
9498 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9501 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9503 // If this is an array subscript, it refers to the whole size if the size of
9504 // the dimension is constant and equals 1. Also, an array section assumes the
9505 // format of an array subscript if no colon is used.
9506 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9507 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9508 return ATy->getSize().getSExtValue() != 1;
9509 // Size can't be evaluated statically.
9513 assert(OASE && "Expecting array section if not an array subscript.");
9514 auto *LowerBound = OASE->getLowerBound();
9515 auto *Length = OASE->getLength();
9517 // If there is a lower bound that does not evaluates to zero, we are not
9518 // covering the whole dimension.
9520 llvm::APSInt ConstLowerBound;
9521 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9522 return false; // Can't get the integer value as a constant.
9523 if (ConstLowerBound.getSExtValue())
9527 // If we don't have a length we covering the whole dimension.
9531 // If the base is a pointer, we don't have a way to get the size of the
9533 if (BaseQTy->isPointerType())
9536 // We can only check if the length is the same as the size of the dimension
9537 // if we have a constant array.
9538 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9542 llvm::APSInt ConstLength;
9543 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9544 return false; // Can't get the integer value as a constant.
9546 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
9549 // Return true if it can be proven that the provided array expression (array
9550 // section or array subscript) does NOT specify a single element of the array
9551 // whose base type is \a BaseQTy.
9552 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
9555 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9557 // An array subscript always refer to a single element. Also, an array section
9558 // assumes the format of an array subscript if no colon is used.
9559 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
9562 assert(OASE && "Expecting array section if not an array subscript.");
9563 auto *Length = OASE->getLength();
9565 // If we don't have a length we have to check if the array has unitary size
9566 // for this dimension. Also, we should always expect a length if the base type
9569 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9570 return ATy->getSize().getSExtValue() != 1;
9571 // We cannot assume anything.
9575 // Check if the length evaluates to 1.
9576 llvm::APSInt ConstLength;
9577 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9578 return false; // Can't get the integer value as a constant.
9580 return ConstLength.getSExtValue() != 1;
9583 // Return the expression of the base of the mappable expression or null if it
9584 // cannot be determined and do all the necessary checks to see if the expression
9585 // is valid as a standalone mappable expression. In the process, record all the
9586 // components of the expression.
9587 static Expr *CheckMapClauseExpressionBase(
9588 Sema &SemaRef, Expr *E,
9589 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
9590 OpenMPClauseKind CKind) {
9591 SourceLocation ELoc = E->getExprLoc();
9592 SourceRange ERange = E->getSourceRange();
9594 // The base of elements of list in a map clause have to be either:
9595 // - a reference to variable or field.
9596 // - a member expression.
9597 // - an array expression.
9599 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9600 // reference to 'r'.
9607 // #pragma omp target map (S.Arr[:12]);
9611 // We want to retrieve the member expression 'this->S';
9613 Expr *RelevantExpr = nullptr;
9615 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
9616 // If a list item is an array section, it must specify contiguous storage.
9618 // For this restriction it is sufficient that we make sure only references
9619 // to variables or fields and array expressions, and that no array sections
9620 // exist except in the rightmost expression (unless they cover the whole
9621 // dimension of the array). E.g. these would be invalid:
9623 // r.ArrS[3:5].Arr[6:7]
9627 // but these would be valid:
9628 // r.ArrS[3].Arr[6:7]
9632 bool AllowUnitySizeArraySection = true;
9633 bool AllowWholeSizeArraySection = true;
9635 while (!RelevantExpr) {
9636 E = E->IgnoreParenImpCasts();
9638 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9639 if (!isa<VarDecl>(CurE->getDecl()))
9642 RelevantExpr = CurE;
9644 // If we got a reference to a declaration, we should not expect any array
9645 // section before that.
9646 AllowUnitySizeArraySection = false;
9647 AllowWholeSizeArraySection = false;
9649 // Record the component.
9650 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
9651 CurE, CurE->getDecl()));
9655 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
9656 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9658 if (isa<CXXThisExpr>(BaseE))
9659 // We found a base expression: this->Val.
9660 RelevantExpr = CurE;
9664 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
9665 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
9666 << CurE->getSourceRange();
9670 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
9672 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
9673 // A bit-field cannot appear in a map clause.
9675 if (FD->isBitField()) {
9676 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
9677 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
9681 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9682 // If the type of a list item is a reference to a type T then the type
9683 // will be considered to be T for all purposes of this clause.
9684 QualType CurType = BaseE->getType().getNonReferenceType();
9686 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
9687 // A list item cannot be a variable that is a member of a structure with
9690 if (auto *RT = CurType->getAs<RecordType>())
9691 if (RT->isUnionType()) {
9692 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
9693 << CurE->getSourceRange();
9697 // If we got a member expression, we should not expect any array section
9700 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
9701 // If a list item is an element of a structure, only the rightmost symbol
9702 // of the variable reference can be an array section.
9704 AllowUnitySizeArraySection = false;
9705 AllowWholeSizeArraySection = false;
9707 // Record the component.
9708 CurComponents.push_back(
9709 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
9713 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
9714 E = CurE->getBase()->IgnoreParenImpCasts();
9716 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
9717 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9718 << 0 << CurE->getSourceRange();
9722 // If we got an array subscript that express the whole dimension we
9723 // can have any array expressions before. If it only expressing part of
9724 // the dimension, we can only have unitary-size array expressions.
9725 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
9727 AllowWholeSizeArraySection = false;
9729 // Record the component - we don't have any declaration associated.
9730 CurComponents.push_back(
9731 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
9735 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
9736 E = CurE->getBase()->IgnoreParenImpCasts();
9739 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9741 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9742 // If the type of a list item is a reference to a type T then the type
9743 // will be considered to be T for all purposes of this clause.
9744 if (CurType->isReferenceType())
9745 CurType = CurType->getPointeeType();
9747 bool IsPointer = CurType->isAnyPointerType();
9749 if (!IsPointer && !CurType->isArrayType()) {
9750 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9751 << 0 << CurE->getSourceRange();
9756 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
9758 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
9760 if (AllowWholeSizeArraySection) {
9761 // Any array section is currently allowed. Allowing a whole size array
9762 // section implies allowing a unity array section as well.
9764 // If this array section refers to the whole dimension we can still
9765 // accept other array sections before this one, except if the base is a
9766 // pointer. Otherwise, only unitary sections are accepted.
9767 if (NotWhole || IsPointer)
9768 AllowWholeSizeArraySection = false;
9769 } else if (AllowUnitySizeArraySection && NotUnity) {
9770 // A unity or whole array section is not allowed and that is not
9771 // compatible with the properties of the current array section.
9773 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
9774 << CurE->getSourceRange();
9778 // Record the component - we don't have any declaration associated.
9779 CurComponents.push_back(
9780 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
9784 // If nothing else worked, this is not a valid map clause expression.
9786 diag::err_omp_expected_named_var_member_or_array_expression)
9791 return RelevantExpr;
9794 // Return true if expression E associated with value VD has conflicts with other
9796 static bool CheckMapConflicts(
9797 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
9798 bool CurrentRegionOnly,
9799 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
9800 OpenMPClauseKind CKind) {
9802 SourceLocation ELoc = E->getExprLoc();
9803 SourceRange ERange = E->getSourceRange();
9805 // In order to easily check the conflicts we need to match each component of
9806 // the expression under test with the components of the expressions that are
9807 // already in the stack.
9809 assert(!CurComponents.empty() && "Map clause expression with no components!");
9810 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
9811 "Map clause expression with unexpected base!");
9813 // Variables to help detecting enclosing problems in data environment nests.
9814 bool IsEnclosedByDataEnvironmentExpr = false;
9815 const Expr *EnclosingExpr = nullptr;
9817 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
9818 VD, CurrentRegionOnly,
9819 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
9821 OpenMPClauseKind) -> bool {
9823 assert(!StackComponents.empty() &&
9824 "Map clause expression with no components!");
9825 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
9826 "Map clause expression with unexpected base!");
9828 // The whole expression in the stack.
9829 auto *RE = StackComponents.front().getAssociatedExpression();
9831 // Expressions must start from the same base. Here we detect at which
9832 // point both expressions diverge from each other and see if we can
9833 // detect if the memory referred to both expressions is contiguous and
9835 auto CI = CurComponents.rbegin();
9836 auto CE = CurComponents.rend();
9837 auto SI = StackComponents.rbegin();
9838 auto SE = StackComponents.rend();
9839 for (; CI != CE && SI != SE; ++CI, ++SI) {
9841 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
9842 // At most one list item can be an array item derived from a given
9843 // variable in map clauses of the same construct.
9844 if (CurrentRegionOnly &&
9845 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
9846 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
9847 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
9848 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
9849 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
9850 diag::err_omp_multiple_array_items_in_map_clause)
9851 << CI->getAssociatedExpression()->getSourceRange();
9852 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
9853 diag::note_used_here)
9854 << SI->getAssociatedExpression()->getSourceRange();
9858 // Do both expressions have the same kind?
9859 if (CI->getAssociatedExpression()->getStmtClass() !=
9860 SI->getAssociatedExpression()->getStmtClass())
9863 // Are we dealing with different variables/fields?
9864 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
9867 // Check if the extra components of the expressions in the enclosing
9868 // data environment are redundant for the current base declaration.
9869 // If they are, the maps completely overlap, which is legal.
9870 for (; SI != SE; ++SI) {
9873 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
9874 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
9875 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
9876 SI->getAssociatedExpression())) {
9877 auto *E = OASE->getBase()->IgnoreParenImpCasts();
9879 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9881 if (Type.isNull() || Type->isAnyPointerType() ||
9882 CheckArrayExpressionDoesNotReferToWholeSize(
9883 SemaRef, SI->getAssociatedExpression(), Type))
9887 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9888 // List items of map clauses in the same construct must not share
9889 // original storage.
9891 // If the expressions are exactly the same or one is a subset of the
9892 // other, it means they are sharing storage.
9893 if (CI == CE && SI == SE) {
9894 if (CurrentRegionOnly) {
9895 if (CKind == OMPC_map)
9896 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9898 assert(CKind == OMPC_to || CKind == OMPC_from);
9899 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9902 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9903 << RE->getSourceRange();
9906 // If we find the same expression in the enclosing data environment,
9908 IsEnclosedByDataEnvironmentExpr = true;
9913 QualType DerivedType =
9914 std::prev(CI)->getAssociatedDeclaration()->getType();
9915 SourceLocation DerivedLoc =
9916 std::prev(CI)->getAssociatedExpression()->getExprLoc();
9918 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9919 // If the type of a list item is a reference to a type T then the type
9920 // will be considered to be T for all purposes of this clause.
9921 DerivedType = DerivedType.getNonReferenceType();
9923 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
9924 // A variable for which the type is pointer and an array section
9925 // derived from that variable must not appear as list items of map
9926 // clauses of the same construct.
9928 // Also, cover one of the cases in:
9929 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9930 // If any part of the original storage of a list item has corresponding
9931 // storage in the device data environment, all of the original storage
9932 // must have corresponding storage in the device data environment.
9934 if (DerivedType->isAnyPointerType()) {
9935 if (CI == CE || SI == SE) {
9938 diag::err_omp_pointer_mapped_along_with_derived_section)
9941 assert(CI != CE && SI != SE);
9942 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
9945 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9946 << RE->getSourceRange();
9950 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9951 // List items of map clauses in the same construct must not share
9952 // original storage.
9954 // An expression is a subset of the other.
9955 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
9956 if (CKind == OMPC_map)
9957 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9959 assert(CKind == OMPC_to || CKind == OMPC_from);
9960 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9963 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9964 << RE->getSourceRange();
9968 // The current expression uses the same base as other expression in the
9969 // data environment but does not contain it completely.
9970 if (!CurrentRegionOnly && SI != SE)
9973 // The current expression is a subset of the expression in the data
9975 IsEnclosedByDataEnvironmentExpr |=
9976 (!CurrentRegionOnly && CI != CE && SI == SE);
9981 if (CurrentRegionOnly)
9984 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9985 // If any part of the original storage of a list item has corresponding
9986 // storage in the device data environment, all of the original storage must
9987 // have corresponding storage in the device data environment.
9988 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
9989 // If a list item is an element of a structure, and a different element of
9990 // the structure has a corresponding list item in the device data environment
9991 // prior to a task encountering the construct associated with the map clause,
9992 // then the list item must also have a corresponding list item in the device
9993 // data environment prior to the task encountering the construct.
9995 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
9997 diag::err_omp_original_storage_is_shared_and_does_not_contain)
9999 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10000 << EnclosingExpr->getSourceRange();
10008 // Utility struct that gathers all the related lists associated with a mappable
10010 struct MappableVarListInfo final {
10011 // The list of expressions.
10012 ArrayRef<Expr *> VarList;
10013 // The list of processed expressions.
10014 SmallVector<Expr *, 16> ProcessedVarList;
10015 // The mappble components for each expression.
10016 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10017 // The base declaration of the variable.
10018 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10020 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10021 // We have a list of components and base declarations for each entry in the
10023 VarComponents.reserve(VarList.size());
10024 VarBaseDeclarations.reserve(VarList.size());
10029 // Check the validity of the provided variable list for the provided clause kind
10030 // \a CKind. In the check process the valid expressions, and mappable expression
10031 // components and variables are extracted and used to fill \a Vars,
10032 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10033 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10035 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10036 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10037 SourceLocation StartLoc,
10038 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10039 bool IsMapTypeImplicit = false) {
10040 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10041 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
10042 "Unexpected clause kind with mappable expressions!");
10044 // Keep track of the mappable components and base declarations in this clause.
10045 // Each entry in the list is going to have a list of components associated. We
10046 // record each set of the components so that we can build the clause later on.
10047 // In the end we should have the same amount of declarations and component
10050 for (auto &RE : MVLI.VarList) {
10051 assert(RE && "Null expr in omp to/from/map clause");
10052 SourceLocation ELoc = RE->getExprLoc();
10054 auto *VE = RE->IgnoreParenLValueCasts();
10056 if (VE->isValueDependent() || VE->isTypeDependent() ||
10057 VE->isInstantiationDependent() ||
10058 VE->containsUnexpandedParameterPack()) {
10059 // We can only analyze this information once the missing information is
10061 MVLI.ProcessedVarList.push_back(RE);
10065 auto *SimpleExpr = RE->IgnoreParenCasts();
10067 if (!RE->IgnoreParenImpCasts()->isLValue()) {
10069 diag::err_omp_expected_named_var_member_or_array_expression)
10070 << RE->getSourceRange();
10074 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10075 ValueDecl *CurDeclaration = nullptr;
10077 // Obtain the array or member expression bases if required. Also, fill the
10078 // components array with all the components identified in the process.
10080 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
10084 assert(!CurComponents.empty() &&
10085 "Invalid mappable expression information.");
10087 // For the following checks, we rely on the base declaration which is
10088 // expected to be associated with the last component. The declaration is
10089 // expected to be a variable or a field (if 'this' is being mapped).
10090 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10091 assert(CurDeclaration && "Null decl on map clause.");
10093 CurDeclaration->isCanonicalDecl() &&
10094 "Expecting components to have associated only canonical declarations.");
10096 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10097 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
10099 assert((VD || FD) && "Only variables or fields are expected here!");
10102 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
10103 // threadprivate variables cannot appear in a map clause.
10104 // OpenMP 4.5 [2.10.5, target update Construct]
10105 // threadprivate variables cannot appear in a from clause.
10106 if (VD && DSAS->isThreadPrivate(VD)) {
10107 auto DVar = DSAS->getTopDSA(VD, false);
10108 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10109 << getOpenMPClauseName(CKind);
10110 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
10114 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10115 // A list item cannot appear in both a map clause and a data-sharing
10116 // attribute clause on the same construct.
10118 // Check conflicts with other map clause expressions. We check the conflicts
10119 // with the current construct separately from the enclosing data
10120 // environment, because the restrictions are different. We only have to
10121 // check conflicts across regions for the map clauses.
10122 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10123 /*CurrentRegionOnly=*/true, CurComponents, CKind))
10125 if (CKind == OMPC_map &&
10126 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10127 /*CurrentRegionOnly=*/false, CurComponents, CKind))
10130 // OpenMP 4.5 [2.10.5, target update Construct]
10131 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10132 // If the type of a list item is a reference to a type T then the type will
10133 // be considered to be T for all purposes of this clause.
10134 QualType Type = CurDeclaration->getType().getNonReferenceType();
10136 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10137 // A list item in a to or from clause must have a mappable type.
10138 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10139 // A list item must have a mappable type.
10140 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10144 if (CKind == OMPC_map) {
10145 // target enter data
10146 // OpenMP [2.10.2, Restrictions, p. 99]
10147 // A map-type must be specified in all map clauses and must be either
10149 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10150 if (DKind == OMPD_target_enter_data &&
10151 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10152 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10153 << (IsMapTypeImplicit ? 1 : 0)
10154 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10155 << getOpenMPDirectiveName(DKind);
10159 // target exit_data
10160 // OpenMP [2.10.3, Restrictions, p. 102]
10161 // A map-type must be specified in all map clauses and must be either
10162 // from, release, or delete.
10163 if (DKind == OMPD_target_exit_data &&
10164 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10165 MapType == OMPC_MAP_delete)) {
10166 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10167 << (IsMapTypeImplicit ? 1 : 0)
10168 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10169 << getOpenMPDirectiveName(DKind);
10173 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10174 // A list item cannot appear in both a map clause and a data-sharing
10175 // attribute clause on the same construct
10176 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
10177 DKind == OMPD_target_teams_distribute ||
10178 DKind == OMPD_target_teams_distribute_parallel_for) && VD) {
10179 auto DVar = DSAS->getTopDSA(VD, false);
10180 if (isOpenMPPrivate(DVar.CKind)) {
10181 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10182 << getOpenMPClauseName(DVar.CKind)
10183 << getOpenMPClauseName(OMPC_map)
10184 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10185 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10191 // Save the current expression.
10192 MVLI.ProcessedVarList.push_back(RE);
10194 // Store the components in the stack so that they can be used to check
10195 // against other clauses later on.
10196 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10197 /*WhereFoundClauseKind=*/OMPC_map);
10199 // Save the components and declaration to create the clause. For purposes of
10200 // the clause creation, any component list that has has base 'this' uses
10201 // null as base declaration.
10202 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10203 MVLI.VarComponents.back().append(CurComponents.begin(),
10204 CurComponents.end());
10205 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10211 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10212 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10213 SourceLocation MapLoc, SourceLocation ColonLoc,
10214 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10215 SourceLocation LParenLoc, SourceLocation EndLoc) {
10216 MappableVarListInfo MVLI(VarList);
10217 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10218 MapType, IsMapTypeImplicit);
10220 // We need to produce a map clause even if we don't have variables so that
10221 // other diagnostics related with non-existing map clauses are accurate.
10222 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10223 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10224 MVLI.VarComponents, MapTypeModifier, MapType,
10225 IsMapTypeImplicit, MapLoc);
10228 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10229 TypeResult ParsedType) {
10230 assert(ParsedType.isUsable());
10232 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10233 if (ReductionType.isNull())
10236 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10237 // A type name in a declare reduction directive cannot be a function type, an
10238 // array type, a reference type, or a type qualified with const, volatile or
10240 if (ReductionType.hasQualifiers()) {
10241 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10245 if (ReductionType->isFunctionType()) {
10246 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10249 if (ReductionType->isReferenceType()) {
10250 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10253 if (ReductionType->isArrayType()) {
10254 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10257 return ReductionType;
10260 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10261 Scope *S, DeclContext *DC, DeclarationName Name,
10262 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10263 AccessSpecifier AS, Decl *PrevDeclInScope) {
10264 SmallVector<Decl *, 8> Decls;
10265 Decls.reserve(ReductionTypes.size());
10267 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10269 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10270 // A reduction-identifier may not be re-declared in the current scope for the
10271 // same type or for a type that is compatible according to the base language
10273 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10274 OMPDeclareReductionDecl *PrevDRD = nullptr;
10275 bool InCompoundScope = true;
10276 if (S != nullptr) {
10277 // Find previous declaration with the same name not referenced in other
10279 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10281 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10282 LookupName(Lookup, S);
10283 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10284 /*AllowInlineNamespace=*/false);
10285 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10286 auto Filter = Lookup.makeFilter();
10287 while (Filter.hasNext()) {
10288 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10289 if (InCompoundScope) {
10290 auto I = UsedAsPrevious.find(PrevDecl);
10291 if (I == UsedAsPrevious.end())
10292 UsedAsPrevious[PrevDecl] = false;
10293 if (auto *D = PrevDecl->getPrevDeclInScope())
10294 UsedAsPrevious[D] = true;
10296 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10297 PrevDecl->getLocation();
10300 if (InCompoundScope) {
10301 for (auto &PrevData : UsedAsPrevious) {
10302 if (!PrevData.second) {
10303 PrevDRD = PrevData.first;
10308 } else if (PrevDeclInScope != nullptr) {
10309 auto *PrevDRDInScope = PrevDRD =
10310 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10312 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10313 PrevDRDInScope->getLocation();
10314 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10315 } while (PrevDRDInScope != nullptr);
10317 for (auto &TyData : ReductionTypes) {
10318 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10319 bool Invalid = false;
10320 if (I != PreviousRedeclTypes.end()) {
10321 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10323 Diag(I->second, diag::note_previous_definition);
10326 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10327 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10328 Name, TyData.first, PrevDRD);
10330 DRD->setAccess(AS);
10331 Decls.push_back(DRD);
10333 DRD->setInvalidDecl();
10338 return DeclGroupPtrTy::make(
10339 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10342 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10343 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10345 // Enter new function scope.
10346 PushFunctionScope();
10347 getCurFunction()->setHasBranchProtectedScope();
10348 getCurFunction()->setHasOMPDeclareReductionCombiner();
10351 PushDeclContext(S, DRD);
10355 PushExpressionEvaluationContext(PotentiallyEvaluated);
10357 QualType ReductionType = DRD->getType();
10358 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10359 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10360 // uses semantics of argument handles by value, but it should be passed by
10361 // reference. C lang does not support references, so pass all parameters as
10363 // Create 'T omp_in;' variable.
10365 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
10366 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10367 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10368 // uses semantics of argument handles by value, but it should be passed by
10369 // reference. C lang does not support references, so pass all parameters as
10371 // Create 'T omp_out;' variable.
10373 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10374 if (S != nullptr) {
10375 PushOnScopeChains(OmpInParm, S);
10376 PushOnScopeChains(OmpOutParm, S);
10378 DRD->addDecl(OmpInParm);
10379 DRD->addDecl(OmpOutParm);
10383 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10384 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10385 DiscardCleanupsInEvaluationContext();
10386 PopExpressionEvaluationContext();
10389 PopFunctionScopeInfo();
10391 if (Combiner != nullptr)
10392 DRD->setCombiner(Combiner);
10394 DRD->setInvalidDecl();
10397 void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10398 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10400 // Enter new function scope.
10401 PushFunctionScope();
10402 getCurFunction()->setHasBranchProtectedScope();
10405 PushDeclContext(S, DRD);
10409 PushExpressionEvaluationContext(PotentiallyEvaluated);
10411 QualType ReductionType = DRD->getType();
10412 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10413 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10414 // uses semantics of argument handles by value, but it should be passed by
10415 // reference. C lang does not support references, so pass all parameters as
10417 // Create 'T omp_priv;' variable.
10418 auto *OmpPrivParm =
10419 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
10420 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10421 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10422 // uses semantics of argument handles by value, but it should be passed by
10423 // reference. C lang does not support references, so pass all parameters as
10425 // Create 'T omp_orig;' variable.
10426 auto *OmpOrigParm =
10427 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
10428 if (S != nullptr) {
10429 PushOnScopeChains(OmpPrivParm, S);
10430 PushOnScopeChains(OmpOrigParm, S);
10432 DRD->addDecl(OmpPrivParm);
10433 DRD->addDecl(OmpOrigParm);
10437 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10438 Expr *Initializer) {
10439 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10440 DiscardCleanupsInEvaluationContext();
10441 PopExpressionEvaluationContext();
10444 PopFunctionScopeInfo();
10446 if (Initializer != nullptr)
10447 DRD->setInitializer(Initializer);
10449 DRD->setInvalidDecl();
10452 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10453 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10454 for (auto *D : DeclReductions.get()) {
10456 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10458 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10460 D->setInvalidDecl();
10462 return DeclReductions;
10465 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
10466 SourceLocation StartLoc,
10467 SourceLocation LParenLoc,
10468 SourceLocation EndLoc) {
10469 Expr *ValExpr = NumTeams;
10471 // OpenMP [teams Constrcut, Restrictions]
10472 // The num_teams expression must evaluate to a positive integer value.
10473 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10474 /*StrictlyPositive=*/true))
10477 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10480 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10481 SourceLocation StartLoc,
10482 SourceLocation LParenLoc,
10483 SourceLocation EndLoc) {
10484 Expr *ValExpr = ThreadLimit;
10486 // OpenMP [teams Constrcut, Restrictions]
10487 // The thread_limit expression must evaluate to a positive integer value.
10488 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10489 /*StrictlyPositive=*/true))
10492 return new (Context)
10493 OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10496 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10497 SourceLocation StartLoc,
10498 SourceLocation LParenLoc,
10499 SourceLocation EndLoc) {
10500 Expr *ValExpr = Priority;
10502 // OpenMP [2.9.1, task Constrcut]
10503 // The priority-value is a non-negative numerical scalar expression.
10504 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10505 /*StrictlyPositive=*/false))
10508 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10511 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10512 SourceLocation StartLoc,
10513 SourceLocation LParenLoc,
10514 SourceLocation EndLoc) {
10515 Expr *ValExpr = Grainsize;
10517 // OpenMP [2.9.2, taskloop Constrcut]
10518 // The parameter of the grainsize clause must be a positive integer
10520 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10521 /*StrictlyPositive=*/true))
10524 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10527 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10528 SourceLocation StartLoc,
10529 SourceLocation LParenLoc,
10530 SourceLocation EndLoc) {
10531 Expr *ValExpr = NumTasks;
10533 // OpenMP [2.9.2, taskloop Constrcut]
10534 // The parameter of the num_tasks clause must be a positive integer
10536 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
10537 /*StrictlyPositive=*/true))
10540 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10543 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10544 SourceLocation LParenLoc,
10545 SourceLocation EndLoc) {
10546 // OpenMP [2.13.2, critical construct, Description]
10547 // ... where hint-expression is an integer constant expression that evaluates
10548 // to a valid lock hint.
10549 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
10550 if (HintExpr.isInvalid())
10552 return new (Context)
10553 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
10556 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
10557 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10558 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
10559 SourceLocation EndLoc) {
10560 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
10561 std::string Values;
10563 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
10565 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10566 << Values << getOpenMPClauseName(OMPC_dist_schedule);
10569 Expr *ValExpr = ChunkSize;
10570 Stmt *HelperValStmt = nullptr;
10572 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10573 !ChunkSize->isInstantiationDependent() &&
10574 !ChunkSize->containsUnexpandedParameterPack()) {
10575 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
10577 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10578 if (Val.isInvalid())
10581 ValExpr = Val.get();
10583 // OpenMP [2.7.1, Restrictions]
10584 // chunk_size must be a loop invariant integer expression with a positive
10586 llvm::APSInt Result;
10587 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10588 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10589 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10590 << "dist_schedule" << ChunkSize->getSourceRange();
10593 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
10594 !CurContext->isDependentContext()) {
10595 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10596 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10597 HelperValStmt = buildPreInits(Context, Captures);
10602 return new (Context)
10603 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
10604 Kind, ValExpr, HelperValStmt);
10607 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
10608 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10609 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10610 SourceLocation KindLoc, SourceLocation EndLoc) {
10611 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
10612 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
10614 SourceLocation Loc;
10616 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
10617 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
10618 OMPC_DEFAULTMAP_MODIFIER_tofrom);
10621 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
10622 OMPC_DEFAULTMAP_scalar);
10626 Diag(Loc, diag::err_omp_unexpected_clause_value)
10627 << Value << getOpenMPClauseName(OMPC_defaultmap);
10631 return new (Context)
10632 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
10635 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
10636 DeclContext *CurLexicalContext = getCurLexicalContext();
10637 if (!CurLexicalContext->isFileContext() &&
10638 !CurLexicalContext->isExternCContext() &&
10639 !CurLexicalContext->isExternCXXContext()) {
10640 Diag(Loc, diag::err_omp_region_not_file_context);
10643 if (IsInOpenMPDeclareTargetContext) {
10644 Diag(Loc, diag::err_omp_enclosed_declare_target);
10648 IsInOpenMPDeclareTargetContext = true;
10652 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
10653 assert(IsInOpenMPDeclareTargetContext &&
10654 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
10656 IsInOpenMPDeclareTargetContext = false;
10659 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
10660 CXXScopeSpec &ScopeSpec,
10661 const DeclarationNameInfo &Id,
10662 OMPDeclareTargetDeclAttr::MapTypeTy MT,
10663 NamedDeclSetType &SameDirectiveDecls) {
10664 LookupResult Lookup(*this, Id, LookupOrdinaryName);
10665 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
10667 if (Lookup.isAmbiguous())
10669 Lookup.suppressDiagnostics();
10671 if (!Lookup.isSingleResult()) {
10672 if (TypoCorrection Corrected =
10673 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
10674 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
10675 CTK_ErrorRecovery)) {
10676 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
10678 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
10682 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
10686 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
10687 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
10688 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
10689 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
10691 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
10692 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
10694 if (ASTMutationListener *ML = Context.getASTMutationListener())
10695 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
10696 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
10697 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
10698 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
10702 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
10705 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
10706 Sema &SemaRef, Decl *D) {
10709 Decl *LD = nullptr;
10710 if (isa<TagDecl>(D)) {
10711 LD = cast<TagDecl>(D)->getDefinition();
10712 } else if (isa<VarDecl>(D)) {
10713 LD = cast<VarDecl>(D)->getDefinition();
10715 // If this is an implicit variable that is legal and we do not need to do
10717 if (cast<VarDecl>(D)->isImplicit()) {
10718 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10719 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10721 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
10722 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10726 } else if (isa<FunctionDecl>(D)) {
10727 const FunctionDecl *FD = nullptr;
10728 if (cast<FunctionDecl>(D)->hasBody(FD))
10729 LD = const_cast<FunctionDecl *>(FD);
10731 // If the definition is associated with the current declaration in the
10732 // target region (it can be e.g. a lambda) that is legal and we do not need
10733 // to do anything else.
10735 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10736 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10738 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
10739 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10745 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
10746 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
10747 // Outlined declaration is not declared target.
10748 if (LD->isOutOfLine()) {
10749 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10750 SemaRef.Diag(SL, diag::note_used_here) << SR;
10752 DeclContext *DC = LD->getDeclContext();
10754 if (isa<FunctionDecl>(DC) &&
10755 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
10757 DC = DC->getParent();
10762 // Is not declared in target context.
10763 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10764 SemaRef.Diag(SL, diag::note_used_here) << SR;
10766 // Mark decl as declared target to prevent further diagnostic.
10767 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10768 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10770 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
10771 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10775 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
10776 Sema &SemaRef, DSAStackTy *Stack,
10778 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
10780 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
10785 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
10786 if (!D || D->isInvalidDecl())
10788 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
10789 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
10790 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
10791 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10792 if (DSAStack->isThreadPrivate(VD)) {
10793 Diag(SL, diag::err_omp_threadprivate_in_target);
10794 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
10798 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
10799 // Problem if any with var declared with incomplete type will be reported
10800 // as normal, so no need to check it here.
10801 if ((E || !VD->getType()->isIncompleteType()) &&
10802 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
10803 // Mark decl as declared target to prevent further diagnostic.
10804 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
10805 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10806 Context, OMPDeclareTargetDeclAttr::MT_To);
10808 if (ASTMutationListener *ML = Context.getASTMutationListener())
10809 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
10815 // Checking declaration inside declare target region.
10816 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
10817 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
10818 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10819 Context, OMPDeclareTargetDeclAttr::MT_To);
10821 if (ASTMutationListener *ML = Context.getASTMutationListener())
10822 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10826 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
10829 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
10830 SourceLocation StartLoc,
10831 SourceLocation LParenLoc,
10832 SourceLocation EndLoc) {
10833 MappableVarListInfo MVLI(VarList);
10834 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
10835 if (MVLI.ProcessedVarList.empty())
10838 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10839 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10840 MVLI.VarComponents);
10843 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
10844 SourceLocation StartLoc,
10845 SourceLocation LParenLoc,
10846 SourceLocation EndLoc) {
10847 MappableVarListInfo MVLI(VarList);
10848 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
10849 if (MVLI.ProcessedVarList.empty())
10852 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10853 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10854 MVLI.VarComponents);
10857 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
10858 SourceLocation StartLoc,
10859 SourceLocation LParenLoc,
10860 SourceLocation EndLoc) {
10861 MappableVarListInfo MVLI(VarList);
10862 SmallVector<Expr *, 8> PrivateCopies;
10863 SmallVector<Expr *, 8> Inits;
10865 for (auto &RefExpr : VarList) {
10866 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
10867 SourceLocation ELoc;
10868 SourceRange ERange;
10869 Expr *SimpleRefExpr = RefExpr;
10870 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10872 // It will be analyzed later.
10873 MVLI.ProcessedVarList.push_back(RefExpr);
10874 PrivateCopies.push_back(nullptr);
10875 Inits.push_back(nullptr);
10877 ValueDecl *D = Res.first;
10881 QualType Type = D->getType();
10882 Type = Type.getNonReferenceType().getUnqualifiedType();
10884 auto *VD = dyn_cast<VarDecl>(D);
10886 // Item should be a pointer or reference to pointer.
10887 if (!Type->isPointerType()) {
10888 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
10889 << 0 << RefExpr->getSourceRange();
10893 // Build the private variable and the expression that refers to it.
10894 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
10895 D->hasAttrs() ? &D->getAttrs() : nullptr);
10896 if (VDPrivate->isInvalidDecl())
10899 CurContext->addDecl(VDPrivate);
10900 auto VDPrivateRefExpr = buildDeclRefExpr(
10901 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
10903 // Add temporary variable to initialize the private copy of the pointer.
10905 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
10906 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10907 RefExpr->getExprLoc());
10908 AddInitializerToDecl(VDPrivate,
10909 DefaultLvalueConversion(VDInitRefExpr).get(),
10910 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
10912 // If required, build a capture to implement the privatization initialized
10913 // with the current list item value.
10914 DeclRefExpr *Ref = nullptr;
10916 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10917 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
10918 PrivateCopies.push_back(VDPrivateRefExpr);
10919 Inits.push_back(VDInitRefExpr);
10921 // We need to add a data sharing attribute for this variable to make sure it
10922 // is correctly captured. A variable that shows up in a use_device_ptr has
10923 // similar properties of a first private variable.
10924 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
10926 // Create a mappable component for the list item. List items in this clause
10927 // only need a component.
10928 MVLI.VarBaseDeclarations.push_back(D);
10929 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10930 MVLI.VarComponents.back().push_back(
10931 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
10934 if (MVLI.ProcessedVarList.empty())
10937 return OMPUseDevicePtrClause::Create(
10938 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
10939 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
10942 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
10943 SourceLocation StartLoc,
10944 SourceLocation LParenLoc,
10945 SourceLocation EndLoc) {
10946 MappableVarListInfo MVLI(VarList);
10947 for (auto &RefExpr : VarList) {
10948 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
10949 SourceLocation ELoc;
10950 SourceRange ERange;
10951 Expr *SimpleRefExpr = RefExpr;
10952 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10954 // It will be analyzed later.
10955 MVLI.ProcessedVarList.push_back(RefExpr);
10957 ValueDecl *D = Res.first;
10961 QualType Type = D->getType();
10962 // item should be a pointer or array or reference to pointer or array
10963 if (!Type.getNonReferenceType()->isPointerType() &&
10964 !Type.getNonReferenceType()->isArrayType()) {
10965 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
10966 << 0 << RefExpr->getSourceRange();
10970 // Check if the declaration in the clause does not show up in any data
10971 // sharing attribute.
10972 auto DVar = DSAStack->getTopDSA(D, false);
10973 if (isOpenMPPrivate(DVar.CKind)) {
10974 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10975 << getOpenMPClauseName(DVar.CKind)
10976 << getOpenMPClauseName(OMPC_is_device_ptr)
10977 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10978 ReportOriginalDSA(*this, DSAStack, D, DVar);
10982 Expr *ConflictExpr;
10983 if (DSAStack->checkMappableExprComponentListsForDecl(
10984 D, /*CurrentRegionOnly=*/true,
10986 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
10987 OpenMPClauseKind) -> bool {
10988 ConflictExpr = R.front().getAssociatedExpression();
10991 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
10992 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
10993 << ConflictExpr->getSourceRange();
10997 // Store the components in the stack so that they can be used to check
10998 // against other clauses later on.
10999 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11000 DSAStack->addMappableExpressionComponents(
11001 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11003 // Record the expression we've just processed.
11004 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11006 // Create a mappable component for the list item. List items in this clause
11007 // only need a component. We use a null declaration to signal fields in
11009 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11010 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11011 "Unexpected device pointer expression!");
11012 MVLI.VarBaseDeclarations.push_back(
11013 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11014 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11015 MVLI.VarComponents.back().push_back(MC);
11018 if (MVLI.ProcessedVarList.empty())
11021 return OMPIsDevicePtrClause::Create(
11022 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11023 MVLI.VarBaseDeclarations, MVLI.VarComponents);