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 "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclOpenMP.h"
20 #include "clang/AST/StmtCXX.h"
21 #include "clang/AST/StmtOpenMP.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/Basic/OpenMPKinds.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/Scope.h"
28 #include "clang/Sema/ScopeInfo.h"
29 #include "clang/Sema/SemaInternal.h"
30 using namespace clang;
32 //===----------------------------------------------------------------------===//
33 // Stack of data-sharing attributes for variables
34 //===----------------------------------------------------------------------===//
37 /// \brief Default data sharing attributes, which can be applied to directive.
38 enum DefaultDataSharingAttributes {
39 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
40 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
41 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
44 template <class T> struct MatchesAny {
45 explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
46 bool operator()(T Kind) {
47 for (auto KindEl : Arr)
56 struct MatchesAlways {
58 template <class T> bool operator()(T) { return true; }
61 typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
62 typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
64 /// \brief Stack for tracking declarations used in OpenMP directives and
65 /// clauses and their data-sharing attributes.
69 OpenMPDirectiveKind DKind;
70 OpenMPClauseKind CKind;
72 SourceLocation ImplicitDSALoc;
74 : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
80 OpenMPClauseKind Attributes;
83 typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
84 typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
85 typedef llvm::DenseSet<VarDecl *> LoopControlVariablesSetTy;
88 DeclSAMapTy SharingMap;
89 AlignedMapTy AlignedMap;
90 LoopControlVariablesSetTy LCVSet;
91 DefaultDataSharingAttributes DefaultAttr;
92 SourceLocation DefaultAttrLoc;
93 OpenMPDirectiveKind Directive;
94 DeclarationNameInfo DirectiveName;
96 SourceLocation ConstructLoc;
98 unsigned CollapseNumber;
99 SourceLocation InnerTeamsRegionLoc;
100 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
101 Scope *CurScope, SourceLocation Loc)
102 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
103 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
104 ConstructLoc(Loc), OrderedRegion(false), CollapseNumber(1),
105 InnerTeamsRegionLoc() {}
107 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
108 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
109 ConstructLoc(), OrderedRegion(false), CollapseNumber(1),
110 InnerTeamsRegionLoc() {}
113 typedef SmallVector<SharingMapTy, 64> StackTy;
115 /// \brief Stack of used declaration and their data-sharing attributes.
117 /// \brief true, if check for DSA must be from parent directive, false, if
118 /// from current directive.
122 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
124 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
126 /// \brief Checks if the variable is a local for OpenMP region.
127 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
130 explicit DSAStackTy(Sema &S) : Stack(1), FromParent(false), SemaRef(S) {}
132 bool isFromParent() const { return FromParent; }
133 void setFromParent(bool Flag) { FromParent = Flag; }
135 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
136 Scope *CurScope, SourceLocation Loc) {
137 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
138 Stack.back().DefaultAttrLoc = Loc;
142 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
146 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
147 /// add it and return NULL; otherwise return previous occurrence's expression
149 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
151 /// \brief Register specified variable as loop control variable.
152 void addLoopControlVariable(VarDecl *D);
153 /// \brief Check if the specified variable is a loop control variable for
155 bool isLoopControlVariable(VarDecl *D);
157 /// \brief Adds explicit data sharing attribute to the specified declaration.
158 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
160 /// \brief Returns data sharing attributes from top of the stack for the
161 /// specified declaration.
162 DSAVarData getTopDSA(VarDecl *D, bool FromParent);
163 /// \brief Returns data-sharing attributes for the specified declaration.
164 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
165 /// \brief Checks if the specified variables has data-sharing attributes which
166 /// match specified \a CPred predicate in any directive which matches \a DPred
168 template <class ClausesPredicate, class DirectivesPredicate>
169 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
170 DirectivesPredicate DPred, bool FromParent);
171 /// \brief Checks if the specified variables has data-sharing attributes which
172 /// match specified \a CPred predicate in any innermost directive which
173 /// matches \a DPred predicate.
174 template <class ClausesPredicate, class DirectivesPredicate>
175 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
176 DirectivesPredicate DPred,
178 /// \brief Finds a directive which matches specified \a DPred predicate.
179 template <class NamedDirectivesPredicate>
180 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
182 /// \brief Returns currently analyzed directive.
183 OpenMPDirectiveKind getCurrentDirective() const {
184 return Stack.back().Directive;
186 /// \brief Returns parent directive.
187 OpenMPDirectiveKind getParentDirective() const {
188 if (Stack.size() > 2)
189 return Stack[Stack.size() - 2].Directive;
193 /// \brief Set default data sharing attribute to none.
194 void setDefaultDSANone(SourceLocation Loc) {
195 Stack.back().DefaultAttr = DSA_none;
196 Stack.back().DefaultAttrLoc = Loc;
198 /// \brief Set default data sharing attribute to shared.
199 void setDefaultDSAShared(SourceLocation Loc) {
200 Stack.back().DefaultAttr = DSA_shared;
201 Stack.back().DefaultAttrLoc = Loc;
204 DefaultDataSharingAttributes getDefaultDSA() const {
205 return Stack.back().DefaultAttr;
207 SourceLocation getDefaultDSALocation() const {
208 return Stack.back().DefaultAttrLoc;
211 /// \brief Checks if the specified variable is a threadprivate.
212 bool isThreadPrivate(VarDecl *D) {
213 DSAVarData DVar = getTopDSA(D, false);
214 return isOpenMPThreadPrivate(DVar.CKind);
217 /// \brief Marks current region as ordered (it has an 'ordered' clause).
218 void setOrderedRegion(bool IsOrdered = true) {
219 Stack.back().OrderedRegion = IsOrdered;
221 /// \brief Returns true, if parent region is ordered (has associated
222 /// 'ordered' clause), false - otherwise.
223 bool isParentOrderedRegion() const {
224 if (Stack.size() > 2)
225 return Stack[Stack.size() - 2].OrderedRegion;
229 /// \brief Set collapse value for the region.
230 void setCollapseNumber(unsigned Val) { Stack.back().CollapseNumber = Val; }
231 /// \brief Return collapse value for region.
232 unsigned getCollapseNumber() const {
233 return Stack.back().CollapseNumber;
236 /// \brief Marks current target region as one with closely nested teams
238 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
239 if (Stack.size() > 2)
240 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
242 /// \brief Returns true, if current region has closely nested teams region.
243 bool hasInnerTeamsRegion() const {
244 return getInnerTeamsRegionLoc().isValid();
246 /// \brief Returns location of the nested teams region (if any).
247 SourceLocation getInnerTeamsRegionLoc() const {
248 if (Stack.size() > 1)
249 return Stack.back().InnerTeamsRegionLoc;
250 return SourceLocation();
253 Scope *getCurScope() const { return Stack.back().CurScope; }
254 Scope *getCurScope() { return Stack.back().CurScope; }
255 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
257 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
258 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
259 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
263 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
265 D = D->getCanonicalDecl();
267 if (Iter == std::prev(Stack.rend())) {
268 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
269 // in a region but not in construct]
270 // File-scope or namespace-scope variables referenced in called routines
271 // in the region are shared unless they appear in a threadprivate
273 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
274 DVar.CKind = OMPC_shared;
276 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
277 // in a region but not in construct]
278 // Variables with static storage duration that are declared in called
279 // routines in the region are shared.
280 if (D->hasGlobalStorage())
281 DVar.CKind = OMPC_shared;
286 DVar.DKind = Iter->Directive;
287 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
288 // in a Construct, C/C++, predetermined, p.1]
289 // Variables with automatic storage duration that are declared in a scope
290 // inside the construct are private.
291 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
292 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
293 DVar.CKind = OMPC_private;
297 // Explicitly specified attributes and local variables with predetermined
299 if (Iter->SharingMap.count(D)) {
300 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
301 DVar.CKind = Iter->SharingMap[D].Attributes;
302 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
306 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
307 // in a Construct, C/C++, implicitly determined, p.1]
308 // In a parallel or task construct, the data-sharing attributes of these
309 // variables are determined by the default clause, if present.
310 switch (Iter->DefaultAttr) {
312 DVar.CKind = OMPC_shared;
313 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
317 case DSA_unspecified:
318 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
319 // in a Construct, implicitly determined, p.2]
320 // In a parallel construct, if no default clause is present, these
321 // variables are shared.
322 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
323 if (isOpenMPParallelDirective(DVar.DKind) ||
324 isOpenMPTeamsDirective(DVar.DKind)) {
325 DVar.CKind = OMPC_shared;
329 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
330 // in a Construct, implicitly determined, p.4]
331 // In a task construct, if no default clause is present, a variable that in
332 // the enclosing context is determined to be shared by all implicit tasks
333 // bound to the current team is shared.
334 if (DVar.DKind == OMPD_task) {
336 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
338 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
340 // in a Construct, implicitly determined, p.6]
341 // In a task construct, if no default clause is present, a variable
342 // whose data-sharing attribute is not determined by the rules above is
344 DVarTemp = getDSA(I, D);
345 if (DVarTemp.CKind != OMPC_shared) {
346 DVar.RefExpr = nullptr;
347 DVar.DKind = OMPD_task;
348 DVar.CKind = OMPC_firstprivate;
351 if (isParallelOrTaskRegion(I->Directive))
354 DVar.DKind = OMPD_task;
356 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
360 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
361 // in a Construct, implicitly determined, p.3]
362 // For constructs other than task, if no default clause is present, these
363 // variables inherit their data-sharing attributes from the enclosing
365 return getDSA(std::next(Iter), D);
368 DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
369 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
370 D = D->getCanonicalDecl();
371 auto It = Stack.back().AlignedMap.find(D);
372 if (It == Stack.back().AlignedMap.end()) {
373 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
374 Stack.back().AlignedMap[D] = NewDE;
377 assert(It->second && "Unexpected nullptr expr in the aligned map");
383 void DSAStackTy::addLoopControlVariable(VarDecl *D) {
384 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
385 D = D->getCanonicalDecl();
386 Stack.back().LCVSet.insert(D);
389 bool DSAStackTy::isLoopControlVariable(VarDecl *D) {
390 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
391 D = D->getCanonicalDecl();
392 return Stack.back().LCVSet.count(D) > 0;
395 void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
396 D = D->getCanonicalDecl();
397 if (A == OMPC_threadprivate) {
398 Stack[0].SharingMap[D].Attributes = A;
399 Stack[0].SharingMap[D].RefExpr = E;
401 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
402 Stack.back().SharingMap[D].Attributes = A;
403 Stack.back().SharingMap[D].RefExpr = E;
407 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
408 D = D->getCanonicalDecl();
409 if (Stack.size() > 2) {
410 reverse_iterator I = Iter, E = std::prev(Stack.rend());
411 Scope *TopScope = nullptr;
412 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
417 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
418 Scope *CurScope = getCurScope();
419 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
420 CurScope = CurScope->getParent();
422 return CurScope != TopScope;
427 /// \brief Build a variable declaration for OpenMP loop iteration variable.
428 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
430 DeclContext *DC = SemaRef.CurContext;
431 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
432 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
434 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
439 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
441 bool RefersToCapture = false) {
443 D->markUsed(S.Context);
444 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
445 SourceLocation(), D, RefersToCapture, Loc, Ty,
449 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
450 D = D->getCanonicalDecl();
453 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
454 // in a Construct, C/C++, predetermined, p.1]
455 // Variables appearing in threadprivate directives are threadprivate.
456 if (D->getTLSKind() != VarDecl::TLS_None ||
457 (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() &&
458 !D->isLocalVarDecl())) {
459 addDSA(D, buildDeclRefExpr(SemaRef, D, D->getType().getNonReferenceType(),
463 if (Stack[0].SharingMap.count(D)) {
464 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
465 DVar.CKind = OMPC_threadprivate;
469 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
470 // in a Construct, C/C++, predetermined, p.1]
471 // Variables with automatic storage duration that are declared in a scope
472 // inside the construct are private.
473 OpenMPDirectiveKind Kind =
474 FromParent ? getParentDirective() : getCurrentDirective();
475 auto StartI = std::next(Stack.rbegin());
476 auto EndI = std::prev(Stack.rend());
477 if (FromParent && StartI != EndI) {
478 StartI = std::next(StartI);
480 if (!isParallelOrTaskRegion(Kind)) {
481 if (isOpenMPLocal(D, StartI) &&
482 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
483 D->getStorageClass() == SC_None)) ||
484 isa<ParmVarDecl>(D))) {
485 DVar.CKind = OMPC_private;
489 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
490 // in a Construct, C/C++, predetermined, p.4]
491 // Static data members are shared.
492 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
493 // in a Construct, C/C++, predetermined, p.7]
494 // Variables with static storage duration that are declared in a scope
495 // inside the construct are shared.
496 if (D->isStaticDataMember() || D->isStaticLocal()) {
497 DSAVarData DVarTemp =
498 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
499 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
502 DVar.CKind = OMPC_shared;
507 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
508 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
509 Type = SemaRef.getASTContext().getBaseElementType(Type);
510 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
511 // in a Construct, C/C++, predetermined, p.6]
512 // Variables with const qualified type having no mutable member are
515 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
517 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
518 // Variables with const-qualified type having no mutable member may be
519 // listed in a firstprivate clause, even if they are static data members.
520 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
521 MatchesAlways(), FromParent);
522 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
525 DVar.CKind = OMPC_shared;
529 // Explicitly specified attributes and local variables with predetermined
531 auto I = std::prev(StartI);
532 if (I->SharingMap.count(D)) {
533 DVar.RefExpr = I->SharingMap[D].RefExpr;
534 DVar.CKind = I->SharingMap[D].Attributes;
535 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
541 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
542 D = D->getCanonicalDecl();
543 auto StartI = Stack.rbegin();
544 auto EndI = std::prev(Stack.rend());
545 if (FromParent && StartI != EndI) {
546 StartI = std::next(StartI);
548 return getDSA(StartI, D);
551 template <class ClausesPredicate, class DirectivesPredicate>
552 DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
553 DirectivesPredicate DPred,
555 D = D->getCanonicalDecl();
556 auto StartI = std::next(Stack.rbegin());
557 auto EndI = std::prev(Stack.rend());
558 if (FromParent && StartI != EndI) {
559 StartI = std::next(StartI);
561 for (auto I = StartI, EE = EndI; I != EE; ++I) {
562 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
564 DSAVarData DVar = getDSA(I, D);
565 if (CPred(DVar.CKind))
571 template <class ClausesPredicate, class DirectivesPredicate>
572 DSAStackTy::DSAVarData
573 DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
574 DirectivesPredicate DPred, bool FromParent) {
575 D = D->getCanonicalDecl();
576 auto StartI = std::next(Stack.rbegin());
577 auto EndI = std::prev(Stack.rend());
578 if (FromParent && StartI != EndI) {
579 StartI = std::next(StartI);
581 for (auto I = StartI, EE = EndI; I != EE; ++I) {
582 if (!DPred(I->Directive))
584 DSAVarData DVar = getDSA(I, D);
585 if (CPred(DVar.CKind))
592 template <class NamedDirectivesPredicate>
593 bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
594 auto StartI = std::next(Stack.rbegin());
595 auto EndI = std::prev(Stack.rend());
596 if (FromParent && StartI != EndI) {
597 StartI = std::next(StartI);
599 for (auto I = StartI, EE = EndI; I != EE; ++I) {
600 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
606 void Sema::InitDataSharingAttributesStack() {
607 VarDataSharingAttributesStack = new DSAStackTy(*this);
610 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
612 bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
613 assert(LangOpts.OpenMP && "OpenMP is not allowed");
614 VD = VD->getCanonicalDecl();
615 if (DSAStack->getCurrentDirective() != OMPD_unknown) {
616 if (DSAStack->isLoopControlVariable(VD) ||
617 (VD->hasLocalStorage() &&
618 isParallelOrTaskRegion(DSAStack->getCurrentDirective())))
620 auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isFromParent());
621 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
623 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
624 DSAStack->isFromParent());
625 return DVarPrivate.CKind != OMPC_unknown;
630 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
632 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
633 const DeclarationNameInfo &DirName,
634 Scope *CurScope, SourceLocation Loc) {
635 DSAStack->push(DKind, DirName, CurScope, Loc);
636 PushExpressionEvaluationContext(PotentiallyEvaluated);
639 void Sema::StartOpenMPClauses() {
640 DSAStack->setFromParent(/*Flag=*/true);
643 void Sema::EndOpenMPClauses() {
644 DSAStack->setFromParent(/*Flag=*/false);
647 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
648 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
649 // A variable of class type (or array thereof) that appears in a lastprivate
650 // clause requires an accessible, unambiguous default constructor for the
651 // class type, unless the list item is also specified in a firstprivate
653 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
654 for (auto *C : D->clauses()) {
655 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
656 SmallVector<Expr *, 8> PrivateCopies;
657 for (auto *DE : Clause->varlists()) {
658 if (DE->isValueDependent() || DE->isTypeDependent()) {
659 PrivateCopies.push_back(nullptr);
662 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
663 QualType Type = VD->getType();
664 auto DVar = DSAStack->getTopDSA(VD, false);
665 if (DVar.CKind == OMPC_lastprivate) {
666 // Generate helper private variable and initialize it with the
667 // default value. The address of the original variable is replaced
668 // by the address of the new private variable in CodeGen. This new
669 // variable is not added to IdResolver, so the code in the OpenMP
670 // region uses original variable for proper diagnostics.
672 buildVarDecl(*this, DE->getExprLoc(), Type.getUnqualifiedType(),
674 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
675 if (VDPrivate->isInvalidDecl())
677 PrivateCopies.push_back(buildDeclRefExpr(
678 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
680 // The variable is also a firstprivate, so initialization sequence
681 // for private copy is generated already.
682 PrivateCopies.push_back(nullptr);
685 // Set initializers to private copies if no errors were found.
686 if (PrivateCopies.size() == Clause->varlist_size()) {
687 Clause->setPrivateCopies(PrivateCopies);
694 DiscardCleanupsInEvaluationContext();
695 PopExpressionEvaluationContext();
698 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
699 Expr *NumIterations, Sema &SemaRef,
704 class VarDeclFilterCCC : public CorrectionCandidateCallback {
709 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
710 bool ValidateCandidate(const TypoCorrection &Candidate) override {
711 NamedDecl *ND = Candidate.getCorrectionDecl();
712 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
713 return VD->hasGlobalStorage() &&
714 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
715 SemaRef.getCurScope());
722 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
723 CXXScopeSpec &ScopeSpec,
724 const DeclarationNameInfo &Id) {
725 LookupResult Lookup(*this, Id, LookupOrdinaryName);
726 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
728 if (Lookup.isAmbiguous())
732 if (!Lookup.isSingleResult()) {
733 if (TypoCorrection Corrected = CorrectTypo(
734 Id, LookupOrdinaryName, CurScope, nullptr,
735 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
736 diagnoseTypo(Corrected,
738 ? diag::err_undeclared_var_use_suggest
739 : diag::err_omp_expected_var_arg_suggest)
741 VD = Corrected.getCorrectionDeclAs<VarDecl>();
743 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
744 : diag::err_omp_expected_var_arg)
749 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
750 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
751 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
755 Lookup.suppressDiagnostics();
757 // OpenMP [2.9.2, Syntax, C/C++]
758 // Variables must be file-scope, namespace-scope, or static block-scope.
759 if (!VD->hasGlobalStorage()) {
760 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
761 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
763 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
764 Diag(VD->getLocation(),
765 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
770 VarDecl *CanonicalVD = VD->getCanonicalDecl();
771 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
772 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
773 // A threadprivate directive for file-scope variables must appear outside
774 // any definition or declaration.
775 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
776 !getCurLexicalContext()->isTranslationUnit()) {
777 Diag(Id.getLoc(), diag::err_omp_var_scope)
778 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
780 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
781 Diag(VD->getLocation(),
782 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
786 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
787 // A threadprivate directive for static class member variables must appear
788 // in the class definition, in the same scope in which the member
789 // variables are declared.
790 if (CanonicalVD->isStaticDataMember() &&
791 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
792 Diag(Id.getLoc(), diag::err_omp_var_scope)
793 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
795 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
796 Diag(VD->getLocation(),
797 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
801 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
802 // A threadprivate directive for namespace-scope variables must appear
803 // outside any definition or declaration other than the namespace
804 // definition itself.
805 if (CanonicalVD->getDeclContext()->isNamespace() &&
806 (!getCurLexicalContext()->isFileContext() ||
807 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
808 Diag(Id.getLoc(), diag::err_omp_var_scope)
809 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
811 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
812 Diag(VD->getLocation(),
813 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
817 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
818 // A threadprivate directive for static block-scope variables must appear
819 // in the scope of the variable and not in a nested scope.
820 if (CanonicalVD->isStaticLocal() && CurScope &&
821 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
822 Diag(Id.getLoc(), diag::err_omp_var_scope)
823 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
825 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
826 Diag(VD->getLocation(),
827 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
832 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
833 // A threadprivate directive must lexically precede all references to any
834 // of the variables in its list.
835 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
836 Diag(Id.getLoc(), diag::err_omp_var_used)
837 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
841 QualType ExprType = VD->getType().getNonReferenceType();
842 ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
847 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
848 ArrayRef<Expr *> VarList) {
849 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
850 CurContext->addDecl(D);
851 return DeclGroupPtrTy::make(DeclGroupRef(D));
853 return DeclGroupPtrTy();
857 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
861 bool VisitDeclRefExpr(const DeclRefExpr *E) {
862 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
863 if (VD->hasLocalStorage()) {
864 SemaRef.Diag(E->getLocStart(),
865 diag::err_omp_local_var_in_threadprivate_init)
866 << E->getSourceRange();
867 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
868 << VD << VD->getSourceRange();
874 bool VisitStmt(const Stmt *S) {
875 for (auto Child : S->children()) {
876 if (Child && Visit(Child))
881 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
885 OMPThreadPrivateDecl *
886 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
887 SmallVector<Expr *, 8> Vars;
888 for (auto &RefExpr : VarList) {
889 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
890 VarDecl *VD = cast<VarDecl>(DE->getDecl());
891 SourceLocation ILoc = DE->getExprLoc();
893 QualType QType = VD->getType();
894 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
895 // It will be analyzed later.
900 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
901 // A threadprivate variable must not have an incomplete type.
902 if (RequireCompleteType(ILoc, VD->getType(),
903 diag::err_omp_threadprivate_incomplete_type)) {
907 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
908 // A threadprivate variable must not have a reference type.
909 if (VD->getType()->isReferenceType()) {
910 Diag(ILoc, diag::err_omp_ref_type_arg)
911 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
913 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
914 Diag(VD->getLocation(),
915 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
920 // Check if this is a TLS variable.
921 if (VD->getTLSKind() != VarDecl::TLS_None ||
922 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
923 !VD->isLocalVarDecl())) {
924 Diag(ILoc, diag::err_omp_var_thread_local)
925 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
927 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
928 Diag(VD->getLocation(),
929 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
934 // Check if initial value of threadprivate variable reference variable with
935 // local storage (it is not supported by runtime).
936 if (auto Init = VD->getAnyInitializer()) {
937 LocalVarRefChecker Checker(*this);
938 if (Checker.Visit(Init))
942 Vars.push_back(RefExpr);
943 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
944 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
945 Context, SourceRange(Loc, Loc)));
946 if (auto *ML = Context.getASTMutationListener())
947 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
949 OMPThreadPrivateDecl *D = nullptr;
951 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
953 D->setAccess(AS_public);
958 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
959 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
960 bool IsLoopIterVar = false) {
962 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
963 << getOpenMPClauseName(DVar.CKind);
967 PDSA_StaticMemberShared,
968 PDSA_StaticLocalVarShared,
969 PDSA_LoopIterVarPrivate,
970 PDSA_LoopIterVarLinear,
971 PDSA_LoopIterVarLastprivate,
973 PDSA_GlobalVarShared,
974 PDSA_TaskVarFirstprivate,
975 PDSA_LocalVarPrivate,
977 } Reason = PDSA_Implicit;
978 bool ReportHint = false;
979 auto ReportLoc = VD->getLocation();
981 if (DVar.CKind == OMPC_private)
982 Reason = PDSA_LoopIterVarPrivate;
983 else if (DVar.CKind == OMPC_lastprivate)
984 Reason = PDSA_LoopIterVarLastprivate;
986 Reason = PDSA_LoopIterVarLinear;
987 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
988 Reason = PDSA_TaskVarFirstprivate;
989 ReportLoc = DVar.ImplicitDSALoc;
990 } else if (VD->isStaticLocal())
991 Reason = PDSA_StaticLocalVarShared;
992 else if (VD->isStaticDataMember())
993 Reason = PDSA_StaticMemberShared;
994 else if (VD->isFileVarDecl())
995 Reason = PDSA_GlobalVarShared;
996 else if (VD->getType().isConstant(SemaRef.getASTContext()))
997 Reason = PDSA_ConstVarShared;
998 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1000 Reason = PDSA_LocalVarPrivate;
1002 if (Reason != PDSA_Implicit) {
1003 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1004 << Reason << ReportHint
1005 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1006 } else if (DVar.ImplicitDSALoc.isValid()) {
1007 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1008 << getOpenMPClauseName(DVar.CKind);
1013 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1018 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1019 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
1022 void VisitDeclRefExpr(DeclRefExpr *E) {
1023 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1024 // Skip internally declared variables.
1025 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1028 auto DVar = Stack->getTopDSA(VD, false);
1029 // Check if the variable has explicit DSA set and stop analysis if it so.
1030 if (DVar.RefExpr) return;
1032 auto ELoc = E->getExprLoc();
1033 auto DKind = Stack->getCurrentDirective();
1034 // The default(none) clause requires that each variable that is referenced
1035 // in the construct, and does not have a predetermined data-sharing
1036 // attribute, must have its data-sharing attribute explicitly determined
1037 // by being listed in a data-sharing attribute clause.
1038 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1039 isParallelOrTaskRegion(DKind) &&
1040 VarsWithInheritedDSA.count(VD) == 0) {
1041 VarsWithInheritedDSA[VD] = E;
1045 // OpenMP [2.9.3.6, Restrictions, p.2]
1046 // A list item that appears in a reduction clause of the innermost
1047 // enclosing worksharing or parallel construct may not be accessed in an
1049 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
1050 [](OpenMPDirectiveKind K) -> bool {
1051 return isOpenMPParallelDirective(K) ||
1052 isOpenMPWorksharingDirective(K) ||
1053 isOpenMPTeamsDirective(K);
1056 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1058 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1059 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1063 // Define implicit data-sharing attributes for task.
1064 DVar = Stack->getImplicitDSA(VD, false);
1065 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
1066 ImplicitFirstprivate.push_back(E);
1069 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
1070 for (auto *C : S->clauses()) {
1071 // Skip analysis of arguments of implicitly defined firstprivate clause
1072 // for task directives.
1073 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1074 for (auto *CC : C->children()) {
1080 void VisitStmt(Stmt *S) {
1081 for (auto *C : S->children()) {
1082 if (C && !isa<OMPExecutableDirective>(C))
1087 bool isErrorFound() { return ErrorFound; }
1088 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
1089 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1090 return VarsWithInheritedDSA;
1093 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1094 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1098 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1100 case OMPD_parallel: {
1101 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1102 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1103 Sema::CapturedParamNameType Params[] = {
1104 std::make_pair(".global_tid.", KmpInt32PtrTy),
1105 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1106 std::make_pair(StringRef(), QualType()) // __context with shared vars
1108 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1113 Sema::CapturedParamNameType Params[] = {
1114 std::make_pair(StringRef(), QualType()) // __context with shared vars
1116 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1121 Sema::CapturedParamNameType Params[] = {
1122 std::make_pair(StringRef(), QualType()) // __context with shared vars
1124 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1128 case OMPD_for_simd: {
1129 Sema::CapturedParamNameType Params[] = {
1130 std::make_pair(StringRef(), QualType()) // __context with shared vars
1132 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1136 case OMPD_sections: {
1137 Sema::CapturedParamNameType Params[] = {
1138 std::make_pair(StringRef(), QualType()) // __context with shared vars
1140 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1144 case OMPD_section: {
1145 Sema::CapturedParamNameType Params[] = {
1146 std::make_pair(StringRef(), QualType()) // __context with shared vars
1148 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1153 Sema::CapturedParamNameType Params[] = {
1154 std::make_pair(StringRef(), QualType()) // __context with shared vars
1156 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1161 Sema::CapturedParamNameType Params[] = {
1162 std::make_pair(StringRef(), QualType()) // __context with shared vars
1164 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1168 case OMPD_critical: {
1169 Sema::CapturedParamNameType Params[] = {
1170 std::make_pair(StringRef(), QualType()) // __context with shared vars
1172 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1176 case OMPD_parallel_for: {
1177 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1178 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1179 Sema::CapturedParamNameType Params[] = {
1180 std::make_pair(".global_tid.", KmpInt32PtrTy),
1181 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1182 std::make_pair(StringRef(), QualType()) // __context with shared vars
1184 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1188 case OMPD_parallel_for_simd: {
1189 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1190 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1191 Sema::CapturedParamNameType Params[] = {
1192 std::make_pair(".global_tid.", KmpInt32PtrTy),
1193 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1194 std::make_pair(StringRef(), QualType()) // __context with shared vars
1196 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1200 case OMPD_parallel_sections: {
1201 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1202 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1203 Sema::CapturedParamNameType Params[] = {
1204 std::make_pair(".global_tid.", KmpInt32PtrTy),
1205 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1206 std::make_pair(StringRef(), QualType()) // __context with shared vars
1208 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1213 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1214 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1215 FunctionProtoType::ExtProtoInfo EPI;
1216 EPI.Variadic = true;
1217 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1218 Sema::CapturedParamNameType Params[] = {
1219 std::make_pair(".global_tid.", KmpInt32Ty),
1220 std::make_pair(".part_id.", KmpInt32Ty),
1221 std::make_pair(".privates.",
1222 Context.VoidPtrTy.withConst().withRestrict()),
1225 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1226 std::make_pair(StringRef(), QualType()) // __context with shared vars
1228 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1230 // Mark this captured region as inlined, because we don't use outlined
1231 // function directly.
1232 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1233 AlwaysInlineAttr::CreateImplicit(
1234 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1237 case OMPD_ordered: {
1238 Sema::CapturedParamNameType Params[] = {
1239 std::make_pair(StringRef(), QualType()) // __context with shared vars
1241 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1246 Sema::CapturedParamNameType Params[] = {
1247 std::make_pair(StringRef(), QualType()) // __context with shared vars
1249 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1254 Sema::CapturedParamNameType Params[] = {
1255 std::make_pair(StringRef(), QualType()) // __context with shared vars
1257 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1262 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1263 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1264 Sema::CapturedParamNameType Params[] = {
1265 std::make_pair(".global_tid.", KmpInt32PtrTy),
1266 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1267 std::make_pair(StringRef(), QualType()) // __context with shared vars
1269 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1273 case OMPD_taskgroup: {
1274 Sema::CapturedParamNameType Params[] = {
1275 std::make_pair(StringRef(), QualType()) // __context with shared vars
1277 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1281 case OMPD_threadprivate:
1282 case OMPD_taskyield:
1286 llvm_unreachable("OpenMP Directive is not allowed");
1288 llvm_unreachable("Unknown OpenMP directive");
1292 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1293 ArrayRef<OMPClause *> Clauses) {
1294 if (!S.isUsable()) {
1295 ActOnCapturedRegionError();
1298 // This is required for proper codegen.
1299 for (auto *Clause : Clauses) {
1300 if (isOpenMPPrivate(Clause->getClauseKind()) ||
1301 Clause->getClauseKind() == OMPC_copyprivate) {
1302 // Mark all variables in private list clauses as used in inner region.
1303 for (auto *VarRef : Clause->children()) {
1304 if (auto *E = cast_or_null<Expr>(VarRef)) {
1305 MarkDeclarationsReferencedInExpr(E);
1308 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
1309 Clause->getClauseKind() == OMPC_schedule) {
1310 // Mark all variables in private list clauses as used in inner region.
1311 // Required for proper codegen of combined directives.
1312 // TODO: add processing for other clauses.
1313 if (auto *E = cast_or_null<Expr>(
1314 cast<OMPScheduleClause>(Clause)->getHelperChunkSize())) {
1315 MarkDeclarationsReferencedInExpr(E);
1319 return ActOnCapturedRegionEnd(S.get());
1322 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1323 OpenMPDirectiveKind CurrentRegion,
1324 const DeclarationNameInfo &CurrentName,
1325 SourceLocation StartLoc) {
1326 // Allowed nesting of constructs
1327 // +------------------+-----------------+------------------------------------+
1328 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1329 // +------------------+-----------------+------------------------------------+
1330 // | parallel | parallel | * |
1331 // | parallel | for | * |
1332 // | parallel | for simd | * |
1333 // | parallel | master | * |
1334 // | parallel | critical | * |
1335 // | parallel | simd | * |
1336 // | parallel | sections | * |
1337 // | parallel | section | + |
1338 // | parallel | single | * |
1339 // | parallel | parallel for | * |
1340 // | parallel |parallel for simd| * |
1341 // | parallel |parallel sections| * |
1342 // | parallel | task | * |
1343 // | parallel | taskyield | * |
1344 // | parallel | barrier | * |
1345 // | parallel | taskwait | * |
1346 // | parallel | taskgroup | * |
1347 // | parallel | flush | * |
1348 // | parallel | ordered | + |
1349 // | parallel | atomic | * |
1350 // | parallel | target | * |
1351 // | parallel | teams | + |
1352 // +------------------+-----------------+------------------------------------+
1353 // | for | parallel | * |
1354 // | for | for | + |
1355 // | for | for simd | + |
1356 // | for | master | + |
1357 // | for | critical | * |
1358 // | for | simd | * |
1359 // | for | sections | + |
1360 // | for | section | + |
1361 // | for | single | + |
1362 // | for | parallel for | * |
1363 // | for |parallel for simd| * |
1364 // | for |parallel sections| * |
1365 // | for | task | * |
1366 // | for | taskyield | * |
1367 // | for | barrier | + |
1368 // | for | taskwait | * |
1369 // | for | taskgroup | * |
1370 // | for | flush | * |
1371 // | for | ordered | * (if construct is ordered) |
1372 // | for | atomic | * |
1373 // | for | target | * |
1374 // | for | teams | + |
1375 // +------------------+-----------------+------------------------------------+
1376 // | master | parallel | * |
1377 // | master | for | + |
1378 // | master | for simd | + |
1379 // | master | master | * |
1380 // | master | critical | * |
1381 // | master | simd | * |
1382 // | master | sections | + |
1383 // | master | section | + |
1384 // | master | single | + |
1385 // | master | parallel for | * |
1386 // | master |parallel for simd| * |
1387 // | master |parallel sections| * |
1388 // | master | task | * |
1389 // | master | taskyield | * |
1390 // | master | barrier | + |
1391 // | master | taskwait | * |
1392 // | master | taskgroup | * |
1393 // | master | flush | * |
1394 // | master | ordered | + |
1395 // | master | atomic | * |
1396 // | master | target | * |
1397 // | master | teams | + |
1398 // +------------------+-----------------+------------------------------------+
1399 // | critical | parallel | * |
1400 // | critical | for | + |
1401 // | critical | for simd | + |
1402 // | critical | master | * |
1403 // | critical | critical | * (should have different names) |
1404 // | critical | simd | * |
1405 // | critical | sections | + |
1406 // | critical | section | + |
1407 // | critical | single | + |
1408 // | critical | parallel for | * |
1409 // | critical |parallel for simd| * |
1410 // | critical |parallel sections| * |
1411 // | critical | task | * |
1412 // | critical | taskyield | * |
1413 // | critical | barrier | + |
1414 // | critical | taskwait | * |
1415 // | critical | taskgroup | * |
1416 // | critical | ordered | + |
1417 // | critical | atomic | * |
1418 // | critical | target | * |
1419 // | critical | teams | + |
1420 // +------------------+-----------------+------------------------------------+
1421 // | simd | parallel | |
1423 // | simd | for simd | |
1424 // | simd | master | |
1425 // | simd | critical | |
1426 // | simd | simd | |
1427 // | simd | sections | |
1428 // | simd | section | |
1429 // | simd | single | |
1430 // | simd | parallel for | |
1431 // | simd |parallel for simd| |
1432 // | simd |parallel sections| |
1433 // | simd | task | |
1434 // | simd | taskyield | |
1435 // | simd | barrier | |
1436 // | simd | taskwait | |
1437 // | simd | taskgroup | |
1438 // | simd | flush | |
1439 // | simd | ordered | |
1440 // | simd | atomic | |
1441 // | simd | target | |
1442 // | simd | teams | |
1443 // +------------------+-----------------+------------------------------------+
1444 // | for simd | parallel | |
1445 // | for simd | for | |
1446 // | for simd | for simd | |
1447 // | for simd | master | |
1448 // | for simd | critical | |
1449 // | for simd | simd | |
1450 // | for simd | sections | |
1451 // | for simd | section | |
1452 // | for simd | single | |
1453 // | for simd | parallel for | |
1454 // | for simd |parallel for simd| |
1455 // | for simd |parallel sections| |
1456 // | for simd | task | |
1457 // | for simd | taskyield | |
1458 // | for simd | barrier | |
1459 // | for simd | taskwait | |
1460 // | for simd | taskgroup | |
1461 // | for simd | flush | |
1462 // | for simd | ordered | |
1463 // | for simd | atomic | |
1464 // | for simd | target | |
1465 // | for simd | teams | |
1466 // +------------------+-----------------+------------------------------------+
1467 // | parallel for simd| parallel | |
1468 // | parallel for simd| for | |
1469 // | parallel for simd| for simd | |
1470 // | parallel for simd| master | |
1471 // | parallel for simd| critical | |
1472 // | parallel for simd| simd | |
1473 // | parallel for simd| sections | |
1474 // | parallel for simd| section | |
1475 // | parallel for simd| single | |
1476 // | parallel for simd| parallel for | |
1477 // | parallel for simd|parallel for simd| |
1478 // | parallel for simd|parallel sections| |
1479 // | parallel for simd| task | |
1480 // | parallel for simd| taskyield | |
1481 // | parallel for simd| barrier | |
1482 // | parallel for simd| taskwait | |
1483 // | parallel for simd| taskgroup | |
1484 // | parallel for simd| flush | |
1485 // | parallel for simd| ordered | |
1486 // | parallel for simd| atomic | |
1487 // | parallel for simd| target | |
1488 // | parallel for simd| teams | |
1489 // +------------------+-----------------+------------------------------------+
1490 // | sections | parallel | * |
1491 // | sections | for | + |
1492 // | sections | for simd | + |
1493 // | sections | master | + |
1494 // | sections | critical | * |
1495 // | sections | simd | * |
1496 // | sections | sections | + |
1497 // | sections | section | * |
1498 // | sections | single | + |
1499 // | sections | parallel for | * |
1500 // | sections |parallel for simd| * |
1501 // | sections |parallel sections| * |
1502 // | sections | task | * |
1503 // | sections | taskyield | * |
1504 // | sections | barrier | + |
1505 // | sections | taskwait | * |
1506 // | sections | taskgroup | * |
1507 // | sections | flush | * |
1508 // | sections | ordered | + |
1509 // | sections | atomic | * |
1510 // | sections | target | * |
1511 // | sections | teams | + |
1512 // +------------------+-----------------+------------------------------------+
1513 // | section | parallel | * |
1514 // | section | for | + |
1515 // | section | for simd | + |
1516 // | section | master | + |
1517 // | section | critical | * |
1518 // | section | simd | * |
1519 // | section | sections | + |
1520 // | section | section | + |
1521 // | section | single | + |
1522 // | section | parallel for | * |
1523 // | section |parallel for simd| * |
1524 // | section |parallel sections| * |
1525 // | section | task | * |
1526 // | section | taskyield | * |
1527 // | section | barrier | + |
1528 // | section | taskwait | * |
1529 // | section | taskgroup | * |
1530 // | section | flush | * |
1531 // | section | ordered | + |
1532 // | section | atomic | * |
1533 // | section | target | * |
1534 // | section | teams | + |
1535 // +------------------+-----------------+------------------------------------+
1536 // | single | parallel | * |
1537 // | single | for | + |
1538 // | single | for simd | + |
1539 // | single | master | + |
1540 // | single | critical | * |
1541 // | single | simd | * |
1542 // | single | sections | + |
1543 // | single | section | + |
1544 // | single | single | + |
1545 // | single | parallel for | * |
1546 // | single |parallel for simd| * |
1547 // | single |parallel sections| * |
1548 // | single | task | * |
1549 // | single | taskyield | * |
1550 // | single | barrier | + |
1551 // | single | taskwait | * |
1552 // | single | taskgroup | * |
1553 // | single | flush | * |
1554 // | single | ordered | + |
1555 // | single | atomic | * |
1556 // | single | target | * |
1557 // | single | teams | + |
1558 // +------------------+-----------------+------------------------------------+
1559 // | parallel for | parallel | * |
1560 // | parallel for | for | + |
1561 // | parallel for | for simd | + |
1562 // | parallel for | master | + |
1563 // | parallel for | critical | * |
1564 // | parallel for | simd | * |
1565 // | parallel for | sections | + |
1566 // | parallel for | section | + |
1567 // | parallel for | single | + |
1568 // | parallel for | parallel for | * |
1569 // | parallel for |parallel for simd| * |
1570 // | parallel for |parallel sections| * |
1571 // | parallel for | task | * |
1572 // | parallel for | taskyield | * |
1573 // | parallel for | barrier | + |
1574 // | parallel for | taskwait | * |
1575 // | parallel for | taskgroup | * |
1576 // | parallel for | flush | * |
1577 // | parallel for | ordered | * (if construct is ordered) |
1578 // | parallel for | atomic | * |
1579 // | parallel for | target | * |
1580 // | parallel for | teams | + |
1581 // +------------------+-----------------+------------------------------------+
1582 // | parallel sections| parallel | * |
1583 // | parallel sections| for | + |
1584 // | parallel sections| for simd | + |
1585 // | parallel sections| master | + |
1586 // | parallel sections| critical | + |
1587 // | parallel sections| simd | * |
1588 // | parallel sections| sections | + |
1589 // | parallel sections| section | * |
1590 // | parallel sections| single | + |
1591 // | parallel sections| parallel for | * |
1592 // | parallel sections|parallel for simd| * |
1593 // | parallel sections|parallel sections| * |
1594 // | parallel sections| task | * |
1595 // | parallel sections| taskyield | * |
1596 // | parallel sections| barrier | + |
1597 // | parallel sections| taskwait | * |
1598 // | parallel sections| taskgroup | * |
1599 // | parallel sections| flush | * |
1600 // | parallel sections| ordered | + |
1601 // | parallel sections| atomic | * |
1602 // | parallel sections| target | * |
1603 // | parallel sections| teams | + |
1604 // +------------------+-----------------+------------------------------------+
1605 // | task | parallel | * |
1606 // | task | for | + |
1607 // | task | for simd | + |
1608 // | task | master | + |
1609 // | task | critical | * |
1610 // | task | simd | * |
1611 // | task | sections | + |
1612 // | task | section | + |
1613 // | task | single | + |
1614 // | task | parallel for | * |
1615 // | task |parallel for simd| * |
1616 // | task |parallel sections| * |
1617 // | task | task | * |
1618 // | task | taskyield | * |
1619 // | task | barrier | + |
1620 // | task | taskwait | * |
1621 // | task | taskgroup | * |
1622 // | task | flush | * |
1623 // | task | ordered | + |
1624 // | task | atomic | * |
1625 // | task | target | * |
1626 // | task | teams | + |
1627 // +------------------+-----------------+------------------------------------+
1628 // | ordered | parallel | * |
1629 // | ordered | for | + |
1630 // | ordered | for simd | + |
1631 // | ordered | master | * |
1632 // | ordered | critical | * |
1633 // | ordered | simd | * |
1634 // | ordered | sections | + |
1635 // | ordered | section | + |
1636 // | ordered | single | + |
1637 // | ordered | parallel for | * |
1638 // | ordered |parallel for simd| * |
1639 // | ordered |parallel sections| * |
1640 // | ordered | task | * |
1641 // | ordered | taskyield | * |
1642 // | ordered | barrier | + |
1643 // | ordered | taskwait | * |
1644 // | ordered | taskgroup | * |
1645 // | ordered | flush | * |
1646 // | ordered | ordered | + |
1647 // | ordered | atomic | * |
1648 // | ordered | target | * |
1649 // | ordered | teams | + |
1650 // +------------------+-----------------+------------------------------------+
1651 // | atomic | parallel | |
1652 // | atomic | for | |
1653 // | atomic | for simd | |
1654 // | atomic | master | |
1655 // | atomic | critical | |
1656 // | atomic | simd | |
1657 // | atomic | sections | |
1658 // | atomic | section | |
1659 // | atomic | single | |
1660 // | atomic | parallel for | |
1661 // | atomic |parallel for simd| |
1662 // | atomic |parallel sections| |
1663 // | atomic | task | |
1664 // | atomic | taskyield | |
1665 // | atomic | barrier | |
1666 // | atomic | taskwait | |
1667 // | atomic | taskgroup | |
1668 // | atomic | flush | |
1669 // | atomic | ordered | |
1670 // | atomic | atomic | |
1671 // | atomic | target | |
1672 // | atomic | teams | |
1673 // +------------------+-----------------+------------------------------------+
1674 // | target | parallel | * |
1675 // | target | for | * |
1676 // | target | for simd | * |
1677 // | target | master | * |
1678 // | target | critical | * |
1679 // | target | simd | * |
1680 // | target | sections | * |
1681 // | target | section | * |
1682 // | target | single | * |
1683 // | target | parallel for | * |
1684 // | target |parallel for simd| * |
1685 // | target |parallel sections| * |
1686 // | target | task | * |
1687 // | target | taskyield | * |
1688 // | target | barrier | * |
1689 // | target | taskwait | * |
1690 // | target | taskgroup | * |
1691 // | target | flush | * |
1692 // | target | ordered | * |
1693 // | target | atomic | * |
1694 // | target | target | * |
1695 // | target | teams | * |
1696 // +------------------+-----------------+------------------------------------+
1697 // | teams | parallel | * |
1698 // | teams | for | + |
1699 // | teams | for simd | + |
1700 // | teams | master | + |
1701 // | teams | critical | + |
1702 // | teams | simd | + |
1703 // | teams | sections | + |
1704 // | teams | section | + |
1705 // | teams | single | + |
1706 // | teams | parallel for | * |
1707 // | teams |parallel for simd| * |
1708 // | teams |parallel sections| * |
1709 // | teams | task | + |
1710 // | teams | taskyield | + |
1711 // | teams | barrier | + |
1712 // | teams | taskwait | + |
1713 // | teams | taskgroup | + |
1714 // | teams | flush | + |
1715 // | teams | ordered | + |
1716 // | teams | atomic | + |
1717 // | teams | target | + |
1718 // | teams | teams | + |
1719 // +------------------+-----------------+------------------------------------+
1720 if (Stack->getCurScope()) {
1721 auto ParentRegion = Stack->getParentDirective();
1722 bool NestingProhibited = false;
1723 bool CloseNesting = true;
1726 ShouldBeInParallelRegion,
1727 ShouldBeInOrderedRegion,
1728 ShouldBeInTargetRegion
1729 } Recommend = NoRecommend;
1730 if (isOpenMPSimdDirective(ParentRegion)) {
1731 // OpenMP [2.16, Nesting of Regions]
1732 // OpenMP constructs may not be nested inside a simd region.
1733 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1736 if (ParentRegion == OMPD_atomic) {
1737 // OpenMP [2.16, Nesting of Regions]
1738 // OpenMP constructs may not be nested inside an atomic region.
1739 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1742 if (CurrentRegion == OMPD_section) {
1743 // OpenMP [2.7.2, sections Construct, Restrictions]
1744 // Orphaned section directives are prohibited. That is, the section
1745 // directives must appear within the sections construct and must not be
1746 // encountered elsewhere in the sections region.
1747 if (ParentRegion != OMPD_sections &&
1748 ParentRegion != OMPD_parallel_sections) {
1749 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1750 << (ParentRegion != OMPD_unknown)
1751 << getOpenMPDirectiveName(ParentRegion);
1756 // Allow some constructs to be orphaned (they could be used in functions,
1757 // called from OpenMP regions with the required preconditions).
1758 if (ParentRegion == OMPD_unknown)
1760 if (CurrentRegion == OMPD_master) {
1761 // OpenMP [2.16, Nesting of Regions]
1762 // A master region may not be closely nested inside a worksharing,
1763 // atomic, or explicit task region.
1764 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1765 ParentRegion == OMPD_task;
1766 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1767 // OpenMP [2.16, Nesting of Regions]
1768 // A critical region may not be nested (closely or otherwise) inside a
1769 // critical region with the same name. Note that this restriction is not
1770 // sufficient to prevent deadlock.
1771 SourceLocation PreviousCriticalLoc;
1773 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1774 OpenMPDirectiveKind K,
1775 const DeclarationNameInfo &DNI,
1778 if (K == OMPD_critical &&
1779 DNI.getName() == CurrentName.getName()) {
1780 PreviousCriticalLoc = Loc;
1785 false /* skip top directive */);
1787 SemaRef.Diag(StartLoc,
1788 diag::err_omp_prohibited_region_critical_same_name)
1789 << CurrentName.getName();
1790 if (PreviousCriticalLoc.isValid())
1791 SemaRef.Diag(PreviousCriticalLoc,
1792 diag::note_omp_previous_critical_region);
1795 } else if (CurrentRegion == OMPD_barrier) {
1796 // OpenMP [2.16, Nesting of Regions]
1797 // A barrier region may not be closely nested inside a worksharing,
1798 // explicit task, critical, ordered, atomic, or master region.
1800 isOpenMPWorksharingDirective(ParentRegion) ||
1801 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1802 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1803 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
1804 !isOpenMPParallelDirective(CurrentRegion)) {
1805 // OpenMP [2.16, Nesting of Regions]
1806 // A worksharing region may not be closely nested inside a worksharing,
1807 // explicit task, critical, ordered, atomic, or master region.
1809 isOpenMPWorksharingDirective(ParentRegion) ||
1810 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1811 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1812 Recommend = ShouldBeInParallelRegion;
1813 } else if (CurrentRegion == OMPD_ordered) {
1814 // OpenMP [2.16, Nesting of Regions]
1815 // An ordered region may not be closely nested inside a critical,
1816 // atomic, or explicit task region.
1817 // An ordered region must be closely nested inside a loop region (or
1818 // parallel loop region) with an ordered clause.
1819 NestingProhibited = ParentRegion == OMPD_critical ||
1820 ParentRegion == OMPD_task ||
1821 !Stack->isParentOrderedRegion();
1822 Recommend = ShouldBeInOrderedRegion;
1823 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1824 // OpenMP [2.16, Nesting of Regions]
1825 // If specified, a teams construct must be contained within a target
1827 NestingProhibited = ParentRegion != OMPD_target;
1828 Recommend = ShouldBeInTargetRegion;
1829 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1831 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1832 // OpenMP [2.16, Nesting of Regions]
1833 // distribute, parallel, parallel sections, parallel workshare, and the
1834 // parallel loop and parallel loop SIMD constructs are the only OpenMP
1835 // constructs that can be closely nested in the teams region.
1836 // TODO: add distribute directive.
1837 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1838 Recommend = ShouldBeInParallelRegion;
1840 if (NestingProhibited) {
1841 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
1842 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1843 << getOpenMPDirectiveName(CurrentRegion);
1850 StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
1851 const DeclarationNameInfo &DirName,
1852 ArrayRef<OMPClause *> Clauses,
1854 SourceLocation StartLoc,
1855 SourceLocation EndLoc) {
1856 StmtResult Res = StmtError();
1857 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
1860 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
1861 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
1862 bool ErrorFound = false;
1863 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
1865 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1867 // Check default data sharing attributes for referenced variables.
1868 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1869 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1870 if (DSAChecker.isErrorFound())
1872 // Generate list of implicitly defined firstprivate variables.
1873 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
1875 if (!DSAChecker.getImplicitFirstprivate().empty()) {
1876 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1877 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1878 SourceLocation(), SourceLocation())) {
1879 ClausesWithImplicit.push_back(Implicit);
1880 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1881 DSAChecker.getImplicitFirstprivate().size();
1889 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1893 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1894 VarsWithInheritedDSA);
1897 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1898 VarsWithInheritedDSA);
1901 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
1902 EndLoc, VarsWithInheritedDSA);
1905 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1909 assert(ClausesWithImplicit.empty() &&
1910 "No clauses are allowed for 'omp section' directive");
1911 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1914 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1918 assert(ClausesWithImplicit.empty() &&
1919 "No clauses are allowed for 'omp master' directive");
1920 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1923 assert(ClausesWithImplicit.empty() &&
1924 "No clauses are allowed for 'omp critical' directive");
1925 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1927 case OMPD_parallel_for:
1928 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1929 EndLoc, VarsWithInheritedDSA);
1931 case OMPD_parallel_for_simd:
1932 Res = ActOnOpenMPParallelForSimdDirective(
1933 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
1935 case OMPD_parallel_sections:
1936 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1941 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1943 case OMPD_taskyield:
1944 assert(ClausesWithImplicit.empty() &&
1945 "No clauses are allowed for 'omp taskyield' directive");
1946 assert(AStmt == nullptr &&
1947 "No associated statement allowed for 'omp taskyield' directive");
1948 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1951 assert(ClausesWithImplicit.empty() &&
1952 "No clauses are allowed for 'omp barrier' directive");
1953 assert(AStmt == nullptr &&
1954 "No associated statement allowed for 'omp barrier' directive");
1955 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1958 assert(ClausesWithImplicit.empty() &&
1959 "No clauses are allowed for 'omp taskwait' directive");
1960 assert(AStmt == nullptr &&
1961 "No associated statement allowed for 'omp taskwait' directive");
1962 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1964 case OMPD_taskgroup:
1965 assert(ClausesWithImplicit.empty() &&
1966 "No clauses are allowed for 'omp taskgroup' directive");
1967 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
1970 assert(AStmt == nullptr &&
1971 "No associated statement allowed for 'omp flush' directive");
1972 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
1975 assert(ClausesWithImplicit.empty() &&
1976 "No clauses are allowed for 'omp ordered' directive");
1977 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
1980 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
1985 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1988 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
1991 case OMPD_threadprivate:
1992 llvm_unreachable("OpenMP Directive is not allowed");
1994 llvm_unreachable("Unknown OpenMP directive");
1997 for (auto P : VarsWithInheritedDSA) {
1998 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1999 << P.first << P.second->getSourceRange();
2001 if (!VarsWithInheritedDSA.empty())
2009 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2011 SourceLocation StartLoc,
2012 SourceLocation EndLoc) {
2013 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2014 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2015 // 1.2.2 OpenMP Language Terminology
2016 // Structured block - An executable statement with a single entry at the
2017 // top and a single exit at the bottom.
2018 // The point of exit cannot be a branch out of the structured block.
2019 // longjmp() and throw() must not violate the entry/exit criteria.
2020 CS->getCapturedDecl()->setNothrow();
2022 getCurFunction()->setHasBranchProtectedScope();
2024 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
2029 /// \brief Helper class for checking canonical form of the OpenMP loops and
2030 /// extracting iteration space of each loop in the loop nest, that will be used
2031 /// for IR generation.
2032 class OpenMPIterationSpaceChecker {
2033 /// \brief Reference to Sema.
2035 /// \brief A location for diagnostics (when there is no some better location).
2036 SourceLocation DefaultLoc;
2037 /// \brief A location for diagnostics (when increment is not compatible).
2038 SourceLocation ConditionLoc;
2039 /// \brief A source location for referring to loop init later.
2040 SourceRange InitSrcRange;
2041 /// \brief A source location for referring to condition later.
2042 SourceRange ConditionSrcRange;
2043 /// \brief A source location for referring to increment later.
2044 SourceRange IncrementSrcRange;
2045 /// \brief Loop variable.
2047 /// \brief Reference to loop variable.
2048 DeclRefExpr *VarRef;
2049 /// \brief Lower bound (initializer for the var).
2051 /// \brief Upper bound.
2053 /// \brief Loop step (increment).
2055 /// \brief This flag is true when condition is one of:
2061 /// \brief This flag is true when condition is strict ( < or > ).
2062 bool TestIsStrictOp;
2063 /// \brief This flag is true when step is subtracted on each iteration.
2067 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2068 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
2069 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
2070 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
2071 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
2072 TestIsStrictOp(false), SubtractStep(false) {}
2073 /// \brief Check init-expr for canonical loop form and save loop counter
2074 /// variable - #Var and its initialization value - #LB.
2075 bool CheckInit(Stmt *S, bool EmitDiags = true);
2076 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2077 /// for less/greater and for strict/non-strict comparison.
2078 bool CheckCond(Expr *S);
2079 /// \brief Check incr-expr for canonical loop form and return true if it
2080 /// does not conform, otherwise save loop step (#Step).
2081 bool CheckInc(Expr *S);
2082 /// \brief Return the loop counter variable.
2083 VarDecl *GetLoopVar() const { return Var; }
2084 /// \brief Return the reference expression to loop counter variable.
2085 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
2086 /// \brief Source range of the loop init.
2087 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2088 /// \brief Source range of the loop condition.
2089 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2090 /// \brief Source range of the loop increment.
2091 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2092 /// \brief True if the step should be subtracted.
2093 bool ShouldSubtractStep() const { return SubtractStep; }
2094 /// \brief Build the expression to calculate the number of iterations.
2095 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
2096 /// \brief Build the precondition expression for the loops.
2097 Expr *BuildPreCond(Scope *S, Expr *Cond) const;
2098 /// \brief Build reference expression to the counter be used for codegen.
2099 Expr *BuildCounterVar() const;
2100 /// \brief Build initization of the counter be used for codegen.
2101 Expr *BuildCounterInit() const;
2102 /// \brief Build step of the counter be used for codegen.
2103 Expr *BuildCounterStep() const;
2104 /// \brief Return true if any expression is dependent.
2105 bool Dependent() const;
2108 /// \brief Check the right-hand side of an assignment in the increment
2110 bool CheckIncRHS(Expr *RHS);
2111 /// \brief Helper to set loop counter variable and its initializer.
2112 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
2113 /// \brief Helper to set upper bound.
2114 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
2115 const SourceLocation &SL);
2116 /// \brief Helper to set loop increment.
2117 bool SetStep(Expr *NewStep, bool Subtract);
2120 bool OpenMPIterationSpaceChecker::Dependent() const {
2122 assert(!LB && !UB && !Step);
2125 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2126 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2129 bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2130 DeclRefExpr *NewVarRefExpr,
2132 // State consistency checking to ensure correct usage.
2133 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2134 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2135 if (!NewVar || !NewLB)
2138 VarRef = NewVarRefExpr;
2143 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2144 const SourceRange &SR,
2145 const SourceLocation &SL) {
2146 // State consistency checking to ensure correct usage.
2147 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2148 !TestIsLessOp && !TestIsStrictOp);
2152 TestIsLessOp = LessOp;
2153 TestIsStrictOp = StrictOp;
2154 ConditionSrcRange = SR;
2159 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2160 // State consistency checking to ensure correct usage.
2161 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2164 if (!NewStep->isValueDependent()) {
2165 // Check that the step is integer expression.
2166 SourceLocation StepLoc = NewStep->getLocStart();
2168 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2169 if (Val.isInvalid())
2171 NewStep = Val.get();
2173 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2174 // If test-expr is of form var relational-op b and relational-op is < or
2175 // <= then incr-expr must cause var to increase on each iteration of the
2176 // loop. If test-expr is of form var relational-op b and relational-op is
2177 // > or >= then incr-expr must cause var to decrease on each iteration of
2179 // If test-expr is of form b relational-op var and relational-op is < or
2180 // <= then incr-expr must cause var to decrease on each iteration of the
2181 // loop. If test-expr is of form b relational-op var and relational-op is
2182 // > or >= then incr-expr must cause var to increase on each iteration of
2184 llvm::APSInt Result;
2185 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2186 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2188 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
2190 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
2191 bool IsConstZero = IsConstant && !Result.getBoolValue();
2192 if (UB && (IsConstZero ||
2193 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
2194 : (IsConstPos || (IsUnsigned && !Subtract))))) {
2195 SemaRef.Diag(NewStep->getExprLoc(),
2196 diag::err_omp_loop_incr_not_compatible)
2197 << Var << TestIsLessOp << NewStep->getSourceRange();
2198 SemaRef.Diag(ConditionLoc,
2199 diag::note_omp_loop_cond_requres_compatible_incr)
2200 << TestIsLessOp << ConditionSrcRange;
2203 if (TestIsLessOp == Subtract) {
2204 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2206 Subtract = !Subtract;
2211 SubtractStep = Subtract;
2215 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
2216 // Check init-expr for canonical loop form and save loop counter
2217 // variable - #Var and its initialization value - #LB.
2218 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2220 // integer-type var = lb
2221 // random-access-iterator-type var = lb
2222 // pointer-type var = lb
2226 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2230 InitSrcRange = S->getSourceRange();
2231 if (Expr *E = dyn_cast<Expr>(S))
2232 S = E->IgnoreParens();
2233 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2234 if (BO->getOpcode() == BO_Assign)
2235 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
2236 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2238 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2239 if (DS->isSingleDecl()) {
2240 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2241 if (Var->hasInit()) {
2242 // Accept non-canonical init form here but emit ext. warning.
2243 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
2244 SemaRef.Diag(S->getLocStart(),
2245 diag::ext_omp_loop_not_canonical_init)
2246 << S->getSourceRange();
2247 return SetVarAndLB(Var, nullptr, Var->getInit());
2251 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2252 if (CE->getOperator() == OO_Equal)
2253 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
2254 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2258 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2259 << S->getSourceRange();
2264 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
2265 /// variable (which may be the loop variable) if possible.
2266 static const VarDecl *GetInitVarDecl(const Expr *E) {
2269 E = E->IgnoreParenImpCasts();
2270 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2271 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2272 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
2273 CE->getArg(0) != nullptr)
2274 E = CE->getArg(0)->IgnoreParenImpCasts();
2275 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2278 return dyn_cast<VarDecl>(DRE->getDecl());
2281 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2282 // Check test-expr for canonical form, save upper-bound UB, flags for
2283 // less/greater and for strict/non-strict comparison.
2284 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2285 // var relational-op b
2286 // b relational-op var
2289 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2292 S = S->IgnoreParenImpCasts();
2293 SourceLocation CondLoc = S->getLocStart();
2294 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2295 if (BO->isRelationalOp()) {
2296 if (GetInitVarDecl(BO->getLHS()) == Var)
2297 return SetUB(BO->getRHS(),
2298 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2299 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2300 BO->getSourceRange(), BO->getOperatorLoc());
2301 if (GetInitVarDecl(BO->getRHS()) == Var)
2302 return SetUB(BO->getLHS(),
2303 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2304 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2305 BO->getSourceRange(), BO->getOperatorLoc());
2307 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2308 if (CE->getNumArgs() == 2) {
2309 auto Op = CE->getOperator();
2312 case OO_GreaterEqual:
2315 if (GetInitVarDecl(CE->getArg(0)) == Var)
2316 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2317 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2318 CE->getOperatorLoc());
2319 if (GetInitVarDecl(CE->getArg(1)) == Var)
2320 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2321 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2322 CE->getOperatorLoc());
2329 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2330 << S->getSourceRange() << Var;
2334 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2335 // RHS of canonical loop form increment can be:
2340 RHS = RHS->IgnoreParenImpCasts();
2341 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2342 if (BO->isAdditiveOp()) {
2343 bool IsAdd = BO->getOpcode() == BO_Add;
2344 if (GetInitVarDecl(BO->getLHS()) == Var)
2345 return SetStep(BO->getRHS(), !IsAdd);
2346 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2347 return SetStep(BO->getLHS(), false);
2349 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2350 bool IsAdd = CE->getOperator() == OO_Plus;
2351 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2352 if (GetInitVarDecl(CE->getArg(0)) == Var)
2353 return SetStep(CE->getArg(1), !IsAdd);
2354 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2355 return SetStep(CE->getArg(0), false);
2358 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2359 << RHS->getSourceRange() << Var;
2363 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2364 // Check incr-expr for canonical loop form and return true if it
2365 // does not conform.
2366 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2378 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2381 IncrementSrcRange = S->getSourceRange();
2382 S = S->IgnoreParens();
2383 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2384 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2386 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2387 (UO->isDecrementOp() ? -1 : 1)).get(),
2389 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2390 switch (BO->getOpcode()) {
2393 if (GetInitVarDecl(BO->getLHS()) == Var)
2394 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2397 if (GetInitVarDecl(BO->getLHS()) == Var)
2398 return CheckIncRHS(BO->getRHS());
2403 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2404 switch (CE->getOperator()) {
2407 if (GetInitVarDecl(CE->getArg(0)) == Var)
2409 SemaRef.ActOnIntegerConstant(
2411 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2416 if (GetInitVarDecl(CE->getArg(0)) == Var)
2417 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2420 if (GetInitVarDecl(CE->getArg(0)) == Var)
2421 return CheckIncRHS(CE->getArg(1));
2427 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2428 << S->getSourceRange() << Var;
2432 /// \brief Build the expression to calculate the number of iterations.
2434 OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2435 const bool LimitedType) const {
2437 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2438 SemaRef.getLangOpts().CPlusPlus) {
2440 Expr *Upper = TestIsLessOp ? UB : LB;
2441 Expr *Lower = TestIsLessOp ? LB : UB;
2443 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2445 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2446 // BuildBinOp already emitted error, this one is to point user to upper
2447 // and lower bound, and to tell what is passed to 'operator-'.
2448 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2449 << Upper->getSourceRange() << Lower->getSourceRange();
2454 if (!Diff.isUsable())
2457 // Upper - Lower [- 1]
2459 Diff = SemaRef.BuildBinOp(
2460 S, DefaultLoc, BO_Sub, Diff.get(),
2461 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2462 if (!Diff.isUsable())
2465 // Upper - Lower [- 1] + Step
2466 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2467 Step->IgnoreImplicit());
2468 if (!Diff.isUsable())
2471 // Parentheses (for dumping/debugging purposes only).
2472 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2473 if (!Diff.isUsable())
2476 // (Upper - Lower [- 1] + Step) / Step
2477 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2478 Step->IgnoreImplicit());
2479 if (!Diff.isUsable())
2482 // OpenMP runtime requires 32-bit or 64-bit loop variables.
2484 auto &C = SemaRef.Context;
2485 QualType Type = Diff.get()->getType();
2486 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2487 if (NewSize != C.getTypeSize(Type)) {
2488 if (NewSize < C.getTypeSize(Type)) {
2489 assert(NewSize == 64 && "incorrect loop var size");
2490 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2491 << InitSrcRange << ConditionSrcRange;
2493 QualType NewType = C.getIntTypeForBitwidth(
2494 NewSize, Type->hasSignedIntegerRepresentation());
2495 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2496 Sema::AA_Converting, true);
2497 if (!Diff.isUsable())
2505 Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
2506 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
2507 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
2508 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
2509 auto CondExpr = SemaRef.BuildBinOp(
2510 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
2511 : (TestIsStrictOp ? BO_GT : BO_GE),
2513 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
2514 // Otherwise use original loop conditon and evaluate it in runtime.
2515 return CondExpr.isUsable() ? CondExpr.get() : Cond;
2518 /// \brief Build reference expression to the counter be used for codegen.
2519 Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
2520 return buildDeclRefExpr(SemaRef, Var, Var->getType(), DefaultLoc);
2523 /// \brief Build initization of the counter be used for codegen.
2524 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2526 /// \brief Build step of the counter be used for codegen.
2527 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2529 /// \brief Iteration space of a single for loop.
2530 struct LoopIterationSpace {
2531 /// \brief Condition of the loop.
2533 /// \brief This expression calculates the number of iterations in the loop.
2534 /// It is always possible to calculate it before starting the loop.
2535 Expr *NumIterations;
2536 /// \brief The loop counter variable.
2538 /// \brief This is initializer for the initial value of #CounterVar.
2540 /// \brief This is step for the #CounterVar used to generate its update:
2541 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2543 /// \brief Should step be subtracted?
2545 /// \brief Source range of the loop init.
2546 SourceRange InitSrcRange;
2547 /// \brief Source range of the loop condition.
2548 SourceRange CondSrcRange;
2549 /// \brief Source range of the loop increment.
2550 SourceRange IncSrcRange;
2555 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
2556 assert(getLangOpts().OpenMP && "OpenMP is not active.");
2557 assert(Init && "Expected loop in canonical form.");
2558 unsigned CollapseIteration = DSAStack->getCollapseNumber();
2559 if (CollapseIteration > 0 &&
2560 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2561 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
2562 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
2563 DSAStack->addLoopControlVariable(ISC.GetLoopVar());
2565 DSAStack->setCollapseNumber(CollapseIteration - 1);
2569 /// \brief Called on a for stmt to check and extract its iteration space
2570 /// for further processing (such as collapsing).
2571 static bool CheckOpenMPIterationSpace(
2572 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2573 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2574 Expr *NestedLoopCountExpr,
2575 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2576 LoopIterationSpace &ResultIterSpace) {
2577 // OpenMP [2.6, Canonical Loop Form]
2578 // for (init-expr; test-expr; incr-expr) structured-block
2579 auto For = dyn_cast_or_null<ForStmt>(S);
2581 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
2582 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2583 << NestedLoopCount << (CurrentNestedLoopCount > 0)
2584 << CurrentNestedLoopCount;
2585 if (NestedLoopCount > 1)
2586 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2587 diag::note_omp_collapse_expr)
2588 << NestedLoopCountExpr->getSourceRange();
2591 assert(For->getBody());
2593 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2596 auto Init = For->getInit();
2597 if (ISC.CheckInit(Init)) {
2601 bool HasErrors = false;
2603 // Check loop variable's type.
2604 auto Var = ISC.GetLoopVar();
2606 // OpenMP [2.6, Canonical Loop Form]
2607 // Var is one of the following:
2608 // A variable of signed or unsigned integer type.
2609 // For C++, a variable of a random access iterator type.
2610 // For C, a variable of a pointer type.
2611 auto VarType = Var->getType();
2612 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2613 !VarType->isPointerType() &&
2614 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2615 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2616 << SemaRef.getLangOpts().CPlusPlus;
2620 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2622 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2623 // parallel for construct is (are) private.
2624 // The loop iteration variable in the associated for-loop of a simd construct
2625 // with just one associated for-loop is linear with a constant-linear-step
2626 // that is the increment of the associated for-loop.
2627 // Exclude loop var from the list of variables with implicitly defined data
2628 // sharing attributes.
2629 VarsWithImplicitDSA.erase(Var);
2631 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2632 // a Construct, C/C++].
2633 // The loop iteration variable in the associated for-loop of a simd construct
2634 // with just one associated for-loop may be listed in a linear clause with a
2635 // constant-linear-step that is the increment of the associated for-loop.
2636 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2637 // parallel for construct may be listed in a private or lastprivate clause.
2638 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
2639 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2640 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2641 // declared in the loop and it is predetermined as a private.
2642 auto PredeterminedCKind =
2643 isOpenMPSimdDirective(DKind)
2644 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2646 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
2647 DVar.CKind != OMPC_threadprivate && DVar.CKind != PredeterminedCKind) ||
2648 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2649 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
2650 DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_threadprivate)) &&
2651 ((DVar.CKind != OMPC_private && DVar.CKind != OMPC_threadprivate) ||
2652 DVar.RefExpr != nullptr)) {
2653 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
2654 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2655 << getOpenMPClauseName(PredeterminedCKind);
2656 if (DVar.RefExpr == nullptr)
2657 DVar.CKind = PredeterminedCKind;
2658 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
2660 } else if (LoopVarRefExpr != nullptr) {
2661 // Make the loop iteration variable private (for worksharing constructs),
2662 // linear (for simd directives with the only one associated loop) or
2663 // lastprivate (for simd directives with several collapsed loops).
2664 if (DVar.CKind == OMPC_unknown)
2665 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2666 /*FromParent=*/false);
2667 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
2670 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
2673 HasErrors |= ISC.CheckCond(For->getCond());
2676 HasErrors |= ISC.CheckInc(For->getInc());
2678 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
2681 // Build the loop's iteration space representation.
2682 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
2683 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2684 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
2685 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2686 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2687 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2688 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2689 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2690 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2691 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2693 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
2694 ResultIterSpace.NumIterations == nullptr ||
2695 ResultIterSpace.CounterVar == nullptr ||
2696 ResultIterSpace.CounterInit == nullptr ||
2697 ResultIterSpace.CounterStep == nullptr);
2702 /// \brief Build 'VarRef = Start + Iter * Step'.
2703 static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2704 SourceLocation Loc, ExprResult VarRef,
2705 ExprResult Start, ExprResult Iter,
2706 ExprResult Step, bool Subtract) {
2707 // Add parentheses (for debugging purposes only).
2708 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2709 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2713 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2714 Step.get()->IgnoreImplicit());
2715 if (!Update.isUsable())
2718 // Build 'VarRef = Start + Iter * Step'.
2719 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2720 Start.get()->IgnoreImplicit(), Update.get());
2721 if (!Update.isUsable())
2724 Update = SemaRef.PerformImplicitConversion(
2725 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2726 if (!Update.isUsable())
2729 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2733 /// \brief Convert integer expression \a E to make it have at least \a Bits
2735 static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2739 auto &C = SemaRef.Context;
2740 QualType OldType = E->getType();
2741 unsigned HasBits = C.getTypeSize(OldType);
2742 if (HasBits >= Bits)
2743 return ExprResult(E);
2744 // OK to convert to signed, because new type has more bits than old.
2745 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2746 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2750 /// \brief Check if the given expression \a E is a constant integer that fits
2751 /// into \a Bits bits.
2752 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2755 llvm::APSInt Result;
2756 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2757 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2761 /// \brief Called on a for stmt to check itself and nested loops (if any).
2762 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2763 /// number of collapsed loops otherwise.
2765 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2766 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
2767 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2768 OMPLoopDirective::HelperExprs &Built) {
2769 unsigned NestedLoopCount = 1;
2770 if (NestedLoopCountExpr) {
2771 // Found 'collapse' clause - calculate collapse number.
2772 llvm::APSInt Result;
2773 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2774 NestedLoopCount = Result.getLimitedValue();
2776 // This is helper routine for loop directives (e.g., 'for', 'simd',
2777 // 'for simd', etc.).
2778 SmallVector<LoopIterationSpace, 4> IterSpaces;
2779 IterSpaces.resize(NestedLoopCount);
2780 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
2781 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
2782 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
2783 NestedLoopCount, NestedLoopCountExpr,
2784 VarsWithImplicitDSA, IterSpaces[Cnt]))
2786 // Move on to the next nested for loop, or to the loop body.
2787 // OpenMP [2.8.1, simd construct, Restrictions]
2788 // All loops associated with the construct must be perfectly nested; that
2789 // is, there must be no intervening code nor any OpenMP directive between
2791 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
2794 Built.clear(/* size */ NestedLoopCount);
2796 if (SemaRef.CurContext->isDependentContext())
2797 return NestedLoopCount;
2799 // An example of what is generated for the following code:
2801 // #pragma omp simd collapse(2)
2802 // for (i = 0; i < NI; ++i)
2803 // for (j = J0; j < NJ; j+=2) {
2807 // We generate the code below.
2808 // Note: the loop body may be outlined in CodeGen.
2809 // Note: some counters may be C++ classes, operator- is used to find number of
2810 // iterations and operator+= to calculate counter value.
2811 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2812 // or i64 is currently supported).
2814 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2815 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2816 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2817 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2818 // // similar updates for vars in clauses (e.g. 'linear')
2819 // <loop body (using local i and j)>
2821 // i = NI; // assign final values of counters
2825 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2826 // the iteration counts of the collapsed for loops.
2827 // Precondition tests if there is at least one iteration (all conditions are
2829 auto PreCond = ExprResult(IterSpaces[0].PreCond);
2830 auto N0 = IterSpaces[0].NumIterations;
2831 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2832 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2834 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2835 return NestedLoopCount;
2837 auto &C = SemaRef.Context;
2838 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
2840 Scope *CurScope = DSA.getCurScope();
2841 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
2842 if (PreCond.isUsable()) {
2843 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
2844 PreCond.get(), IterSpaces[Cnt].PreCond);
2846 auto N = IterSpaces[Cnt].NumIterations;
2847 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
2848 if (LastIteration32.isUsable())
2849 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2850 LastIteration32.get(), N);
2851 if (LastIteration64.isUsable())
2852 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2853 LastIteration64.get(), N);
2856 // Choose either the 32-bit or 64-bit version.
2857 ExprResult LastIteration = LastIteration64;
2858 if (LastIteration32.isUsable() &&
2859 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
2860 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
2863 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
2864 LastIteration64.get(), SemaRef)))
2865 LastIteration = LastIteration32;
2867 if (!LastIteration.isUsable())
2870 // Save the number of iterations.
2871 ExprResult NumIterations = LastIteration;
2873 LastIteration = SemaRef.BuildBinOp(
2874 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
2875 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2876 if (!LastIteration.isUsable())
2880 // Calculate the last iteration number beforehand instead of doing this on
2881 // each iteration. Do not do this if the number of iterations may be kfold-ed.
2882 llvm::APSInt Result;
2884 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
2885 ExprResult CalcLastIteration;
2887 SourceLocation SaveLoc;
2889 buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
2890 ".omp.last.iteration");
2891 ExprResult SaveRef = buildDeclRefExpr(
2892 SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
2893 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
2894 SaveRef.get(), LastIteration.get());
2895 LastIteration = SaveRef;
2897 // Prepare SaveRef + 1.
2898 NumIterations = SemaRef.BuildBinOp(
2899 CurScope, SaveLoc, BO_Add, SaveRef.get(),
2900 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2901 if (!NumIterations.isUsable())
2905 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
2907 QualType VType = LastIteration.get()->getType();
2908 // Build variables passed into runtime, nesessary for worksharing directives.
2909 ExprResult LB, UB, IL, ST, EUB;
2910 if (isOpenMPWorksharingDirective(DKind)) {
2911 // Lower bound variable, initialized with zero.
2912 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
2913 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
2914 SemaRef.AddInitializerToDecl(
2915 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2916 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2918 // Upper bound variable, initialized with last iteration number.
2919 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
2920 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
2921 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
2922 /*DirectInit*/ false,
2923 /*TypeMayContainAuto*/ false);
2925 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
2926 // This will be used to implement clause 'lastprivate'.
2927 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
2928 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
2929 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
2930 SemaRef.AddInitializerToDecl(
2931 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2932 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2934 // Stride variable returned by runtime (we initialize it to 1 by default).
2935 VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
2936 ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
2937 SemaRef.AddInitializerToDecl(
2938 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
2939 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2941 // Build expression: UB = min(UB, LastIteration)
2942 // It is nesessary for CodeGen of directives with static scheduling.
2943 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
2944 UB.get(), LastIteration.get());
2945 ExprResult CondOp = SemaRef.ActOnConditionalOp(
2946 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
2947 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
2949 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
2952 // Build the iteration variable and its initialization before loop.
2956 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
2957 IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
2958 Expr *RHS = isOpenMPWorksharingDirective(DKind)
2960 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
2961 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
2962 Init = SemaRef.ActOnFinishFullExpr(Init.get());
2965 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
2966 SourceLocation CondLoc;
2968 isOpenMPWorksharingDirective(DKind)
2969 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
2970 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
2971 NumIterations.get());
2973 // Loop increment (IV = IV + 1)
2974 SourceLocation IncLoc;
2976 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
2977 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
2978 if (!Inc.isUsable())
2980 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
2981 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
2982 if (!Inc.isUsable())
2985 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
2986 // Used for directives with static scheduling.
2987 ExprResult NextLB, NextUB;
2988 if (isOpenMPWorksharingDirective(DKind)) {
2990 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
2991 if (!NextLB.isUsable())
2995 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
2996 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
2997 if (!NextLB.isUsable())
3000 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
3001 if (!NextUB.isUsable())
3005 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
3006 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
3007 if (!NextUB.isUsable())
3011 // Build updates and final values of the loop counters.
3012 bool HasErrors = false;
3013 Built.Counters.resize(NestedLoopCount);
3014 Built.Updates.resize(NestedLoopCount);
3015 Built.Finals.resize(NestedLoopCount);
3018 // Go from inner nested loop to outer.
3019 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
3020 LoopIterationSpace &IS = IterSpaces[Cnt];
3021 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
3022 // Build: Iter = (IV / Div) % IS.NumIters
3023 // where Div is product of previous iterations' IS.NumIters.
3025 if (Div.isUsable()) {
3027 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
3030 assert((Cnt == (int)NestedLoopCount - 1) &&
3031 "unusable div expected on first iteration only");
3034 if (Cnt != 0 && Iter.isUsable())
3035 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
3037 if (!Iter.isUsable()) {
3042 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
3043 auto *CounterVar = buildDeclRefExpr(
3044 SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
3045 IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
3046 /*RefersToCapture=*/true);
3048 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
3049 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
3050 if (!Update.isUsable()) {
3055 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
3056 ExprResult Final = BuildCounterUpdate(
3057 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
3058 IS.NumIterations, IS.CounterStep, IS.Subtract);
3059 if (!Final.isUsable()) {
3064 // Build Div for the next iteration: Div <- Div * IS.NumIters
3067 Div = IS.NumIterations;
3069 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
3072 // Add parentheses (for debugging purposes only).
3074 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
3075 if (!Div.isUsable()) {
3080 if (!Update.isUsable() || !Final.isUsable()) {
3085 Built.Counters[Cnt] = IS.CounterVar;
3086 Built.Updates[Cnt] = Update.get();
3087 Built.Finals[Cnt] = Final.get();
3095 Built.IterationVarRef = IV.get();
3096 Built.LastIteration = LastIteration.get();
3097 Built.NumIterations = NumIterations.get();
3098 Built.CalcLastIteration = CalcLastIteration.get();
3099 Built.PreCond = PreCond.get();
3100 Built.Cond = Cond.get();
3101 Built.Init = Init.get();
3102 Built.Inc = Inc.get();
3103 Built.LB = LB.get();
3104 Built.UB = UB.get();
3105 Built.IL = IL.get();
3106 Built.ST = ST.get();
3107 Built.EUB = EUB.get();
3108 Built.NLB = NextLB.get();
3109 Built.NUB = NextUB.get();
3111 return NestedLoopCount;
3114 static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
3115 auto &&CollapseFilter = [](const OMPClause *C) -> bool {
3116 return C->getClauseKind() == OMPC_collapse;
3118 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
3119 Clauses, std::move(CollapseFilter));
3121 return cast<OMPCollapseClause>(*I)->getNumForLoops();
3125 StmtResult Sema::ActOnOpenMPSimdDirective(
3126 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3127 SourceLocation EndLoc,
3128 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3129 OMPLoopDirective::HelperExprs B;
3130 // In presence of clause 'collapse', it will define the nested loops number.
3131 unsigned NestedLoopCount =
3132 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
3133 *DSAStack, VarsWithImplicitDSA, B);
3134 if (NestedLoopCount == 0)
3137 assert((CurContext->isDependentContext() || B.builtAll()) &&
3138 "omp simd loop exprs were not built");
3140 if (!CurContext->isDependentContext()) {
3141 // Finalize the clauses that need pre-built expressions for CodeGen.
3142 for (auto C : Clauses) {
3143 if (auto LC = dyn_cast<OMPLinearClause>(C))
3144 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3145 B.NumIterations, *this, CurScope))
3150 getCurFunction()->setHasBranchProtectedScope();
3151 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3155 StmtResult Sema::ActOnOpenMPForDirective(
3156 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3157 SourceLocation EndLoc,
3158 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3159 OMPLoopDirective::HelperExprs B;
3160 // In presence of clause 'collapse', it will define the nested loops number.
3161 unsigned NestedLoopCount =
3162 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
3163 *DSAStack, VarsWithImplicitDSA, B);
3164 if (NestedLoopCount == 0)
3167 assert((CurContext->isDependentContext() || B.builtAll()) &&
3168 "omp for loop exprs were not built");
3170 getCurFunction()->setHasBranchProtectedScope();
3171 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3175 StmtResult Sema::ActOnOpenMPForSimdDirective(
3176 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3177 SourceLocation EndLoc,
3178 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3179 OMPLoopDirective::HelperExprs B;
3180 // In presence of clause 'collapse', it will define the nested loops number.
3181 unsigned NestedLoopCount =
3182 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
3183 *this, *DSAStack, VarsWithImplicitDSA, B);
3184 if (NestedLoopCount == 0)
3187 assert((CurContext->isDependentContext() || B.builtAll()) &&
3188 "omp for simd loop exprs were not built");
3190 if (!CurContext->isDependentContext()) {
3191 // Finalize the clauses that need pre-built expressions for CodeGen.
3192 for (auto C : Clauses) {
3193 if (auto LC = dyn_cast<OMPLinearClause>(C))
3194 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3195 B.NumIterations, *this, CurScope))
3200 getCurFunction()->setHasBranchProtectedScope();
3201 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3205 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3207 SourceLocation StartLoc,
3208 SourceLocation EndLoc) {
3209 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3210 auto BaseStmt = AStmt;
3211 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3212 BaseStmt = CS->getCapturedStmt();
3213 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3214 auto S = C->children();
3217 // All associated statements must be '#pragma omp section' except for
3220 auto SectionStmt = *S;
3221 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3223 Diag(SectionStmt->getLocStart(),
3224 diag::err_omp_sections_substmt_not_section);
3229 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3233 getCurFunction()->setHasBranchProtectedScope();
3235 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3239 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3240 SourceLocation StartLoc,
3241 SourceLocation EndLoc) {
3242 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3244 getCurFunction()->setHasBranchProtectedScope();
3246 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3249 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3251 SourceLocation StartLoc,
3252 SourceLocation EndLoc) {
3253 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3255 getCurFunction()->setHasBranchProtectedScope();
3257 // OpenMP [2.7.3, single Construct, Restrictions]
3258 // The copyprivate clause must not be used with the nowait clause.
3259 OMPClause *Nowait = nullptr;
3260 OMPClause *Copyprivate = nullptr;
3261 for (auto *Clause : Clauses) {
3262 if (Clause->getClauseKind() == OMPC_nowait)
3264 else if (Clause->getClauseKind() == OMPC_copyprivate)
3265 Copyprivate = Clause;
3266 if (Copyprivate && Nowait) {
3267 Diag(Copyprivate->getLocStart(),
3268 diag::err_omp_single_copyprivate_with_nowait);
3269 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3274 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3277 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3278 SourceLocation StartLoc,
3279 SourceLocation EndLoc) {
3280 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3282 getCurFunction()->setHasBranchProtectedScope();
3284 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3288 Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3289 Stmt *AStmt, SourceLocation StartLoc,
3290 SourceLocation EndLoc) {
3291 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3293 getCurFunction()->setHasBranchProtectedScope();
3295 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3299 StmtResult Sema::ActOnOpenMPParallelForDirective(
3300 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3301 SourceLocation EndLoc,
3302 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3303 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3304 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3305 // 1.2.2 OpenMP Language Terminology
3306 // Structured block - An executable statement with a single entry at the
3307 // top and a single exit at the bottom.
3308 // The point of exit cannot be a branch out of the structured block.
3309 // longjmp() and throw() must not violate the entry/exit criteria.
3310 CS->getCapturedDecl()->setNothrow();
3312 OMPLoopDirective::HelperExprs B;
3313 // In presence of clause 'collapse', it will define the nested loops number.
3314 unsigned NestedLoopCount =
3315 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
3316 *this, *DSAStack, VarsWithImplicitDSA, B);
3317 if (NestedLoopCount == 0)
3320 assert((CurContext->isDependentContext() || B.builtAll()) &&
3321 "omp parallel for loop exprs were not built");
3323 getCurFunction()->setHasBranchProtectedScope();
3324 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3325 NestedLoopCount, Clauses, AStmt, B);
3328 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3329 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3330 SourceLocation EndLoc,
3331 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3332 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3333 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3334 // 1.2.2 OpenMP Language Terminology
3335 // Structured block - An executable statement with a single entry at the
3336 // top and a single exit at the bottom.
3337 // The point of exit cannot be a branch out of the structured block.
3338 // longjmp() and throw() must not violate the entry/exit criteria.
3339 CS->getCapturedDecl()->setNothrow();
3341 OMPLoopDirective::HelperExprs B;
3342 // In presence of clause 'collapse', it will define the nested loops number.
3343 unsigned NestedLoopCount =
3344 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
3345 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
3346 if (NestedLoopCount == 0)
3349 if (!CurContext->isDependentContext()) {
3350 // Finalize the clauses that need pre-built expressions for CodeGen.
3351 for (auto C : Clauses) {
3352 if (auto LC = dyn_cast<OMPLinearClause>(C))
3353 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3354 B.NumIterations, *this, CurScope))
3359 getCurFunction()->setHasBranchProtectedScope();
3360 return OMPParallelForSimdDirective::Create(
3361 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
3365 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3366 Stmt *AStmt, SourceLocation StartLoc,
3367 SourceLocation EndLoc) {
3368 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3369 auto BaseStmt = AStmt;
3370 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3371 BaseStmt = CS->getCapturedStmt();
3372 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3373 auto S = C->children();
3376 // All associated statements must be '#pragma omp section' except for
3379 auto SectionStmt = *S;
3380 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3382 Diag(SectionStmt->getLocStart(),
3383 diag::err_omp_parallel_sections_substmt_not_section);
3388 Diag(AStmt->getLocStart(),
3389 diag::err_omp_parallel_sections_not_compound_stmt);
3393 getCurFunction()->setHasBranchProtectedScope();
3395 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3399 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3400 Stmt *AStmt, SourceLocation StartLoc,
3401 SourceLocation EndLoc) {
3402 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3403 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3404 // 1.2.2 OpenMP Language Terminology
3405 // Structured block - An executable statement with a single entry at the
3406 // top and a single exit at the bottom.
3407 // The point of exit cannot be a branch out of the structured block.
3408 // longjmp() and throw() must not violate the entry/exit criteria.
3409 CS->getCapturedDecl()->setNothrow();
3411 getCurFunction()->setHasBranchProtectedScope();
3413 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3416 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3417 SourceLocation EndLoc) {
3418 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3421 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3422 SourceLocation EndLoc) {
3423 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3426 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3427 SourceLocation EndLoc) {
3428 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3431 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
3432 SourceLocation StartLoc,
3433 SourceLocation EndLoc) {
3434 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3436 getCurFunction()->setHasBranchProtectedScope();
3438 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
3441 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3442 SourceLocation StartLoc,
3443 SourceLocation EndLoc) {
3444 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3445 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3448 StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3449 SourceLocation StartLoc,
3450 SourceLocation EndLoc) {
3451 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3453 getCurFunction()->setHasBranchProtectedScope();
3455 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3459 /// \brief Helper class for checking expression in 'omp atomic [update]'
3461 class OpenMPAtomicUpdateChecker {
3462 /// \brief Error results for atomic update expressions.
3463 enum ExprAnalysisErrorCode {
3464 /// \brief A statement is not an expression statement.
3466 /// \brief Expression is not builtin binary or unary operation.
3467 NotABinaryOrUnaryExpression,
3468 /// \brief Unary operation is not post-/pre- increment/decrement operation.
3469 NotAnUnaryIncDecExpression,
3470 /// \brief An expression is not of scalar type.
3472 /// \brief A binary operation is not an assignment operation.
3474 /// \brief RHS part of the binary operation is not a binary expression.
3475 NotABinaryExpression,
3476 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
3479 /// \brief RHS binary operation does not have reference to the updated LHS
3481 NotAnUpdateExpression,
3482 /// \brief No errors is found.
3485 /// \brief Reference to Sema.
3487 /// \brief A location for note diagnostics (when error is found).
3488 SourceLocation NoteLoc;
3489 /// \brief 'x' lvalue part of the source atomic expression.
3491 /// \brief 'expr' rvalue part of the source atomic expression.
3493 /// \brief Helper expression of the form
3494 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3495 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3497 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
3498 /// important for non-associative operations.
3499 bool IsXLHSInRHSPart;
3500 BinaryOperatorKind Op;
3501 SourceLocation OpLoc;
3502 /// \brief true if the source expression is a postfix unary operation, false
3503 /// if it is a prefix unary operation.
3504 bool IsPostfixUpdate;
3507 OpenMPAtomicUpdateChecker(Sema &SemaRef)
3508 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
3509 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
3510 /// \brief Check specified statement that it is suitable for 'atomic update'
3511 /// constructs and extract 'x', 'expr' and Operation from the original
3512 /// expression. If DiagId and NoteId == 0, then only check is performed
3513 /// without error notification.
3514 /// \param DiagId Diagnostic which should be emitted if error is found.
3515 /// \param NoteId Diagnostic note for the main error message.
3516 /// \return true if statement is not an update expression, false otherwise.
3517 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
3518 /// \brief Return the 'x' lvalue part of the source atomic expression.
3519 Expr *getX() const { return X; }
3520 /// \brief Return the 'expr' rvalue part of the source atomic expression.
3521 Expr *getExpr() const { return E; }
3522 /// \brief Return the update expression used in calculation of the updated
3523 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3524 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3525 Expr *getUpdateExpr() const { return UpdateExpr; }
3526 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
3527 /// false otherwise.
3528 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
3530 /// \brief true if the source expression is a postfix unary operation, false
3531 /// if it is a prefix unary operation.
3532 bool isPostfixUpdate() const { return IsPostfixUpdate; }
3535 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
3536 unsigned NoteId = 0);
3540 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
3541 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
3542 ExprAnalysisErrorCode ErrorFound = NoError;
3543 SourceLocation ErrorLoc, NoteLoc;
3544 SourceRange ErrorRange, NoteRange;
3545 // Allowed constructs are:
3546 // x = x binop expr;
3547 // x = expr binop x;
3548 if (AtomicBinOp->getOpcode() == BO_Assign) {
3549 X = AtomicBinOp->getLHS();
3550 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
3551 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
3552 if (AtomicInnerBinOp->isMultiplicativeOp() ||
3553 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
3554 AtomicInnerBinOp->isBitwiseOp()) {
3555 Op = AtomicInnerBinOp->getOpcode();
3556 OpLoc = AtomicInnerBinOp->getOperatorLoc();
3557 auto *LHS = AtomicInnerBinOp->getLHS();
3558 auto *RHS = AtomicInnerBinOp->getRHS();
3559 llvm::FoldingSetNodeID XId, LHSId, RHSId;
3560 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
3561 /*Canonical=*/true);
3562 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
3563 /*Canonical=*/true);
3564 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
3565 /*Canonical=*/true);
3568 IsXLHSInRHSPart = true;
3569 } else if (XId == RHSId) {
3571 IsXLHSInRHSPart = false;
3573 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3574 ErrorRange = AtomicInnerBinOp->getSourceRange();
3575 NoteLoc = X->getExprLoc();
3576 NoteRange = X->getSourceRange();
3577 ErrorFound = NotAnUpdateExpression;
3580 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3581 ErrorRange = AtomicInnerBinOp->getSourceRange();
3582 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
3583 NoteRange = SourceRange(NoteLoc, NoteLoc);
3584 ErrorFound = NotABinaryOperator;
3587 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
3588 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
3589 ErrorFound = NotABinaryExpression;
3592 ErrorLoc = AtomicBinOp->getExprLoc();
3593 ErrorRange = AtomicBinOp->getSourceRange();
3594 NoteLoc = AtomicBinOp->getOperatorLoc();
3595 NoteRange = SourceRange(NoteLoc, NoteLoc);
3596 ErrorFound = NotAnAssignmentOp;
3598 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
3599 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3600 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3602 } else if (SemaRef.CurContext->isDependentContext())
3603 E = X = UpdateExpr = nullptr;
3604 return ErrorFound != NoError;
3607 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
3609 ExprAnalysisErrorCode ErrorFound = NoError;
3610 SourceLocation ErrorLoc, NoteLoc;
3611 SourceRange ErrorRange, NoteRange;
3612 // Allowed constructs are:
3618 // x = x binop expr;
3619 // x = expr binop x;
3620 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
3621 AtomicBody = AtomicBody->IgnoreParenImpCasts();
3622 if (AtomicBody->getType()->isScalarType() ||
3623 AtomicBody->isInstantiationDependent()) {
3624 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
3625 AtomicBody->IgnoreParenImpCasts())) {
3626 // Check for Compound Assignment Operation
3627 Op = BinaryOperator::getOpForCompoundAssignment(
3628 AtomicCompAssignOp->getOpcode());
3629 OpLoc = AtomicCompAssignOp->getOperatorLoc();
3630 E = AtomicCompAssignOp->getRHS();
3631 X = AtomicCompAssignOp->getLHS();
3632 IsXLHSInRHSPart = true;
3633 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
3634 AtomicBody->IgnoreParenImpCasts())) {
3635 // Check for Binary Operation
3636 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
3638 } else if (auto *AtomicUnaryOp =
3639 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
3640 // Check for Unary Operation
3641 if (AtomicUnaryOp->isIncrementDecrementOp()) {
3642 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
3643 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
3644 OpLoc = AtomicUnaryOp->getOperatorLoc();
3645 X = AtomicUnaryOp->getSubExpr();
3646 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
3647 IsXLHSInRHSPart = true;
3649 ErrorFound = NotAnUnaryIncDecExpression;
3650 ErrorLoc = AtomicUnaryOp->getExprLoc();
3651 ErrorRange = AtomicUnaryOp->getSourceRange();
3652 NoteLoc = AtomicUnaryOp->getOperatorLoc();
3653 NoteRange = SourceRange(NoteLoc, NoteLoc);
3656 ErrorFound = NotABinaryOrUnaryExpression;
3657 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
3658 NoteRange = ErrorRange = AtomicBody->getSourceRange();
3661 ErrorFound = NotAScalarType;
3662 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
3663 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3666 ErrorFound = NotAnExpression;
3667 NoteLoc = ErrorLoc = S->getLocStart();
3668 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3670 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
3671 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3672 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3674 } else if (SemaRef.CurContext->isDependentContext())
3675 E = X = UpdateExpr = nullptr;
3676 if (ErrorFound == NoError && E && X) {
3677 // Build an update expression of form 'OpaqueValueExpr(x) binop
3678 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
3679 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
3680 auto *OVEX = new (SemaRef.getASTContext())
3681 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
3682 auto *OVEExpr = new (SemaRef.getASTContext())
3683 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
3685 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
3686 IsXLHSInRHSPart ? OVEExpr : OVEX);
3687 if (Update.isInvalid())
3689 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
3691 if (Update.isInvalid())
3693 UpdateExpr = Update.get();
3695 return ErrorFound != NoError;
3698 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3700 SourceLocation StartLoc,
3701 SourceLocation EndLoc) {
3702 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3703 auto CS = cast<CapturedStmt>(AStmt);
3704 // 1.2.2 OpenMP Language Terminology
3705 // Structured block - An executable statement with a single entry at the
3706 // top and a single exit at the bottom.
3707 // The point of exit cannot be a branch out of the structured block.
3708 // longjmp() and throw() must not violate the entry/exit criteria.
3709 OpenMPClauseKind AtomicKind = OMPC_unknown;
3710 SourceLocation AtomicKindLoc;
3711 for (auto *C : Clauses) {
3712 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
3713 C->getClauseKind() == OMPC_update ||
3714 C->getClauseKind() == OMPC_capture) {
3715 if (AtomicKind != OMPC_unknown) {
3716 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3717 << SourceRange(C->getLocStart(), C->getLocEnd());
3718 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3719 << getOpenMPClauseName(AtomicKind);
3721 AtomicKind = C->getClauseKind();
3722 AtomicKindLoc = C->getLocStart();
3727 auto Body = CS->getCapturedStmt();
3728 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
3729 Body = EWC->getSubExpr();
3735 bool IsXLHSInRHSPart = false;
3736 bool IsPostfixUpdate = false;
3737 // OpenMP [2.12.6, atomic Construct]
3738 // In the next expressions:
3739 // * x and v (as applicable) are both l-value expressions with scalar type.
3740 // * During the execution of an atomic region, multiple syntactic
3741 // occurrences of x must designate the same storage location.
3742 // * Neither of v and expr (as applicable) may access the storage location
3744 // * Neither of x and expr (as applicable) may access the storage location
3746 // * expr is an expression with scalar type.
3747 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3748 // * binop, binop=, ++, and -- are not overloaded operators.
3749 // * The expression x binop expr must be numerically equivalent to x binop
3750 // (expr). This requirement is satisfied if the operators in expr have
3751 // precedence greater than binop, or by using parentheses around expr or
3752 // subexpressions of expr.
3753 // * The expression expr binop x must be numerically equivalent to (expr)
3754 // binop x. This requirement is satisfied if the operators in expr have
3755 // precedence equal to or greater than binop, or by using parentheses around
3756 // expr or subexpressions of expr.
3757 // * For forms that allow multiple occurrences of x, the number of times
3758 // that x is evaluated is unspecified.
3759 if (AtomicKind == OMPC_read) {
3766 } ErrorFound = NoError;
3767 SourceLocation ErrorLoc, NoteLoc;
3768 SourceRange ErrorRange, NoteRange;
3769 // If clause is read:
3771 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3773 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3774 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3775 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3776 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3777 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3778 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3779 if (!X->isLValue() || !V->isLValue()) {
3780 auto NotLValueExpr = X->isLValue() ? V : X;
3781 ErrorFound = NotAnLValue;
3782 ErrorLoc = AtomicBinOp->getExprLoc();
3783 ErrorRange = AtomicBinOp->getSourceRange();
3784 NoteLoc = NotLValueExpr->getExprLoc();
3785 NoteRange = NotLValueExpr->getSourceRange();
3787 } else if (!X->isInstantiationDependent() ||
3788 !V->isInstantiationDependent()) {
3789 auto NotScalarExpr =
3790 (X->isInstantiationDependent() || X->getType()->isScalarType())
3793 ErrorFound = NotAScalarType;
3794 ErrorLoc = AtomicBinOp->getExprLoc();
3795 ErrorRange = AtomicBinOp->getSourceRange();
3796 NoteLoc = NotScalarExpr->getExprLoc();
3797 NoteRange = NotScalarExpr->getSourceRange();
3800 ErrorFound = NotAnAssignmentOp;
3801 ErrorLoc = AtomicBody->getExprLoc();
3802 ErrorRange = AtomicBody->getSourceRange();
3803 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3804 : AtomicBody->getExprLoc();
3805 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3806 : AtomicBody->getSourceRange();
3809 ErrorFound = NotAnExpression;
3810 NoteLoc = ErrorLoc = Body->getLocStart();
3811 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3813 if (ErrorFound != NoError) {
3814 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3816 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3819 } else if (CurContext->isDependentContext())
3821 } else if (AtomicKind == OMPC_write) {
3828 } ErrorFound = NoError;
3829 SourceLocation ErrorLoc, NoteLoc;
3830 SourceRange ErrorRange, NoteRange;
3831 // If clause is write:
3833 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3835 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3836 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3837 X = AtomicBinOp->getLHS();
3838 E = AtomicBinOp->getRHS();
3839 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3840 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
3841 if (!X->isLValue()) {
3842 ErrorFound = NotAnLValue;
3843 ErrorLoc = AtomicBinOp->getExprLoc();
3844 ErrorRange = AtomicBinOp->getSourceRange();
3845 NoteLoc = X->getExprLoc();
3846 NoteRange = X->getSourceRange();
3848 } else if (!X->isInstantiationDependent() ||
3849 !E->isInstantiationDependent()) {
3850 auto NotScalarExpr =
3851 (X->isInstantiationDependent() || X->getType()->isScalarType())
3854 ErrorFound = NotAScalarType;
3855 ErrorLoc = AtomicBinOp->getExprLoc();
3856 ErrorRange = AtomicBinOp->getSourceRange();
3857 NoteLoc = NotScalarExpr->getExprLoc();
3858 NoteRange = NotScalarExpr->getSourceRange();
3861 ErrorFound = NotAnAssignmentOp;
3862 ErrorLoc = AtomicBody->getExprLoc();
3863 ErrorRange = AtomicBody->getSourceRange();
3864 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3865 : AtomicBody->getExprLoc();
3866 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3867 : AtomicBody->getSourceRange();
3870 ErrorFound = NotAnExpression;
3871 NoteLoc = ErrorLoc = Body->getLocStart();
3872 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3874 if (ErrorFound != NoError) {
3875 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
3877 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3880 } else if (CurContext->isDependentContext())
3882 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
3883 // If clause is update:
3889 // x = x binop expr;
3890 // x = expr binop x;
3891 OpenMPAtomicUpdateChecker Checker(*this);
3892 if (Checker.checkStatement(
3893 Body, (AtomicKind == OMPC_update)
3894 ? diag::err_omp_atomic_update_not_expression_statement
3895 : diag::err_omp_atomic_not_expression_statement,
3896 diag::note_omp_atomic_update))
3898 if (!CurContext->isDependentContext()) {
3899 E = Checker.getExpr();
3901 UE = Checker.getUpdateExpr();
3902 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3904 } else if (AtomicKind == OMPC_capture) {
3907 NotACompoundStatement,
3908 NotTwoSubstatements,
3909 NotASpecificExpression,
3911 } ErrorFound = NoError;
3912 SourceLocation ErrorLoc, NoteLoc;
3913 SourceRange ErrorRange, NoteRange;
3914 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
3915 // If clause is a capture:
3920 // v = x binop= expr;
3921 // v = x = x binop expr;
3922 // v = x = expr binop x;
3924 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3925 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3926 V = AtomicBinOp->getLHS();
3927 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3928 OpenMPAtomicUpdateChecker Checker(*this);
3929 if (Checker.checkStatement(
3930 Body, diag::err_omp_atomic_capture_not_expression_statement,
3931 diag::note_omp_atomic_update))
3933 E = Checker.getExpr();
3935 UE = Checker.getUpdateExpr();
3936 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3937 IsPostfixUpdate = Checker.isPostfixUpdate();
3939 ErrorLoc = AtomicBody->getExprLoc();
3940 ErrorRange = AtomicBody->getSourceRange();
3941 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3942 : AtomicBody->getExprLoc();
3943 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3944 : AtomicBody->getSourceRange();
3945 ErrorFound = NotAnAssignmentOp;
3947 if (ErrorFound != NoError) {
3948 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
3950 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3952 } else if (CurContext->isDependentContext()) {
3953 UE = V = E = X = nullptr;
3956 // If clause is a capture:
3957 // { v = x; x = expr; }
3962 // { v = x; x binop= expr; }
3963 // { v = x; x = x binop expr; }
3964 // { v = x; x = expr binop x; }
3969 // { x binop= expr; v = x; }
3970 // { x = x binop expr; v = x; }
3971 // { x = expr binop x; v = x; }
3972 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
3973 // Check that this is { expr1; expr2; }
3974 if (CS->size() == 2) {
3975 auto *First = CS->body_front();
3976 auto *Second = CS->body_back();
3977 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
3978 First = EWC->getSubExpr()->IgnoreParenImpCasts();
3979 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
3980 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
3981 // Need to find what subexpression is 'v' and what is 'x'.
3982 OpenMPAtomicUpdateChecker Checker(*this);
3983 bool IsUpdateExprFound = !Checker.checkStatement(Second);
3984 BinaryOperator *BinOp = nullptr;
3985 if (IsUpdateExprFound) {
3986 BinOp = dyn_cast<BinaryOperator>(First);
3987 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3989 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3994 // { v = x; x binop= expr; }
3995 // { v = x; x = x binop expr; }
3996 // { v = x; x = expr binop x; }
3997 // Check that the first expression has form v = x.
3998 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3999 llvm::FoldingSetNodeID XId, PossibleXId;
4000 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4001 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4002 IsUpdateExprFound = XId == PossibleXId;
4003 if (IsUpdateExprFound) {
4004 V = BinOp->getLHS();
4006 E = Checker.getExpr();
4007 UE = Checker.getUpdateExpr();
4008 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4009 IsPostfixUpdate = true;
4012 if (!IsUpdateExprFound) {
4013 IsUpdateExprFound = !Checker.checkStatement(First);
4015 if (IsUpdateExprFound) {
4016 BinOp = dyn_cast<BinaryOperator>(Second);
4017 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4019 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4024 // { x binop= expr; v = x; }
4025 // { x = x binop expr; v = x; }
4026 // { x = expr binop x; v = x; }
4027 // Check that the second expression has form v = x.
4028 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4029 llvm::FoldingSetNodeID XId, PossibleXId;
4030 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4031 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4032 IsUpdateExprFound = XId == PossibleXId;
4033 if (IsUpdateExprFound) {
4034 V = BinOp->getLHS();
4036 E = Checker.getExpr();
4037 UE = Checker.getUpdateExpr();
4038 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4039 IsPostfixUpdate = false;
4043 if (!IsUpdateExprFound) {
4044 // { v = x; x = expr; }
4045 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
4046 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
4047 ErrorFound = NotAnAssignmentOp;
4048 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
4049 : First->getLocStart();
4050 NoteRange = ErrorRange = FirstBinOp
4051 ? FirstBinOp->getSourceRange()
4052 : SourceRange(ErrorLoc, ErrorLoc);
4054 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
4055 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
4056 ErrorFound = NotAnAssignmentOp;
4057 NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
4058 : Second->getLocStart();
4059 NoteRange = ErrorRange = SecondBinOp
4060 ? SecondBinOp->getSourceRange()
4061 : SourceRange(ErrorLoc, ErrorLoc);
4063 auto *PossibleXRHSInFirst =
4064 FirstBinOp->getRHS()->IgnoreParenImpCasts();
4065 auto *PossibleXLHSInSecond =
4066 SecondBinOp->getLHS()->IgnoreParenImpCasts();
4067 llvm::FoldingSetNodeID X1Id, X2Id;
4068 PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
4069 PossibleXLHSInSecond->Profile(X2Id, Context,
4070 /*Canonical=*/true);
4071 IsUpdateExprFound = X1Id == X2Id;
4072 if (IsUpdateExprFound) {
4073 V = FirstBinOp->getLHS();
4074 X = SecondBinOp->getLHS();
4075 E = SecondBinOp->getRHS();
4077 IsXLHSInRHSPart = false;
4078 IsPostfixUpdate = true;
4080 ErrorFound = NotASpecificExpression;
4081 ErrorLoc = FirstBinOp->getExprLoc();
4082 ErrorRange = FirstBinOp->getSourceRange();
4083 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
4084 NoteRange = SecondBinOp->getRHS()->getSourceRange();
4090 NoteLoc = ErrorLoc = Body->getLocStart();
4091 NoteRange = ErrorRange =
4092 SourceRange(Body->getLocStart(), Body->getLocStart());
4093 ErrorFound = NotTwoSubstatements;
4096 NoteLoc = ErrorLoc = Body->getLocStart();
4097 NoteRange = ErrorRange =
4098 SourceRange(Body->getLocStart(), Body->getLocStart());
4099 ErrorFound = NotACompoundStatement;
4101 if (ErrorFound != NoError) {
4102 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
4104 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4106 } else if (CurContext->isDependentContext()) {
4107 UE = V = E = X = nullptr;
4112 getCurFunction()->setHasBranchProtectedScope();
4114 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4115 X, V, E, UE, IsXLHSInRHSPart,
4119 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
4121 SourceLocation StartLoc,
4122 SourceLocation EndLoc) {
4123 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4125 // OpenMP [2.16, Nesting of Regions]
4126 // If specified, a teams construct must be contained within a target
4127 // construct. That target construct must contain no statements or directives
4128 // outside of the teams construct.
4129 if (DSAStack->hasInnerTeamsRegion()) {
4130 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
4131 bool OMPTeamsFound = true;
4132 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
4133 auto I = CS->body_begin();
4134 while (I != CS->body_end()) {
4135 auto OED = dyn_cast<OMPExecutableDirective>(*I);
4136 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
4137 OMPTeamsFound = false;
4142 assert(I != CS->body_end() && "Not found statement");
4145 if (!OMPTeamsFound) {
4146 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
4147 Diag(DSAStack->getInnerTeamsRegionLoc(),
4148 diag::note_omp_nested_teams_construct_here);
4149 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
4150 << isa<OMPExecutableDirective>(S);
4155 getCurFunction()->setHasBranchProtectedScope();
4157 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4160 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
4161 Stmt *AStmt, SourceLocation StartLoc,
4162 SourceLocation EndLoc) {
4163 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4164 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4165 // 1.2.2 OpenMP Language Terminology
4166 // Structured block - An executable statement with a single entry at the
4167 // top and a single exit at the bottom.
4168 // The point of exit cannot be a branch out of the structured block.
4169 // longjmp() and throw() must not violate the entry/exit criteria.
4170 CS->getCapturedDecl()->setNothrow();
4172 getCurFunction()->setHasBranchProtectedScope();
4174 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4177 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
4178 SourceLocation StartLoc,
4179 SourceLocation LParenLoc,
4180 SourceLocation EndLoc) {
4181 OMPClause *Res = nullptr;
4184 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
4187 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
4189 case OMPC_num_threads:
4190 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
4193 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
4196 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
4199 case OMPC_proc_bind:
4202 case OMPC_firstprivate:
4203 case OMPC_lastprivate:
4205 case OMPC_reduction:
4209 case OMPC_copyprivate:
4213 case OMPC_mergeable:
4214 case OMPC_threadprivate:
4222 llvm_unreachable("Clause is not allowed.");
4227 OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
4228 SourceLocation LParenLoc,
4229 SourceLocation EndLoc) {
4230 Expr *ValExpr = Condition;
4231 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4232 !Condition->isInstantiationDependent() &&
4233 !Condition->containsUnexpandedParameterPack()) {
4234 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4235 Condition->getExprLoc(), Condition);
4236 if (Val.isInvalid())
4239 ValExpr = Val.get();
4242 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4245 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
4246 SourceLocation StartLoc,
4247 SourceLocation LParenLoc,
4248 SourceLocation EndLoc) {
4249 Expr *ValExpr = Condition;
4250 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4251 !Condition->isInstantiationDependent() &&
4252 !Condition->containsUnexpandedParameterPack()) {
4253 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4254 Condition->getExprLoc(), Condition);
4255 if (Val.isInvalid())
4258 ValExpr = Val.get();
4261 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4263 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
4268 class IntConvertDiagnoser : public ICEConvertDiagnoser {
4270 IntConvertDiagnoser()
4271 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
4272 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
4273 QualType T) override {
4274 return S.Diag(Loc, diag::err_omp_not_integral) << T;
4276 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4277 QualType T) override {
4278 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
4280 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4282 QualType ConvTy) override {
4283 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
4285 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4286 QualType ConvTy) override {
4287 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
4288 << ConvTy->isEnumeralType() << ConvTy;
4290 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4291 QualType T) override {
4292 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
4294 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4295 QualType ConvTy) override {
4296 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
4297 << ConvTy->isEnumeralType() << ConvTy;
4299 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
4300 QualType) override {
4301 llvm_unreachable("conversion functions are permitted");
4304 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
4307 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
4308 SourceLocation StartLoc,
4309 SourceLocation LParenLoc,
4310 SourceLocation EndLoc) {
4311 Expr *ValExpr = NumThreads;
4312 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
4313 !NumThreads->containsUnexpandedParameterPack()) {
4314 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
4316 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
4317 if (Val.isInvalid())
4320 ValExpr = Val.get();
4322 // OpenMP [2.5, Restrictions]
4323 // The num_threads expression must evaluate to a positive integer value.
4324 llvm::APSInt Result;
4325 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
4326 !Result.isStrictlyPositive()) {
4327 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
4328 << "num_threads" << NumThreads->getSourceRange();
4333 return new (Context)
4334 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4337 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
4338 OpenMPClauseKind CKind) {
4341 if (E->isValueDependent() || E->isTypeDependent() ||
4342 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4344 llvm::APSInt Result;
4345 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
4346 if (ICE.isInvalid())
4348 if (!Result.isStrictlyPositive()) {
4349 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
4350 << getOpenMPClauseName(CKind) << E->getSourceRange();
4353 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
4354 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
4355 << E->getSourceRange();
4358 if (CKind == OMPC_collapse) {
4359 DSAStack->setCollapseNumber(Result.getExtValue());
4364 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
4365 SourceLocation LParenLoc,
4366 SourceLocation EndLoc) {
4367 // OpenMP [2.8.1, simd construct, Description]
4368 // The parameter of the safelen clause must be a constant
4369 // positive integer expression.
4370 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
4371 if (Safelen.isInvalid())
4373 return new (Context)
4374 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
4377 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
4378 SourceLocation StartLoc,
4379 SourceLocation LParenLoc,
4380 SourceLocation EndLoc) {
4381 // OpenMP [2.7.1, loop construct, Description]
4382 // OpenMP [2.8.1, simd construct, Description]
4383 // OpenMP [2.9.6, distribute construct, Description]
4384 // The parameter of the collapse clause must be a constant
4385 // positive integer expression.
4386 ExprResult NumForLoopsResult =
4387 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
4388 if (NumForLoopsResult.isInvalid())
4390 return new (Context)
4391 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
4394 OMPClause *Sema::ActOnOpenMPSimpleClause(
4395 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
4396 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
4397 OMPClause *Res = nullptr;
4401 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
4402 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
4404 case OMPC_proc_bind:
4405 Res = ActOnOpenMPProcBindClause(
4406 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
4411 case OMPC_num_threads:
4416 case OMPC_firstprivate:
4417 case OMPC_lastprivate:
4419 case OMPC_reduction:
4423 case OMPC_copyprivate:
4427 case OMPC_mergeable:
4428 case OMPC_threadprivate:
4436 llvm_unreachable("Clause is not allowed.");
4441 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
4442 SourceLocation KindKwLoc,
4443 SourceLocation StartLoc,
4444 SourceLocation LParenLoc,
4445 SourceLocation EndLoc) {
4446 if (Kind == OMPC_DEFAULT_unknown) {
4448 static_assert(OMPC_DEFAULT_unknown > 0,
4449 "OMPC_DEFAULT_unknown not greater than 0");
4450 std::string Sep(", ");
4451 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
4453 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
4456 case OMPC_DEFAULT_unknown - 2:
4459 case OMPC_DEFAULT_unknown - 1:
4466 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
4467 << Values << getOpenMPClauseName(OMPC_default);
4471 case OMPC_DEFAULT_none:
4472 DSAStack->setDefaultDSANone(KindKwLoc);
4474 case OMPC_DEFAULT_shared:
4475 DSAStack->setDefaultDSAShared(KindKwLoc);
4477 case OMPC_DEFAULT_unknown:
4478 llvm_unreachable("Clause kind is not allowed.");
4481 return new (Context)
4482 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
4485 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
4486 SourceLocation KindKwLoc,
4487 SourceLocation StartLoc,
4488 SourceLocation LParenLoc,
4489 SourceLocation EndLoc) {
4490 if (Kind == OMPC_PROC_BIND_unknown) {
4492 std::string Sep(", ");
4493 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
4495 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
4498 case OMPC_PROC_BIND_unknown - 2:
4501 case OMPC_PROC_BIND_unknown - 1:
4508 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
4509 << Values << getOpenMPClauseName(OMPC_proc_bind);
4512 return new (Context)
4513 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
4516 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
4517 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
4518 SourceLocation StartLoc, SourceLocation LParenLoc,
4519 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
4520 SourceLocation EndLoc) {
4521 OMPClause *Res = nullptr;
4524 Res = ActOnOpenMPScheduleClause(
4525 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
4526 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
4530 case OMPC_num_threads:
4534 case OMPC_proc_bind:
4536 case OMPC_firstprivate:
4537 case OMPC_lastprivate:
4539 case OMPC_reduction:
4543 case OMPC_copyprivate:
4547 case OMPC_mergeable:
4548 case OMPC_threadprivate:
4556 llvm_unreachable("Clause is not allowed.");
4561 OMPClause *Sema::ActOnOpenMPScheduleClause(
4562 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
4563 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
4564 SourceLocation EndLoc) {
4565 if (Kind == OMPC_SCHEDULE_unknown) {
4567 std::string Sep(", ");
4568 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
4570 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
4573 case OMPC_SCHEDULE_unknown - 2:
4576 case OMPC_SCHEDULE_unknown - 1:
4583 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
4584 << Values << getOpenMPClauseName(OMPC_schedule);
4587 Expr *ValExpr = ChunkSize;
4588 Expr *HelperValExpr = nullptr;
4590 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
4591 !ChunkSize->isInstantiationDependent() &&
4592 !ChunkSize->containsUnexpandedParameterPack()) {
4593 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
4595 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
4596 if (Val.isInvalid())
4599 ValExpr = Val.get();
4601 // OpenMP [2.7.1, Restrictions]
4602 // chunk_size must be a loop invariant integer expression with a positive
4604 llvm::APSInt Result;
4605 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
4606 if (Result.isSigned() && !Result.isStrictlyPositive()) {
4607 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
4608 << "schedule" << ChunkSize->getSourceRange();
4611 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
4612 auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
4613 ChunkSize->getType(), ".chunk.");
4614 auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
4615 ChunkSize->getExprLoc(),
4616 /*RefersToCapture=*/true);
4617 HelperValExpr = ImpVarRef;
4622 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
4623 EndLoc, Kind, ValExpr, HelperValExpr);
4626 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
4627 SourceLocation StartLoc,
4628 SourceLocation EndLoc) {
4629 OMPClause *Res = nullptr;
4632 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
4635 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
4638 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
4640 case OMPC_mergeable:
4641 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
4644 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
4647 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
4650 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
4653 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
4656 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
4660 case OMPC_num_threads:
4665 case OMPC_firstprivate:
4666 case OMPC_lastprivate:
4668 case OMPC_reduction:
4672 case OMPC_copyprivate:
4674 case OMPC_proc_bind:
4675 case OMPC_threadprivate:
4678 llvm_unreachable("Clause is not allowed.");
4683 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
4684 SourceLocation EndLoc) {
4685 DSAStack->setOrderedRegion();
4686 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
4689 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
4690 SourceLocation EndLoc) {
4691 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
4694 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
4695 SourceLocation EndLoc) {
4696 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
4699 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
4700 SourceLocation EndLoc) {
4701 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
4704 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
4705 SourceLocation EndLoc) {
4706 return new (Context) OMPReadClause(StartLoc, EndLoc);
4709 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
4710 SourceLocation EndLoc) {
4711 return new (Context) OMPWriteClause(StartLoc, EndLoc);
4714 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
4715 SourceLocation EndLoc) {
4716 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
4719 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
4720 SourceLocation EndLoc) {
4721 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
4724 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
4725 SourceLocation EndLoc) {
4726 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
4729 OMPClause *Sema::ActOnOpenMPVarListClause(
4730 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
4731 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
4732 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
4733 const DeclarationNameInfo &ReductionId) {
4734 OMPClause *Res = nullptr;
4737 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4739 case OMPC_firstprivate:
4740 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4742 case OMPC_lastprivate:
4743 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4746 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
4748 case OMPC_reduction:
4749 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
4750 EndLoc, ReductionIdScopeSpec, ReductionId);
4753 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
4757 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
4761 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
4763 case OMPC_copyprivate:
4764 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4767 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4771 case OMPC_num_threads:
4775 case OMPC_proc_bind:
4780 case OMPC_mergeable:
4781 case OMPC_threadprivate:
4788 llvm_unreachable("Clause is not allowed.");
4793 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
4794 SourceLocation StartLoc,
4795 SourceLocation LParenLoc,
4796 SourceLocation EndLoc) {
4797 SmallVector<Expr *, 8> Vars;
4798 SmallVector<Expr *, 8> PrivateCopies;
4799 for (auto &RefExpr : VarList) {
4800 assert(RefExpr && "NULL expr in OpenMP private clause.");
4801 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4802 // It will be analyzed later.
4803 Vars.push_back(RefExpr);
4804 PrivateCopies.push_back(nullptr);
4808 SourceLocation ELoc = RefExpr->getExprLoc();
4809 // OpenMP [2.1, C/C++]
4810 // A list item is a variable name.
4811 // OpenMP [2.9.3.3, Restrictions, p.1]
4812 // A variable that is part of another variable (as an array or
4813 // structure element) cannot appear in a private clause.
4814 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4815 if (!DE || !isa<VarDecl>(DE->getDecl())) {
4816 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4819 Decl *D = DE->getDecl();
4820 VarDecl *VD = cast<VarDecl>(D);
4822 QualType Type = VD->getType();
4823 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4824 // It will be analyzed later.
4826 PrivateCopies.push_back(nullptr);
4830 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4831 // A variable that appears in a private clause must not have an incomplete
4832 // type or a reference type.
4833 if (RequireCompleteType(ELoc, Type,
4834 diag::err_omp_private_incomplete_type)) {
4837 if (Type->isReferenceType()) {
4838 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4839 << getOpenMPClauseName(OMPC_private) << Type;
4841 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4842 Diag(VD->getLocation(),
4843 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4848 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4850 // Variables with the predetermined data-sharing attributes may not be
4851 // listed in data-sharing attributes clauses, except for the cases
4852 // listed below. For these exceptions only, listing a predetermined
4853 // variable in a data-sharing attribute clause is allowed and overrides
4854 // the variable's predetermined data-sharing attributes.
4855 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
4856 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
4857 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4858 << getOpenMPClauseName(OMPC_private);
4859 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4863 // Variably modified types are not supported for tasks.
4864 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
4865 DSAStack->getCurrentDirective() == OMPD_task) {
4866 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
4867 << getOpenMPClauseName(OMPC_private) << Type
4868 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4870 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4871 Diag(VD->getLocation(),
4872 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4877 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
4878 // A variable of class type (or array thereof) that appears in a private
4879 // clause requires an accessible, unambiguous default constructor for the
4881 // Generate helper private variable and initialize it with the default
4882 // value. The address of the original variable is replaced by the address of
4883 // the new private variable in CodeGen. This new variable is not added to
4884 // IdResolver, so the code in the OpenMP region uses original variable for
4885 // proper diagnostics.
4886 Type = Type.getUnqualifiedType();
4887 auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName());
4888 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
4889 if (VDPrivate->isInvalidDecl())
4891 auto VDPrivateRefExpr = buildDeclRefExpr(
4892 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
4894 DSAStack->addDSA(VD, DE, OMPC_private);
4896 PrivateCopies.push_back(VDPrivateRefExpr);
4902 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
4907 class DiagsUninitializedSeveretyRAII {
4909 DiagnosticsEngine &Diags;
4910 SourceLocation SavedLoc;
4914 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
4916 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
4918 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
4919 /*Map*/ diag::Severity::Ignored, Loc);
4922 ~DiagsUninitializedSeveretyRAII() {
4924 Diags.popMappings(SavedLoc);
4929 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
4930 SourceLocation StartLoc,
4931 SourceLocation LParenLoc,
4932 SourceLocation EndLoc) {
4933 SmallVector<Expr *, 8> Vars;
4934 SmallVector<Expr *, 8> PrivateCopies;
4935 SmallVector<Expr *, 8> Inits;
4936 bool IsImplicitClause =
4937 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
4938 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
4940 for (auto &RefExpr : VarList) {
4941 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
4942 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4943 // It will be analyzed later.
4944 Vars.push_back(RefExpr);
4945 PrivateCopies.push_back(nullptr);
4946 Inits.push_back(nullptr);
4950 SourceLocation ELoc =
4951 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
4952 // OpenMP [2.1, C/C++]
4953 // A list item is a variable name.
4954 // OpenMP [2.9.3.3, Restrictions, p.1]
4955 // A variable that is part of another variable (as an array or
4956 // structure element) cannot appear in a private clause.
4957 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4958 if (!DE || !isa<VarDecl>(DE->getDecl())) {
4959 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4962 Decl *D = DE->getDecl();
4963 VarDecl *VD = cast<VarDecl>(D);
4965 QualType Type = VD->getType();
4966 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4967 // It will be analyzed later.
4969 PrivateCopies.push_back(nullptr);
4970 Inits.push_back(nullptr);
4974 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4975 // A variable that appears in a private clause must not have an incomplete
4976 // type or a reference type.
4977 if (RequireCompleteType(ELoc, Type,
4978 diag::err_omp_firstprivate_incomplete_type)) {
4981 if (Type->isReferenceType()) {
4982 if (IsImplicitClause) {
4983 Diag(ImplicitClauseLoc,
4984 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
4986 Diag(RefExpr->getExprLoc(), diag::note_used_here);
4988 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4989 << getOpenMPClauseName(OMPC_firstprivate) << Type;
4992 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4993 Diag(VD->getLocation(),
4994 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4999 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
5000 // A variable of class type (or array thereof) that appears in a private
5001 // clause requires an accessible, unambiguous copy constructor for the
5003 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
5005 // If an implicit firstprivate variable found it was checked already.
5006 if (!IsImplicitClause) {
5007 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5008 bool IsConstant = ElemType.isConstant(Context);
5009 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
5010 // A list item that specifies a given variable may not appear in more
5011 // than one clause on the same directive, except that a variable may be
5012 // specified in both firstprivate and lastprivate clauses.
5013 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
5014 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
5015 Diag(ELoc, diag::err_omp_wrong_dsa)
5016 << getOpenMPClauseName(DVar.CKind)
5017 << getOpenMPClauseName(OMPC_firstprivate);
5018 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5022 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5024 // Variables with the predetermined data-sharing attributes may not be
5025 // listed in data-sharing attributes clauses, except for the cases
5026 // listed below. For these exceptions only, listing a predetermined
5027 // variable in a data-sharing attribute clause is allowed and overrides
5028 // the variable's predetermined data-sharing attributes.
5029 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5030 // in a Construct, C/C++, p.2]
5031 // Variables with const-qualified type having no mutable member may be
5032 // listed in a firstprivate clause, even if they are static data members.
5033 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
5034 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
5035 Diag(ELoc, diag::err_omp_wrong_dsa)
5036 << getOpenMPClauseName(DVar.CKind)
5037 << getOpenMPClauseName(OMPC_firstprivate);
5038 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5042 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5043 // OpenMP [2.9.3.4, Restrictions, p.2]
5044 // A list item that is private within a parallel region must not appear
5045 // in a firstprivate clause on a worksharing construct if any of the
5046 // worksharing regions arising from the worksharing construct ever bind
5047 // to any of the parallel regions arising from the parallel construct.
5048 if (isOpenMPWorksharingDirective(CurrDir) &&
5049 !isOpenMPParallelDirective(CurrDir)) {
5050 DVar = DSAStack->getImplicitDSA(VD, true);
5051 if (DVar.CKind != OMPC_shared &&
5052 (isOpenMPParallelDirective(DVar.DKind) ||
5053 DVar.DKind == OMPD_unknown)) {
5054 Diag(ELoc, diag::err_omp_required_access)
5055 << getOpenMPClauseName(OMPC_firstprivate)
5056 << getOpenMPClauseName(OMPC_shared);
5057 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5061 // OpenMP [2.9.3.4, Restrictions, p.3]
5062 // A list item that appears in a reduction clause of a parallel construct
5063 // must not appear in a firstprivate clause on a worksharing or task
5064 // construct if any of the worksharing or task regions arising from the
5065 // worksharing or task construct ever bind to any of the parallel regions
5066 // arising from the parallel construct.
5067 // OpenMP [2.9.3.4, Restrictions, p.4]
5068 // A list item that appears in a reduction clause in worksharing
5069 // construct must not appear in a firstprivate clause in a task construct
5070 // encountered during execution of any of the worksharing regions arising
5071 // from the worksharing construct.
5072 if (CurrDir == OMPD_task) {
5074 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
5075 [](OpenMPDirectiveKind K) -> bool {
5076 return isOpenMPParallelDirective(K) ||
5077 isOpenMPWorksharingDirective(K);
5080 if (DVar.CKind == OMPC_reduction &&
5081 (isOpenMPParallelDirective(DVar.DKind) ||
5082 isOpenMPWorksharingDirective(DVar.DKind))) {
5083 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
5084 << getOpenMPDirectiveName(DVar.DKind);
5085 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5091 // Variably modified types are not supported for tasks.
5092 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
5093 DSAStack->getCurrentDirective() == OMPD_task) {
5094 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5095 << getOpenMPClauseName(OMPC_firstprivate) << Type
5096 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5098 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5099 Diag(VD->getLocation(),
5100 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5105 Type = Type.getUnqualifiedType();
5106 auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName());
5107 // Generate helper private variable and initialize it with the value of the
5108 // original variable. The address of the original variable is replaced by
5109 // the address of the new private variable in the CodeGen. This new variable
5110 // is not added to IdResolver, so the code in the OpenMP region uses
5111 // original variable for proper diagnostics and variable capturing.
5112 Expr *VDInitRefExpr = nullptr;
5113 // For arrays generate initializer for single element and replace it by the
5114 // original array element in CodeGen.
5115 if (Type->isArrayType()) {
5117 buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
5118 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
5119 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
5120 ElemType = ElemType.getUnqualifiedType();
5121 auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
5122 ".firstprivate.temp");
5123 InitializedEntity Entity =
5124 InitializedEntity::InitializeVariable(VDInitTemp);
5125 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
5127 InitializationSequence InitSeq(*this, Entity, Kind, Init);
5128 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
5129 if (Result.isInvalid())
5130 VDPrivate->setInvalidDecl();
5132 VDPrivate->setInit(Result.getAs<Expr>());
5135 buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
5137 buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
5138 AddInitializerToDecl(VDPrivate,
5139 DefaultLvalueConversion(VDInitRefExpr).get(),
5140 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
5142 if (VDPrivate->isInvalidDecl()) {
5143 if (IsImplicitClause) {
5144 Diag(DE->getExprLoc(),
5145 diag::note_omp_task_predetermined_firstprivate_here);
5149 CurContext->addDecl(VDPrivate);
5150 auto VDPrivateRefExpr = buildDeclRefExpr(
5151 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
5152 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
5154 PrivateCopies.push_back(VDPrivateRefExpr);
5155 Inits.push_back(VDInitRefExpr);
5161 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
5162 Vars, PrivateCopies, Inits);
5165 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
5166 SourceLocation StartLoc,
5167 SourceLocation LParenLoc,
5168 SourceLocation EndLoc) {
5169 SmallVector<Expr *, 8> Vars;
5170 SmallVector<Expr *, 8> SrcExprs;
5171 SmallVector<Expr *, 8> DstExprs;
5172 SmallVector<Expr *, 8> AssignmentOps;
5173 for (auto &RefExpr : VarList) {
5174 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
5175 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5176 // It will be analyzed later.
5177 Vars.push_back(RefExpr);
5178 SrcExprs.push_back(nullptr);
5179 DstExprs.push_back(nullptr);
5180 AssignmentOps.push_back(nullptr);
5184 SourceLocation ELoc = RefExpr->getExprLoc();
5185 // OpenMP [2.1, C/C++]
5186 // A list item is a variable name.
5187 // OpenMP [2.14.3.5, Restrictions, p.1]
5188 // A variable that is part of another variable (as an array or structure
5189 // element) cannot appear in a lastprivate clause.
5190 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5191 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5192 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5195 Decl *D = DE->getDecl();
5196 VarDecl *VD = cast<VarDecl>(D);
5198 QualType Type = VD->getType();
5199 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5200 // It will be analyzed later.
5202 SrcExprs.push_back(nullptr);
5203 DstExprs.push_back(nullptr);
5204 AssignmentOps.push_back(nullptr);
5208 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
5209 // A variable that appears in a lastprivate clause must not have an
5210 // incomplete type or a reference type.
5211 if (RequireCompleteType(ELoc, Type,
5212 diag::err_omp_lastprivate_incomplete_type)) {
5215 if (Type->isReferenceType()) {
5216 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5217 << getOpenMPClauseName(OMPC_lastprivate) << Type;
5219 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5220 Diag(VD->getLocation(),
5221 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5226 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5228 // Variables with the predetermined data-sharing attributes may not be
5229 // listed in data-sharing attributes clauses, except for the cases
5231 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5232 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
5233 DVar.CKind != OMPC_firstprivate &&
5234 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5235 Diag(ELoc, diag::err_omp_wrong_dsa)
5236 << getOpenMPClauseName(DVar.CKind)
5237 << getOpenMPClauseName(OMPC_lastprivate);
5238 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5242 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5243 // OpenMP [2.14.3.5, Restrictions, p.2]
5244 // A list item that is private within a parallel region, or that appears in
5245 // the reduction clause of a parallel construct, must not appear in a
5246 // lastprivate clause on a worksharing construct if any of the corresponding
5247 // worksharing regions ever binds to any of the corresponding parallel
5249 DSAStackTy::DSAVarData TopDVar = DVar;
5250 if (isOpenMPWorksharingDirective(CurrDir) &&
5251 !isOpenMPParallelDirective(CurrDir)) {
5252 DVar = DSAStack->getImplicitDSA(VD, true);
5253 if (DVar.CKind != OMPC_shared) {
5254 Diag(ELoc, diag::err_omp_required_access)
5255 << getOpenMPClauseName(OMPC_lastprivate)
5256 << getOpenMPClauseName(OMPC_shared);
5257 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5261 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
5262 // A variable of class type (or array thereof) that appears in a
5263 // lastprivate clause requires an accessible, unambiguous default
5264 // constructor for the class type, unless the list item is also specified
5265 // in a firstprivate clause.
5266 // A variable of class type (or array thereof) that appears in a
5267 // lastprivate clause requires an accessible, unambiguous copy assignment
5268 // operator for the class type.
5269 Type = Context.getBaseElementType(Type).getNonReferenceType();
5270 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
5271 Type.getUnqualifiedType(), ".lastprivate.src");
5272 auto *PseudoSrcExpr = buildDeclRefExpr(
5273 *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
5275 buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst");
5276 auto *PseudoDstExpr =
5277 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
5278 // For arrays generate assignment operation for single element and replace
5279 // it by the original array element in CodeGen.
5280 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
5281 PseudoDstExpr, PseudoSrcExpr);
5282 if (AssignmentOp.isInvalid())
5284 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
5285 /*DiscardedValue=*/true);
5286 if (AssignmentOp.isInvalid())
5289 if (TopDVar.CKind != OMPC_firstprivate)
5290 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
5292 SrcExprs.push_back(PseudoSrcExpr);
5293 DstExprs.push_back(PseudoDstExpr);
5294 AssignmentOps.push_back(AssignmentOp.get());
5300 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
5301 Vars, SrcExprs, DstExprs, AssignmentOps);
5304 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
5305 SourceLocation StartLoc,
5306 SourceLocation LParenLoc,
5307 SourceLocation EndLoc) {
5308 SmallVector<Expr *, 8> Vars;
5309 for (auto &RefExpr : VarList) {
5310 assert(RefExpr && "NULL expr in OpenMP shared clause.");
5311 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5312 // It will be analyzed later.
5313 Vars.push_back(RefExpr);
5317 SourceLocation ELoc = RefExpr->getExprLoc();
5318 // OpenMP [2.1, C/C++]
5319 // A list item is a variable name.
5320 // OpenMP [2.14.3.2, Restrictions, p.1]
5321 // A variable that is part of another variable (as an array or structure
5322 // element) cannot appear in a shared unless it is a static data member
5324 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5325 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5326 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5329 Decl *D = DE->getDecl();
5330 VarDecl *VD = cast<VarDecl>(D);
5332 QualType Type = VD->getType();
5333 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5334 // It will be analyzed later.
5339 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5341 // Variables with the predetermined data-sharing attributes may not be
5342 // listed in data-sharing attributes clauses, except for the cases
5343 // listed below. For these exceptions only, listing a predetermined
5344 // variable in a data-sharing attribute clause is allowed and overrides
5345 // the variable's predetermined data-sharing attributes.
5346 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5347 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
5349 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5350 << getOpenMPClauseName(OMPC_shared);
5351 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5355 DSAStack->addDSA(VD, DE, OMPC_shared);
5362 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5366 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
5370 bool VisitDeclRefExpr(DeclRefExpr *E) {
5371 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
5372 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
5373 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
5375 if (DVar.CKind != OMPC_unknown)
5377 DSAStackTy::DSAVarData DVarPrivate =
5378 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
5379 if (DVarPrivate.CKind != OMPC_unknown)
5385 bool VisitStmt(Stmt *S) {
5386 for (auto Child : S->children()) {
5387 if (Child && Visit(Child))
5392 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
5396 OMPClause *Sema::ActOnOpenMPReductionClause(
5397 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
5398 SourceLocation ColonLoc, SourceLocation EndLoc,
5399 CXXScopeSpec &ReductionIdScopeSpec,
5400 const DeclarationNameInfo &ReductionId) {
5401 // TODO: Allow scope specification search when 'declare reduction' is
5403 assert(ReductionIdScopeSpec.isEmpty() &&
5404 "No support for scoped reduction identifiers yet.");
5406 auto DN = ReductionId.getName();
5407 auto OOK = DN.getCXXOverloadedOperator();
5408 BinaryOperatorKind BOK = BO_Comma;
5410 // OpenMP [2.14.3.6, reduction clause]
5412 // reduction-identifier is either an identifier or one of the following
5413 // operators: +, -, *, &, |, ^, && and ||
5415 // reduction-identifier is either an id-expression or one of the following
5416 // operators: +, -, *, &, |, ^, && and ||
5417 // FIXME: Only 'min' and 'max' identifiers are supported for now.
5444 case OO_Array_Delete:
5453 case OO_GreaterEqual:
5458 case OO_PercentEqual:
5463 case OO_GreaterGreater:
5464 case OO_LessLessEqual:
5465 case OO_GreaterGreaterEqual:
5467 case OO_ExclaimEqual:
5475 case OO_Conditional:
5476 case NUM_OVERLOADED_OPERATORS:
5477 llvm_unreachable("Unexpected reduction identifier");
5479 if (auto II = DN.getAsIdentifierInfo()) {
5480 if (II->isStr("max"))
5482 else if (II->isStr("min"))
5487 SourceRange ReductionIdRange;
5488 if (ReductionIdScopeSpec.isValid()) {
5489 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
5491 ReductionIdRange.setEnd(ReductionId.getEndLoc());
5492 if (BOK == BO_Comma) {
5493 // Not allowed reduction identifier is found.
5494 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
5495 << ReductionIdRange;
5499 SmallVector<Expr *, 8> Vars;
5500 SmallVector<Expr *, 8> LHSs;
5501 SmallVector<Expr *, 8> RHSs;
5502 SmallVector<Expr *, 8> ReductionOps;
5503 for (auto RefExpr : VarList) {
5504 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
5505 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5506 // It will be analyzed later.
5507 Vars.push_back(RefExpr);
5508 LHSs.push_back(nullptr);
5509 RHSs.push_back(nullptr);
5510 ReductionOps.push_back(nullptr);
5514 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5515 RefExpr->isInstantiationDependent() ||
5516 RefExpr->containsUnexpandedParameterPack()) {
5517 // It will be analyzed later.
5518 Vars.push_back(RefExpr);
5519 LHSs.push_back(nullptr);
5520 RHSs.push_back(nullptr);
5521 ReductionOps.push_back(nullptr);
5525 auto ELoc = RefExpr->getExprLoc();
5526 auto ERange = RefExpr->getSourceRange();
5527 // OpenMP [2.1, C/C++]
5528 // A list item is a variable or array section, subject to the restrictions
5529 // specified in Section 2.4 on page 42 and in each of the sections
5530 // describing clauses and directives for which a list appears.
5531 // OpenMP [2.14.3.3, Restrictions, p.1]
5532 // A variable that is part of another variable (as an array or
5533 // structure element) cannot appear in a private clause.
5534 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
5535 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5536 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
5539 auto D = DE->getDecl();
5540 auto VD = cast<VarDecl>(D);
5541 auto Type = VD->getType();
5542 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5543 // A variable that appears in a private clause must not have an incomplete
5544 // type or a reference type.
5545 if (RequireCompleteType(ELoc, Type,
5546 diag::err_omp_reduction_incomplete_type))
5548 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5549 // Arrays may not appear in a reduction clause.
5550 if (Type.getNonReferenceType()->isArrayType()) {
5551 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
5553 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5554 Diag(VD->getLocation(),
5555 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5559 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5560 // A list item that appears in a reduction clause must not be
5562 if (Type.getNonReferenceType().isConstant(Context)) {
5563 Diag(ELoc, diag::err_omp_const_variable)
5564 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
5566 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5567 Diag(VD->getLocation(),
5568 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5572 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
5573 // If a list-item is a reference type then it must bind to the same object
5574 // for all threads of the team.
5575 VarDecl *VDDef = VD->getDefinition();
5576 if (Type->isReferenceType() && VDDef) {
5577 DSARefChecker Check(DSAStack);
5578 if (Check.Visit(VDDef->getInit())) {
5579 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
5580 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
5584 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5585 // The type of a list item that appears in a reduction clause must be valid
5586 // for the reduction-identifier. For a max or min reduction in C, the type
5587 // of the list item must be an allowed arithmetic data type: char, int,
5588 // float, double, or _Bool, possibly modified with long, short, signed, or
5589 // unsigned. For a max or min reduction in C++, the type of the list item
5590 // must be an allowed arithmetic data type: char, wchar_t, int, float,
5591 // double, or bool, possibly modified with long, short, signed, or unsigned.
5592 if ((BOK == BO_GT || BOK == BO_LT) &&
5593 !(Type->isScalarType() ||
5594 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
5595 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
5596 << getLangOpts().CPlusPlus;
5598 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5599 Diag(VD->getLocation(),
5600 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5604 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
5605 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
5606 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
5608 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5609 Diag(VD->getLocation(),
5610 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5614 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5616 // Variables with the predetermined data-sharing attributes may not be
5617 // listed in data-sharing attributes clauses, except for the cases
5618 // listed below. For these exceptions only, listing a predetermined
5619 // variable in a data-sharing attribute clause is allowed and overrides
5620 // the variable's predetermined data-sharing attributes.
5621 // OpenMP [2.14.3.6, Restrictions, p.3]
5622 // Any number of reduction clauses can be specified on the directive,
5623 // but a list item can appear only once in the reduction clauses for that
5625 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5626 if (DVar.CKind == OMPC_reduction) {
5627 Diag(ELoc, diag::err_omp_once_referenced)
5628 << getOpenMPClauseName(OMPC_reduction);
5630 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
5632 } else if (DVar.CKind != OMPC_unknown) {
5633 Diag(ELoc, diag::err_omp_wrong_dsa)
5634 << getOpenMPClauseName(DVar.CKind)
5635 << getOpenMPClauseName(OMPC_reduction);
5636 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5640 // OpenMP [2.14.3.6, Restrictions, p.1]
5641 // A list item that appears in a reduction clause of a worksharing
5642 // construct must be shared in the parallel regions to which any of the
5643 // worksharing regions arising from the worksharing construct bind.
5644 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5645 if (isOpenMPWorksharingDirective(CurrDir) &&
5646 !isOpenMPParallelDirective(CurrDir)) {
5647 DVar = DSAStack->getImplicitDSA(VD, true);
5648 if (DVar.CKind != OMPC_shared) {
5649 Diag(ELoc, diag::err_omp_required_access)
5650 << getOpenMPClauseName(OMPC_reduction)
5651 << getOpenMPClauseName(OMPC_shared);
5652 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5656 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
5657 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs");
5658 auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName());
5659 // Add initializer for private variable.
5660 Expr *Init = nullptr;
5666 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
5667 if (Type->isScalarType() || Type->isAnyComplexType()) {
5668 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
5673 if (Type->isScalarType() || Type->isAnyComplexType()) {
5674 // '*' and '&&' reduction ops - initializer is '1'.
5675 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
5679 // '&' reduction op - initializer is '~0'.
5680 QualType OrigType = Type;
5681 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
5682 Type = ComplexTy->getElementType();
5684 if (Type->isRealFloatingType()) {
5685 llvm::APFloat InitValue =
5686 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
5688 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5690 } else if (Type->isScalarType()) {
5691 auto Size = Context.getTypeSize(Type);
5692 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
5693 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
5694 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5696 if (Init && OrigType->isAnyComplexType()) {
5697 // Init = 0xFFFF + 0xFFFFi;
5698 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
5699 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
5706 // 'min' reduction op - initializer is 'Largest representable number in
5707 // the reduction list item type'.
5708 // 'max' reduction op - initializer is 'Least representable number in
5709 // the reduction list item type'.
5710 if (Type->isIntegerType() || Type->isPointerType()) {
5711 bool IsSigned = Type->hasSignedIntegerRepresentation();
5712 auto Size = Context.getTypeSize(Type);
5714 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
5715 llvm::APInt InitValue =
5717 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
5718 : llvm::APInt::getMinValue(Size)
5719 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
5720 : llvm::APInt::getMaxValue(Size);
5721 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5722 if (Type->isPointerType()) {
5723 // Cast to pointer type.
5724 auto CastExpr = BuildCStyleCastExpr(
5725 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
5726 SourceLocation(), Init);
5727 if (CastExpr.isInvalid())
5729 Init = CastExpr.get();
5731 } else if (Type->isRealFloatingType()) {
5732 llvm::APFloat InitValue = llvm::APFloat::getLargest(
5733 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
5734 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5762 llvm_unreachable("Unexpected reduction operation");
5765 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
5766 /*TypeMayContainAuto=*/false);
5768 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
5770 if (!RHSVD->hasInit()) {
5771 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
5772 << ReductionIdRange;
5774 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5775 Diag(VD->getLocation(),
5776 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5780 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
5781 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
5782 ExprResult ReductionOp =
5783 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
5785 if (ReductionOp.isUsable()) {
5786 if (BOK != BO_LT && BOK != BO_GT) {
5788 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5789 BO_Assign, LHSDRE, ReductionOp.get());
5791 auto *ConditionalOp = new (Context) ConditionalOperator(
5792 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
5793 RHSDRE, Type, VK_LValue, OK_Ordinary);
5795 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5796 BO_Assign, LHSDRE, ConditionalOp);
5798 if (ReductionOp.isUsable()) {
5799 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
5802 if (ReductionOp.isInvalid())
5805 DSAStack->addDSA(VD, DE, OMPC_reduction);
5807 LHSs.push_back(LHSDRE);
5808 RHSs.push_back(RHSDRE);
5809 ReductionOps.push_back(ReductionOp.get());
5815 return OMPReductionClause::Create(
5816 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
5817 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
5818 RHSs, ReductionOps);
5821 OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
5822 SourceLocation StartLoc,
5823 SourceLocation LParenLoc,
5824 SourceLocation ColonLoc,
5825 SourceLocation EndLoc) {
5826 SmallVector<Expr *, 8> Vars;
5827 SmallVector<Expr *, 8> Inits;
5828 for (auto &RefExpr : VarList) {
5829 assert(RefExpr && "NULL expr in OpenMP linear clause.");
5830 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5831 // It will be analyzed later.
5832 Vars.push_back(RefExpr);
5833 Inits.push_back(nullptr);
5837 // OpenMP [2.14.3.7, linear clause]
5838 // A list item that appears in a linear clause is subject to the private
5839 // clause semantics described in Section 2.14.3.3 on page 159 except as
5840 // noted. In addition, the value of the new list item on each iteration
5841 // of the associated loop(s) corresponds to the value of the original
5842 // list item before entering the construct plus the logical number of
5843 // the iteration times linear-step.
5845 SourceLocation ELoc = RefExpr->getExprLoc();
5846 // OpenMP [2.1, C/C++]
5847 // A list item is a variable name.
5848 // OpenMP [2.14.3.3, Restrictions, p.1]
5849 // A variable that is part of another variable (as an array or
5850 // structure element) cannot appear in a private clause.
5851 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5852 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5853 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5857 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5859 // OpenMP [2.14.3.7, linear clause]
5860 // A list-item cannot appear in more than one linear clause.
5861 // A list-item that appears in a linear clause cannot appear in any
5862 // other data-sharing attribute clause.
5863 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5865 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5866 << getOpenMPClauseName(OMPC_linear);
5867 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5871 QualType QType = VD->getType();
5872 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
5873 // It will be analyzed later.
5875 Inits.push_back(nullptr);
5879 // A variable must not have an incomplete type or a reference type.
5880 if (RequireCompleteType(ELoc, QType,
5881 diag::err_omp_linear_incomplete_type)) {
5884 if (QType->isReferenceType()) {
5885 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5886 << getOpenMPClauseName(OMPC_linear) << QType;
5888 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5889 Diag(VD->getLocation(),
5890 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5895 // A list item must not be const-qualified.
5896 if (QType.isConstant(Context)) {
5897 Diag(ELoc, diag::err_omp_const_variable)
5898 << getOpenMPClauseName(OMPC_linear);
5900 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5901 Diag(VD->getLocation(),
5902 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5907 // A list item must be of integral or pointer type.
5908 QType = QType.getUnqualifiedType().getCanonicalType();
5909 const Type *Ty = QType.getTypePtrOrNull();
5910 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
5911 !Ty->isPointerType())) {
5912 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
5914 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5915 Diag(VD->getLocation(),
5916 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5921 // Build var to save initial value.
5922 VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
5923 AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
5924 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
5925 auto InitRef = buildDeclRefExpr(
5926 *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
5927 DSAStack->addDSA(VD, DE, OMPC_linear);
5929 Inits.push_back(InitRef);
5935 Expr *StepExpr = Step;
5936 Expr *CalcStepExpr = nullptr;
5937 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5938 !Step->isInstantiationDependent() &&
5939 !Step->containsUnexpandedParameterPack()) {
5940 SourceLocation StepLoc = Step->getLocStart();
5941 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
5942 if (Val.isInvalid())
5944 StepExpr = Val.get();
5946 // Build var to save the step value.
5948 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
5949 ExprResult SaveRef =
5950 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
5951 ExprResult CalcStep =
5952 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
5954 // Warn about zero linear step (it would be probably better specified as
5955 // making corresponding variables 'const').
5956 llvm::APSInt Result;
5957 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
5958 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
5959 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
5960 << (Vars.size() > 1);
5961 if (!IsConstant && CalcStep.isUsable()) {
5962 // Calculate the step beforehand instead of doing this on each iteration.
5963 // (This is not used if the number of iterations may be kfold-ed).
5964 CalcStepExpr = CalcStep.get();
5968 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
5969 Vars, Inits, StepExpr, CalcStepExpr);
5972 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
5973 Expr *NumIterations, Sema &SemaRef,
5975 // Walk the vars and build update/final expressions for the CodeGen.
5976 SmallVector<Expr *, 8> Updates;
5977 SmallVector<Expr *, 8> Finals;
5978 Expr *Step = Clause.getStep();
5979 Expr *CalcStep = Clause.getCalcStep();
5980 // OpenMP [2.14.3.7, linear clause]
5981 // If linear-step is not specified it is assumed to be 1.
5982 if (Step == nullptr)
5983 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5985 Step = cast<BinaryOperator>(CalcStep)->getLHS();
5986 bool HasErrors = false;
5987 auto CurInit = Clause.inits().begin();
5988 for (auto &RefExpr : Clause.varlists()) {
5989 Expr *InitExpr = *CurInit;
5991 // Build privatized reference to the current linear var.
5992 auto DE = cast<DeclRefExpr>(RefExpr);
5994 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
5995 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
5996 /*RefersToCapture=*/true);
5998 // Build update: Var = InitExpr + IV * Step
6000 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
6001 InitExpr, IV, Step, /* Subtract */ false);
6002 Update = SemaRef.ActOnFinishFullExpr(Update.get());
6004 // Build final: Var = InitExpr + NumIterations * Step
6006 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
6007 InitExpr, NumIterations, Step, /* Subtract */ false);
6008 Final = SemaRef.ActOnFinishFullExpr(Final.get());
6009 if (!Update.isUsable() || !Final.isUsable()) {
6010 Updates.push_back(nullptr);
6011 Finals.push_back(nullptr);
6014 Updates.push_back(Update.get());
6015 Finals.push_back(Final.get());
6019 Clause.setUpdates(Updates);
6020 Clause.setFinals(Finals);
6024 OMPClause *Sema::ActOnOpenMPAlignedClause(
6025 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
6026 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
6028 SmallVector<Expr *, 8> Vars;
6029 for (auto &RefExpr : VarList) {
6030 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
6031 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6032 // It will be analyzed later.
6033 Vars.push_back(RefExpr);
6037 SourceLocation ELoc = RefExpr->getExprLoc();
6038 // OpenMP [2.1, C/C++]
6039 // A list item is a variable name.
6040 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6041 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6042 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6046 VarDecl *VD = cast<VarDecl>(DE->getDecl());
6048 // OpenMP [2.8.1, simd construct, Restrictions]
6049 // The type of list items appearing in the aligned clause must be
6050 // array, pointer, reference to array, or reference to pointer.
6051 QualType QType = VD->getType();
6052 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
6053 const Type *Ty = QType.getTypePtrOrNull();
6054 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
6055 !Ty->isPointerType())) {
6056 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
6057 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
6059 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6060 Diag(VD->getLocation(),
6061 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6066 // OpenMP [2.8.1, simd construct, Restrictions]
6067 // A list-item cannot appear in more than one aligned clause.
6068 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
6069 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
6070 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
6071 << getOpenMPClauseName(OMPC_aligned);
6078 // OpenMP [2.8.1, simd construct, Description]
6079 // The parameter of the aligned clause, alignment, must be a constant
6080 // positive integer expression.
6081 // If no optional parameter is specified, implementation-defined default
6082 // alignments for SIMD instructions on the target platforms are assumed.
6083 if (Alignment != nullptr) {
6084 ExprResult AlignResult =
6085 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
6086 if (AlignResult.isInvalid())
6088 Alignment = AlignResult.get();
6093 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
6094 EndLoc, Vars, Alignment);
6097 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
6098 SourceLocation StartLoc,
6099 SourceLocation LParenLoc,
6100 SourceLocation EndLoc) {
6101 SmallVector<Expr *, 8> Vars;
6102 SmallVector<Expr *, 8> SrcExprs;
6103 SmallVector<Expr *, 8> DstExprs;
6104 SmallVector<Expr *, 8> AssignmentOps;
6105 for (auto &RefExpr : VarList) {
6106 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
6107 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6108 // It will be analyzed later.
6109 Vars.push_back(RefExpr);
6110 SrcExprs.push_back(nullptr);
6111 DstExprs.push_back(nullptr);
6112 AssignmentOps.push_back(nullptr);
6116 SourceLocation ELoc = RefExpr->getExprLoc();
6117 // OpenMP [2.1, C/C++]
6118 // A list item is a variable name.
6119 // OpenMP [2.14.4.1, Restrictions, p.1]
6120 // A list item that appears in a copyin clause must be threadprivate.
6121 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6122 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6123 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6127 Decl *D = DE->getDecl();
6128 VarDecl *VD = cast<VarDecl>(D);
6130 QualType Type = VD->getType();
6131 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6132 // It will be analyzed later.
6134 SrcExprs.push_back(nullptr);
6135 DstExprs.push_back(nullptr);
6136 AssignmentOps.push_back(nullptr);
6140 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
6141 // A list item that appears in a copyin clause must be threadprivate.
6142 if (!DSAStack->isThreadPrivate(VD)) {
6143 Diag(ELoc, diag::err_omp_required_access)
6144 << getOpenMPClauseName(OMPC_copyin)
6145 << getOpenMPDirectiveName(OMPD_threadprivate);
6149 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6150 // A variable of class type (or array thereof) that appears in a
6151 // copyin clause requires an accessible, unambiguous copy assignment
6152 // operator for the class type.
6153 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
6154 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
6155 ElemType.getUnqualifiedType(), ".copyin.src");
6156 auto *PseudoSrcExpr = buildDeclRefExpr(
6157 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
6159 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst");
6160 auto *PseudoDstExpr =
6161 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
6162 // For arrays generate assignment operation for single element and replace
6163 // it by the original array element in CodeGen.
6164 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6165 PseudoDstExpr, PseudoSrcExpr);
6166 if (AssignmentOp.isInvalid())
6168 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6169 /*DiscardedValue=*/true);
6170 if (AssignmentOp.isInvalid())
6173 DSAStack->addDSA(VD, DE, OMPC_copyin);
6175 SrcExprs.push_back(PseudoSrcExpr);
6176 DstExprs.push_back(PseudoDstExpr);
6177 AssignmentOps.push_back(AssignmentOp.get());
6183 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
6184 SrcExprs, DstExprs, AssignmentOps);
6187 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
6188 SourceLocation StartLoc,
6189 SourceLocation LParenLoc,
6190 SourceLocation EndLoc) {
6191 SmallVector<Expr *, 8> Vars;
6192 SmallVector<Expr *, 8> SrcExprs;
6193 SmallVector<Expr *, 8> DstExprs;
6194 SmallVector<Expr *, 8> AssignmentOps;
6195 for (auto &RefExpr : VarList) {
6196 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
6197 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6198 // It will be analyzed later.
6199 Vars.push_back(RefExpr);
6200 SrcExprs.push_back(nullptr);
6201 DstExprs.push_back(nullptr);
6202 AssignmentOps.push_back(nullptr);
6206 SourceLocation ELoc = RefExpr->getExprLoc();
6207 // OpenMP [2.1, C/C++]
6208 // A list item is a variable name.
6209 // OpenMP [2.14.4.1, Restrictions, p.1]
6210 // A list item that appears in a copyin clause must be threadprivate.
6211 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6212 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6213 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6217 Decl *D = DE->getDecl();
6218 VarDecl *VD = cast<VarDecl>(D);
6220 QualType Type = VD->getType();
6221 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6222 // It will be analyzed later.
6224 SrcExprs.push_back(nullptr);
6225 DstExprs.push_back(nullptr);
6226 AssignmentOps.push_back(nullptr);
6230 // OpenMP [2.14.4.2, Restrictions, p.2]
6231 // A list item that appears in a copyprivate clause may not appear in a
6232 // private or firstprivate clause on the single construct.
6233 if (!DSAStack->isThreadPrivate(VD)) {
6234 auto DVar = DSAStack->getTopDSA(VD, false);
6235 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
6237 Diag(ELoc, diag::err_omp_wrong_dsa)
6238 << getOpenMPClauseName(DVar.CKind)
6239 << getOpenMPClauseName(OMPC_copyprivate);
6240 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6244 // OpenMP [2.11.4.2, Restrictions, p.1]
6245 // All list items that appear in a copyprivate clause must be either
6246 // threadprivate or private in the enclosing context.
6247 if (DVar.CKind == OMPC_unknown) {
6248 DVar = DSAStack->getImplicitDSA(VD, false);
6249 if (DVar.CKind == OMPC_shared) {
6250 Diag(ELoc, diag::err_omp_required_access)
6251 << getOpenMPClauseName(OMPC_copyprivate)
6252 << "threadprivate or private in the enclosing context";
6253 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6259 // Variably modified types are not supported.
6260 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
6261 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
6262 << getOpenMPClauseName(OMPC_copyprivate) << Type
6263 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
6265 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6266 Diag(VD->getLocation(),
6267 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6272 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6273 // A variable of class type (or array thereof) that appears in a
6274 // copyin clause requires an accessible, unambiguous copy assignment
6275 // operator for the class type.
6276 Type = Context.getBaseElementType(Type).getUnqualifiedType();
6278 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src");
6279 auto *PseudoSrcExpr =
6280 buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
6282 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst");
6283 auto *PseudoDstExpr =
6284 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
6285 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6286 PseudoDstExpr, PseudoSrcExpr);
6287 if (AssignmentOp.isInvalid())
6289 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6290 /*DiscardedValue=*/true);
6291 if (AssignmentOp.isInvalid())
6294 // No need to mark vars as copyprivate, they are already threadprivate or
6295 // implicitly private.
6297 SrcExprs.push_back(PseudoSrcExpr);
6298 DstExprs.push_back(PseudoDstExpr);
6299 AssignmentOps.push_back(AssignmentOp.get());
6305 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6306 Vars, SrcExprs, DstExprs, AssignmentOps);
6309 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
6310 SourceLocation StartLoc,
6311 SourceLocation LParenLoc,
6312 SourceLocation EndLoc) {
6313 if (VarList.empty())
6316 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);