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/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclOpenMP.h"
19 #include "clang/AST/StmtCXX.h"
20 #include "clang/AST/StmtOpenMP.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/Basic/OpenMPKinds.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Sema/Initialization.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "clang/Sema/SemaInternal.h"
29 using namespace clang;
31 //===----------------------------------------------------------------------===//
32 // Stack of data-sharing attributes for variables
33 //===----------------------------------------------------------------------===//
36 /// \brief Default data sharing attributes, which can be applied to directive.
37 enum DefaultDataSharingAttributes {
38 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
39 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
40 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
43 template <class T> struct MatchesAny {
44 explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
45 bool operator()(T Kind) {
46 for (auto KindEl : Arr)
55 struct MatchesAlways {
57 template <class T> bool operator()(T) { return true; }
60 typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
61 typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
63 /// \brief Stack for tracking declarations used in OpenMP directives and
64 /// clauses and their data-sharing attributes.
68 OpenMPDirectiveKind DKind;
69 OpenMPClauseKind CKind;
71 SourceLocation ImplicitDSALoc;
73 : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
79 OpenMPClauseKind Attributes;
82 typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
83 typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
86 DeclSAMapTy SharingMap;
87 AlignedMapTy AlignedMap;
88 DefaultDataSharingAttributes DefaultAttr;
89 SourceLocation DefaultAttrLoc;
90 OpenMPDirectiveKind Directive;
91 DeclarationNameInfo DirectiveName;
93 SourceLocation ConstructLoc;
94 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
95 Scope *CurScope, SourceLocation Loc)
96 : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified),
97 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
100 : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified),
101 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
105 typedef SmallVector<SharingMapTy, 64> StackTy;
107 /// \brief Stack of used declaration and their data-sharing attributes.
111 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
113 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
115 /// \brief Checks if the variable is a local for OpenMP region.
116 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
119 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
121 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
122 Scope *CurScope, SourceLocation Loc) {
123 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
124 Stack.back().DefaultAttrLoc = Loc;
128 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
132 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
133 /// add it and return NULL; otherwise return previous occurrence's expression
135 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
137 /// \brief Adds explicit data sharing attribute to the specified declaration.
138 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
140 /// \brief Returns data sharing attributes from top of the stack for the
141 /// specified declaration.
142 DSAVarData getTopDSA(VarDecl *D, bool FromParent);
143 /// \brief Returns data-sharing attributes for the specified declaration.
144 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
145 /// \brief Checks if the specified variables has data-sharing attributes which
146 /// match specified \a CPred predicate in any directive which matches \a DPred
148 template <class ClausesPredicate, class DirectivesPredicate>
149 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
150 DirectivesPredicate DPred, bool FromParent);
151 /// \brief Checks if the specified variables has data-sharing attributes which
152 /// match specified \a CPred predicate in any innermost directive which
153 /// matches \a DPred predicate.
154 template <class ClausesPredicate, class DirectivesPredicate>
155 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
156 DirectivesPredicate DPred,
158 /// \brief Finds a directive which matches specified \a DPred predicate.
159 template <class NamedDirectivesPredicate>
160 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
162 /// \brief Returns currently analyzed directive.
163 OpenMPDirectiveKind getCurrentDirective() const {
164 return Stack.back().Directive;
166 /// \brief Returns parent directive.
167 OpenMPDirectiveKind getParentDirective() const {
168 if (Stack.size() > 2)
169 return Stack[Stack.size() - 2].Directive;
173 /// \brief Set default data sharing attribute to none.
174 void setDefaultDSANone(SourceLocation Loc) {
175 Stack.back().DefaultAttr = DSA_none;
176 Stack.back().DefaultAttrLoc = Loc;
178 /// \brief Set default data sharing attribute to shared.
179 void setDefaultDSAShared(SourceLocation Loc) {
180 Stack.back().DefaultAttr = DSA_shared;
181 Stack.back().DefaultAttrLoc = Loc;
184 DefaultDataSharingAttributes getDefaultDSA() const {
185 return Stack.back().DefaultAttr;
187 SourceLocation getDefaultDSALocation() const {
188 return Stack.back().DefaultAttrLoc;
191 /// \brief Checks if the specified variable is a threadprivate.
192 bool isThreadPrivate(VarDecl *D) {
193 DSAVarData DVar = getTopDSA(D, false);
194 return isOpenMPThreadPrivate(DVar.CKind);
197 Scope *getCurScope() const { return Stack.back().CurScope; }
198 Scope *getCurScope() { return Stack.back().CurScope; }
199 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
201 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
202 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
203 DKind == OMPD_unknown;
207 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
210 if (Iter == std::prev(Stack.rend())) {
211 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
212 // in a region but not in construct]
213 // File-scope or namespace-scope variables referenced in called routines
214 // in the region are shared unless they appear in a threadprivate
216 if (!D->isFunctionOrMethodVarDecl())
217 DVar.CKind = OMPC_shared;
219 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
220 // in a region but not in construct]
221 // Variables with static storage duration that are declared in called
222 // routines in the region are shared.
223 if (D->hasGlobalStorage())
224 DVar.CKind = OMPC_shared;
229 DVar.DKind = Iter->Directive;
230 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
231 // in a Construct, C/C++, predetermined, p.1]
232 // Variables with automatic storage duration that are declared in a scope
233 // inside the construct are private.
234 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
235 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
236 DVar.CKind = OMPC_private;
240 // Explicitly specified attributes and local variables with predetermined
242 if (Iter->SharingMap.count(D)) {
243 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
244 DVar.CKind = Iter->SharingMap[D].Attributes;
245 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
249 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
250 // in a Construct, C/C++, implicitly determined, p.1]
251 // In a parallel or task construct, the data-sharing attributes of these
252 // variables are determined by the default clause, if present.
253 switch (Iter->DefaultAttr) {
255 DVar.CKind = OMPC_shared;
256 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
260 case DSA_unspecified:
261 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
262 // in a Construct, implicitly determined, p.2]
263 // In a parallel construct, if no default clause is present, these
264 // variables are shared.
265 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
266 if (isOpenMPParallelDirective(DVar.DKind)) {
267 DVar.CKind = OMPC_shared;
271 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
272 // in a Construct, implicitly determined, p.4]
273 // In a task construct, if no default clause is present, a variable that in
274 // the enclosing context is determined to be shared by all implicit tasks
275 // bound to the current team is shared.
276 if (DVar.DKind == OMPD_task) {
278 for (StackTy::reverse_iterator I = std::next(Iter),
279 EE = std::prev(Stack.rend());
281 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
283 // in a Construct, implicitly determined, p.6]
284 // In a task construct, if no default clause is present, a variable
285 // whose data-sharing attribute is not determined by the rules above is
287 DVarTemp = getDSA(I, D);
288 if (DVarTemp.CKind != OMPC_shared) {
289 DVar.RefExpr = nullptr;
290 DVar.DKind = OMPD_task;
291 DVar.CKind = OMPC_firstprivate;
294 if (isParallelOrTaskRegion(I->Directive))
297 DVar.DKind = OMPD_task;
299 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
303 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
304 // in a Construct, implicitly determined, p.3]
305 // For constructs other than task, if no default clause is present, these
306 // variables inherit their data-sharing attributes from the enclosing
308 return getDSA(std::next(Iter), D);
311 DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
312 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
313 auto It = Stack.back().AlignedMap.find(D);
314 if (It == Stack.back().AlignedMap.end()) {
315 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
316 Stack.back().AlignedMap[D] = NewDE;
319 assert(It->second && "Unexpected nullptr expr in the aligned map");
325 void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
326 if (A == OMPC_threadprivate) {
327 Stack[0].SharingMap[D].Attributes = A;
328 Stack[0].SharingMap[D].RefExpr = E;
330 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
331 Stack.back().SharingMap[D].Attributes = A;
332 Stack.back().SharingMap[D].RefExpr = E;
336 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
337 if (Stack.size() > 2) {
338 reverse_iterator I = Iter, E = std::prev(Stack.rend());
339 Scope *TopScope = nullptr;
340 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
345 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
346 Scope *CurScope = getCurScope();
347 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
348 CurScope = CurScope->getParent();
350 return CurScope != TopScope;
355 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
358 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
359 // in a Construct, C/C++, predetermined, p.1]
360 // Variables appearing in threadprivate directives are threadprivate.
361 if (D->getTLSKind() != VarDecl::TLS_None) {
362 DVar.CKind = OMPC_threadprivate;
365 if (Stack[0].SharingMap.count(D)) {
366 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
367 DVar.CKind = OMPC_threadprivate;
371 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
372 // in a Construct, C/C++, predetermined, p.1]
373 // Variables with automatic storage duration that are declared in a scope
374 // inside the construct are private.
375 OpenMPDirectiveKind Kind =
376 FromParent ? getParentDirective() : getCurrentDirective();
377 auto StartI = std::next(Stack.rbegin());
378 auto EndI = std::prev(Stack.rend());
379 if (FromParent && StartI != EndI) {
380 StartI = std::next(StartI);
382 if (!isParallelOrTaskRegion(Kind)) {
383 if (isOpenMPLocal(D, StartI) && D->isLocalVarDecl() &&
384 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
385 DVar.CKind = OMPC_private;
390 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
391 // in a Construct, C/C++, predetermined, p.4]
392 // Static data members are shared.
393 if (D->isStaticDataMember()) {
394 // Variables with const-qualified type having no mutable member may be
395 // listed in a firstprivate clause, even if they are static data members.
396 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
397 MatchesAlways(), FromParent);
398 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
401 DVar.CKind = OMPC_shared;
405 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
406 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
407 while (Type->isArrayType()) {
408 QualType ElemType = cast<ArrayType>(Type.getTypePtr())->getElementType();
409 Type = ElemType.getNonReferenceType().getCanonicalType();
411 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
412 // in a Construct, C/C++, predetermined, p.6]
413 // Variables with const qualified type having no mutable member are
416 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
418 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
419 // Variables with const-qualified type having no mutable member may be
420 // listed in a firstprivate clause, even if they are static data members.
421 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
422 MatchesAlways(), FromParent);
423 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
426 DVar.CKind = OMPC_shared;
430 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
431 // in a Construct, C/C++, predetermined, p.7]
432 // Variables with static storage duration that are declared in a scope
433 // inside the construct are shared.
434 if (D->isStaticLocal()) {
435 DVar.CKind = OMPC_shared;
439 // Explicitly specified attributes and local variables with predetermined
441 auto I = std::prev(StartI);
442 if (I->SharingMap.count(D)) {
443 DVar.RefExpr = I->SharingMap[D].RefExpr;
444 DVar.CKind = I->SharingMap[D].Attributes;
445 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
451 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
452 auto StartI = Stack.rbegin();
453 auto EndI = std::prev(Stack.rend());
454 if (FromParent && StartI != EndI) {
455 StartI = std::next(StartI);
457 return getDSA(StartI, D);
460 template <class ClausesPredicate, class DirectivesPredicate>
461 DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
462 DirectivesPredicate DPred,
464 auto StartI = std::next(Stack.rbegin());
465 auto EndI = std::prev(Stack.rend());
466 if (FromParent && StartI != EndI) {
467 StartI = std::next(StartI);
469 for (auto I = StartI, EE = EndI; I != EE; ++I) {
470 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
472 DSAVarData DVar = getDSA(I, D);
473 if (CPred(DVar.CKind))
479 template <class ClausesPredicate, class DirectivesPredicate>
480 DSAStackTy::DSAVarData
481 DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
482 DirectivesPredicate DPred, bool FromParent) {
483 auto StartI = std::next(Stack.rbegin());
484 auto EndI = std::prev(Stack.rend());
485 if (FromParent && StartI != EndI) {
486 StartI = std::next(StartI);
488 for (auto I = StartI, EE = EndI; I != EE; ++I) {
489 if (!DPred(I->Directive))
491 DSAVarData DVar = getDSA(I, D);
492 if (CPred(DVar.CKind))
499 template <class NamedDirectivesPredicate>
500 bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
501 auto StartI = std::next(Stack.rbegin());
502 auto EndI = std::prev(Stack.rend());
503 if (FromParent && StartI != EndI) {
504 StartI = std::next(StartI);
506 for (auto I = StartI, EE = EndI; I != EE; ++I) {
507 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
513 void Sema::InitDataSharingAttributesStack() {
514 VarDataSharingAttributesStack = new DSAStackTy(*this);
517 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
519 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
521 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
522 const DeclarationNameInfo &DirName,
523 Scope *CurScope, SourceLocation Loc) {
524 DSAStack->push(DKind, DirName, CurScope, Loc);
525 PushExpressionEvaluationContext(PotentiallyEvaluated);
528 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
529 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
530 // A variable of class type (or array thereof) that appears in a lastprivate
531 // clause requires an accessible, unambiguous default constructor for the
532 // class type, unless the list item is also specified in a firstprivate
534 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
535 for (auto C : D->clauses()) {
536 if (auto Clause = dyn_cast<OMPLastprivateClause>(C)) {
537 for (auto VarRef : Clause->varlists()) {
538 if (VarRef->isValueDependent() || VarRef->isTypeDependent())
540 auto VD = cast<VarDecl>(cast<DeclRefExpr>(VarRef)->getDecl());
541 auto DVar = DSAStack->getTopDSA(VD, false);
542 if (DVar.CKind == OMPC_lastprivate) {
543 SourceLocation ELoc = VarRef->getExprLoc();
544 auto Type = VarRef->getType();
545 if (Type->isArrayType())
546 Type = QualType(Type->getArrayElementTypeNoTypeQual(), 0);
548 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
549 // FIXME This code must be replaced by actual constructing of the
550 // lastprivate variable.
552 CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
553 PartialDiagnostic PD =
554 PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
556 CheckConstructorAccess(
557 ELoc, CD, InitializedEntity::InitializeTemporary(Type),
558 CD->getAccess(), PD) == AR_inaccessible ||
560 Diag(ELoc, diag::err_omp_required_method)
561 << getOpenMPClauseName(OMPC_lastprivate) << 0;
562 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
563 VarDecl::DeclarationOnly;
564 Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl
565 : diag::note_defined_here)
567 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
570 MarkFunctionReferenced(ELoc, CD);
571 DiagnoseUseOfDecl(CD, ELoc);
580 DiscardCleanupsInEvaluationContext();
581 PopExpressionEvaluationContext();
586 class VarDeclFilterCCC : public CorrectionCandidateCallback {
591 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
592 bool ValidateCandidate(const TypoCorrection &Candidate) override {
593 NamedDecl *ND = Candidate.getCorrectionDecl();
594 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
595 return VD->hasGlobalStorage() &&
596 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
597 SemaRef.getCurScope());
604 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
605 CXXScopeSpec &ScopeSpec,
606 const DeclarationNameInfo &Id) {
607 LookupResult Lookup(*this, Id, LookupOrdinaryName);
608 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
610 if (Lookup.isAmbiguous())
614 if (!Lookup.isSingleResult()) {
615 VarDeclFilterCCC Validator(*this);
616 if (TypoCorrection Corrected =
617 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, Validator,
618 CTK_ErrorRecovery)) {
619 diagnoseTypo(Corrected,
621 ? diag::err_undeclared_var_use_suggest
622 : diag::err_omp_expected_var_arg_suggest)
624 VD = Corrected.getCorrectionDeclAs<VarDecl>();
626 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
627 : diag::err_omp_expected_var_arg)
632 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
633 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
634 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
638 Lookup.suppressDiagnostics();
640 // OpenMP [2.9.2, Syntax, C/C++]
641 // Variables must be file-scope, namespace-scope, or static block-scope.
642 if (!VD->hasGlobalStorage()) {
643 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
644 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
646 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
647 Diag(VD->getLocation(),
648 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
653 VarDecl *CanonicalVD = VD->getCanonicalDecl();
654 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
655 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
656 // A threadprivate directive for file-scope variables must appear outside
657 // any definition or declaration.
658 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
659 !getCurLexicalContext()->isTranslationUnit()) {
660 Diag(Id.getLoc(), diag::err_omp_var_scope)
661 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
663 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
664 Diag(VD->getLocation(),
665 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
669 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
670 // A threadprivate directive for static class member variables must appear
671 // in the class definition, in the same scope in which the member
672 // variables are declared.
673 if (CanonicalVD->isStaticDataMember() &&
674 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
675 Diag(Id.getLoc(), diag::err_omp_var_scope)
676 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
678 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
679 Diag(VD->getLocation(),
680 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
684 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
685 // A threadprivate directive for namespace-scope variables must appear
686 // outside any definition or declaration other than the namespace
687 // definition itself.
688 if (CanonicalVD->getDeclContext()->isNamespace() &&
689 (!getCurLexicalContext()->isFileContext() ||
690 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
691 Diag(Id.getLoc(), diag::err_omp_var_scope)
692 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
694 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
695 Diag(VD->getLocation(),
696 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
700 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
701 // A threadprivate directive for static block-scope variables must appear
702 // in the scope of the variable and not in a nested scope.
703 if (CanonicalVD->isStaticLocal() && CurScope &&
704 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
705 Diag(Id.getLoc(), diag::err_omp_var_scope)
706 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
708 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
709 Diag(VD->getLocation(),
710 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
715 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
716 // A threadprivate directive must lexically precede all references to any
717 // of the variables in its list.
719 Diag(Id.getLoc(), diag::err_omp_var_used)
720 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
724 QualType ExprType = VD->getType().getNonReferenceType();
725 ExprResult DE = BuildDeclRefExpr(VD, ExprType, VK_LValue, Id.getLoc());
730 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
731 ArrayRef<Expr *> VarList) {
732 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
733 CurContext->addDecl(D);
734 return DeclGroupPtrTy::make(DeclGroupRef(D));
736 return DeclGroupPtrTy();
740 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
744 bool VisitDeclRefExpr(const DeclRefExpr *E) {
745 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
746 if (VD->hasLocalStorage()) {
747 SemaRef.Diag(E->getLocStart(),
748 diag::err_omp_local_var_in_threadprivate_init)
749 << E->getSourceRange();
750 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
751 << VD << VD->getSourceRange();
757 bool VisitStmt(const Stmt *S) {
758 for (auto Child : S->children()) {
759 if (Child && Visit(Child))
764 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
768 OMPThreadPrivateDecl *
769 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
770 SmallVector<Expr *, 8> Vars;
771 for (auto &RefExpr : VarList) {
772 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
773 VarDecl *VD = cast<VarDecl>(DE->getDecl());
774 SourceLocation ILoc = DE->getExprLoc();
776 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
777 // A threadprivate variable must not have an incomplete type.
778 if (RequireCompleteType(ILoc, VD->getType(),
779 diag::err_omp_threadprivate_incomplete_type)) {
783 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
784 // A threadprivate variable must not have a reference type.
785 if (VD->getType()->isReferenceType()) {
786 Diag(ILoc, diag::err_omp_ref_type_arg)
787 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
789 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
790 Diag(VD->getLocation(),
791 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
796 // Check if this is a TLS variable.
797 if (VD->getTLSKind()) {
798 Diag(ILoc, diag::err_omp_var_thread_local) << VD;
800 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
801 Diag(VD->getLocation(),
802 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
807 // Check if initial value of threadprivate variable reference variable with
808 // local storage (it is not supported by runtime).
809 if (auto Init = VD->getAnyInitializer()) {
810 LocalVarRefChecker Checker(*this);
811 if (Checker.Visit(Init))
815 Vars.push_back(RefExpr);
816 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
818 OMPThreadPrivateDecl *D = nullptr;
820 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
822 D->setAccess(AS_public);
827 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
828 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
829 bool IsLoopIterVar = false) {
831 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
832 << getOpenMPClauseName(DVar.CKind);
836 PDSA_StaticMemberShared,
837 PDSA_StaticLocalVarShared,
838 PDSA_LoopIterVarPrivate,
839 PDSA_LoopIterVarLinear,
840 PDSA_LoopIterVarLastprivate,
842 PDSA_GlobalVarShared,
843 PDSA_TaskVarFirstprivate,
844 PDSA_LocalVarPrivate,
846 } Reason = PDSA_Implicit;
847 bool ReportHint = false;
848 auto ReportLoc = VD->getLocation();
850 if (DVar.CKind == OMPC_private)
851 Reason = PDSA_LoopIterVarPrivate;
852 else if (DVar.CKind == OMPC_lastprivate)
853 Reason = PDSA_LoopIterVarLastprivate;
855 Reason = PDSA_LoopIterVarLinear;
856 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
857 Reason = PDSA_TaskVarFirstprivate;
858 ReportLoc = DVar.ImplicitDSALoc;
859 } else if (VD->isStaticLocal())
860 Reason = PDSA_StaticLocalVarShared;
861 else if (VD->isStaticDataMember())
862 Reason = PDSA_StaticMemberShared;
863 else if (VD->isFileVarDecl())
864 Reason = PDSA_GlobalVarShared;
865 else if (VD->getType().isConstant(SemaRef.getASTContext()))
866 Reason = PDSA_ConstVarShared;
867 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
869 Reason = PDSA_LocalVarPrivate;
871 if (Reason != PDSA_Implicit) {
872 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
873 << Reason << ReportHint
874 << getOpenMPDirectiveName(Stack->getCurrentDirective());
875 } else if (DVar.ImplicitDSALoc.isValid()) {
876 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
877 << getOpenMPClauseName(DVar.CKind);
882 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
887 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
888 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
891 void VisitDeclRefExpr(DeclRefExpr *E) {
892 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
893 // Skip internally declared variables.
894 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
897 auto DVar = Stack->getTopDSA(VD, false);
898 // Check if the variable has explicit DSA set and stop analysis if it so.
899 if (DVar.RefExpr) return;
901 auto ELoc = E->getExprLoc();
902 auto DKind = Stack->getCurrentDirective();
903 // The default(none) clause requires that each variable that is referenced
904 // in the construct, and does not have a predetermined data-sharing
905 // attribute, must have its data-sharing attribute explicitly determined
906 // by being listed in a data-sharing attribute clause.
907 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
908 isParallelOrTaskRegion(DKind) &&
909 VarsWithInheritedDSA.count(VD) == 0) {
910 VarsWithInheritedDSA[VD] = E;
914 // OpenMP [2.9.3.6, Restrictions, p.2]
915 // A list item that appears in a reduction clause of the innermost
916 // enclosing worksharing or parallel construct may not be accessed in an
918 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
919 [](OpenMPDirectiveKind K) -> bool {
920 return isOpenMPParallelDirective(K) ||
921 isOpenMPWorksharingDirective(K);
924 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
926 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
927 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
931 // Define implicit data-sharing attributes for task.
932 DVar = Stack->getImplicitDSA(VD, false);
933 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
934 ImplicitFirstprivate.push_back(E);
937 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
938 for (auto *C : S->clauses()) {
939 // Skip analysis of arguments of implicitly defined firstprivate clause
940 // for task directives.
941 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
942 for (auto *CC : C->children()) {
948 void VisitStmt(Stmt *S) {
949 for (auto *C : S->children()) {
950 if (C && !isa<OMPExecutableDirective>(C))
955 bool isErrorFound() { return ErrorFound; }
956 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
957 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
958 return VarsWithInheritedDSA;
961 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
962 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
966 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
968 case OMPD_parallel: {
969 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
970 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
971 Sema::CapturedParamNameType Params[] = {
972 std::make_pair(".global_tid.", KmpInt32PtrTy),
973 std::make_pair(".bound_tid.", KmpInt32PtrTy),
974 std::make_pair(StringRef(), QualType()) // __context with shared vars
976 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
981 Sema::CapturedParamNameType Params[] = {
982 std::make_pair(StringRef(), QualType()) // __context with shared vars
984 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
989 Sema::CapturedParamNameType Params[] = {
990 std::make_pair(StringRef(), QualType()) // __context with shared vars
992 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
996 case OMPD_sections: {
997 Sema::CapturedParamNameType Params[] = {
998 std::make_pair(StringRef(), QualType()) // __context with shared vars
1000 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1004 case OMPD_section: {
1005 Sema::CapturedParamNameType Params[] = {
1006 std::make_pair(StringRef(), QualType()) // __context with shared vars
1008 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1013 Sema::CapturedParamNameType Params[] = {
1014 std::make_pair(StringRef(), QualType()) // __context with shared vars
1016 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1021 Sema::CapturedParamNameType Params[] = {
1022 std::make_pair(StringRef(), QualType()) // __context with shared vars
1024 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1028 case OMPD_critical: {
1029 Sema::CapturedParamNameType Params[] = {
1030 std::make_pair(StringRef(), QualType()) // __context with shared vars
1032 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1036 case OMPD_parallel_for: {
1037 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1038 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1039 Sema::CapturedParamNameType Params[] = {
1040 std::make_pair(".global_tid.", KmpInt32PtrTy),
1041 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1042 std::make_pair(StringRef(), QualType()) // __context with shared vars
1044 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1048 case OMPD_parallel_sections: {
1049 Sema::CapturedParamNameType Params[] = {
1050 std::make_pair(StringRef(), QualType()) // __context with shared vars
1052 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1057 Sema::CapturedParamNameType Params[] = {
1058 std::make_pair(StringRef(), QualType()) // __context with shared vars
1060 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1064 case OMPD_taskyield: {
1065 Sema::CapturedParamNameType Params[] = {
1066 std::make_pair(StringRef(), QualType()) // __context with shared vars
1068 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1072 case OMPD_barrier: {
1073 Sema::CapturedParamNameType Params[] = {
1074 std::make_pair(StringRef(), QualType()) // __context with shared vars
1076 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1080 case OMPD_taskwait: {
1081 Sema::CapturedParamNameType Params[] = {
1082 std::make_pair(StringRef(), QualType()) // __context with shared vars
1084 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1089 Sema::CapturedParamNameType Params[] = {
1090 std::make_pair(StringRef(), QualType()) // __context with shared vars
1092 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1096 case OMPD_threadprivate:
1097 llvm_unreachable("OpenMP Directive is not allowed");
1099 llvm_unreachable("Unknown OpenMP directive");
1103 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1104 OpenMPDirectiveKind CurrentRegion,
1105 const DeclarationNameInfo &CurrentName,
1106 SourceLocation StartLoc) {
1107 // Allowed nesting of constructs
1108 // +------------------+-----------------+------------------------------------+
1109 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1110 // +------------------+-----------------+------------------------------------+
1111 // | parallel | parallel | * |
1112 // | parallel | for | * |
1113 // | parallel | master | * |
1114 // | parallel | critical | * |
1115 // | parallel | simd | * |
1116 // | parallel | sections | * |
1117 // | parallel | section | + |
1118 // | parallel | single | * |
1119 // | parallel | parallel for | * |
1120 // | parallel |parallel sections| * |
1121 // | parallel | task | * |
1122 // | parallel | taskyield | * |
1123 // | parallel | barrier | * |
1124 // | parallel | taskwait | * |
1125 // | parallel | flush | * |
1126 // +------------------+-----------------+------------------------------------+
1127 // | for | parallel | * |
1128 // | for | for | + |
1129 // | for | master | + |
1130 // | for | critical | * |
1131 // | for | simd | * |
1132 // | for | sections | + |
1133 // | for | section | + |
1134 // | for | single | + |
1135 // | for | parallel for | * |
1136 // | for |parallel sections| * |
1137 // | for | task | * |
1138 // | for | taskyield | * |
1139 // | for | barrier | + |
1140 // | for | taskwait | * |
1141 // | for | flush | * |
1142 // +------------------+-----------------+------------------------------------+
1143 // | master | parallel | * |
1144 // | master | for | + |
1145 // | master | master | * |
1146 // | master | critical | * |
1147 // | master | simd | * |
1148 // | master | sections | + |
1149 // | master | section | + |
1150 // | master | single | + |
1151 // | master | parallel for | * |
1152 // | master |parallel sections| * |
1153 // | master | task | * |
1154 // | master | taskyield | * |
1155 // | master | barrier | + |
1156 // | master | taskwait | * |
1157 // | master | flush | * |
1158 // +------------------+-----------------+------------------------------------+
1159 // | critical | parallel | * |
1160 // | critical | for | + |
1161 // | critical | master | * |
1162 // | critical | critical | * (should have dirrerent names) |
1163 // | critical | simd | * |
1164 // | critical | sections | + |
1165 // | critical | section | + |
1166 // | critical | single | + |
1167 // | critical | parallel for | * |
1168 // | critical |parallel sections| * |
1169 // | critical | task | * |
1170 // | critical | taskyield | * |
1171 // | critical | barrier | + |
1172 // | critical | taskwait | * |
1173 // +------------------+-----------------+------------------------------------+
1174 // | simd | parallel | |
1176 // | simd | master | |
1177 // | simd | critical | |
1178 // | simd | simd | |
1179 // | simd | sections | |
1180 // | simd | section | |
1181 // | simd | single | |
1182 // | simd | parallel for | |
1183 // | simd |parallel sections| |
1184 // | simd | task | |
1185 // | simd | taskyield | |
1186 // | simd | barrier | |
1187 // | simd | taskwait | |
1188 // | simd | flush | |
1189 // +------------------+-----------------+------------------------------------+
1190 // | sections | parallel | * |
1191 // | sections | for | + |
1192 // | sections | master | + |
1193 // | sections | critical | * |
1194 // | sections | simd | * |
1195 // | sections | sections | + |
1196 // | sections | section | * |
1197 // | sections | single | + |
1198 // | sections | parallel for | * |
1199 // | sections |parallel sections| * |
1200 // | sections | task | * |
1201 // | sections | taskyield | * |
1202 // | sections | barrier | + |
1203 // | sections | taskwait | * |
1204 // | sections | flush | * |
1205 // +------------------+-----------------+------------------------------------+
1206 // | section | parallel | * |
1207 // | section | for | + |
1208 // | section | master | + |
1209 // | section | critical | * |
1210 // | section | simd | * |
1211 // | section | sections | + |
1212 // | section | section | + |
1213 // | section | single | + |
1214 // | section | parallel for | * |
1215 // | section |parallel sections| * |
1216 // | section | task | * |
1217 // | section | taskyield | * |
1218 // | section | barrier | + |
1219 // | section | taskwait | * |
1220 // | section | flush | * |
1221 // +------------------+-----------------+------------------------------------+
1222 // | single | parallel | * |
1223 // | single | for | + |
1224 // | single | master | + |
1225 // | single | critical | * |
1226 // | single | simd | * |
1227 // | single | sections | + |
1228 // | single | section | + |
1229 // | single | single | + |
1230 // | single | parallel for | * |
1231 // | single |parallel sections| * |
1232 // | single | task | * |
1233 // | single | taskyield | * |
1234 // | single | barrier | + |
1235 // | single | taskwait | * |
1236 // | single | flush | * |
1237 // +------------------+-----------------+------------------------------------+
1238 // | parallel for | parallel | * |
1239 // | parallel for | for | + |
1240 // | parallel for | master | + |
1241 // | parallel for | critical | * |
1242 // | parallel for | simd | * |
1243 // | parallel for | sections | + |
1244 // | parallel for | section | + |
1245 // | parallel for | single | + |
1246 // | parallel for | parallel for | * |
1247 // | parallel for |parallel sections| * |
1248 // | parallel for | task | * |
1249 // | parallel for | taskyield | * |
1250 // | parallel for | barrier | + |
1251 // | parallel for | taskwait | * |
1252 // | parallel for | flush | * |
1253 // +------------------+-----------------+------------------------------------+
1254 // | parallel sections| parallel | * |
1255 // | parallel sections| for | + |
1256 // | parallel sections| master | + |
1257 // | parallel sections| critical | + |
1258 // | parallel sections| simd | * |
1259 // | parallel sections| sections | + |
1260 // | parallel sections| section | * |
1261 // | parallel sections| single | + |
1262 // | parallel sections| parallel for | * |
1263 // | parallel sections|parallel sections| * |
1264 // | parallel sections| task | * |
1265 // | parallel sections| taskyield | * |
1266 // | parallel sections| barrier | + |
1267 // | parallel sections| taskwait | * |
1268 // | parallel sections| flush | * |
1269 // +------------------+-----------------+------------------------------------+
1270 // | task | parallel | * |
1271 // | task | for | + |
1272 // | task | master | + |
1273 // | task | critical | * |
1274 // | task | simd | * |
1275 // | task | sections | + |
1276 // | task | section | + |
1277 // | task | single | + |
1278 // | task | parallel for | * |
1279 // | task |parallel sections| * |
1280 // | task | task | * |
1281 // | task | taskyield | * |
1282 // | task | barrier | + |
1283 // | task | taskwait | * |
1284 // | task | flush | * |
1285 // +------------------+-----------------+------------------------------------+
1286 if (Stack->getCurScope()) {
1287 auto ParentRegion = Stack->getParentDirective();
1288 bool NestingProhibited = false;
1289 bool CloseNesting = true;
1290 bool ShouldBeInParallelRegion = false;
1291 if (isOpenMPSimdDirective(ParentRegion)) {
1292 // OpenMP [2.16, Nesting of Regions]
1293 // OpenMP constructs may not be nested inside a simd region.
1294 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1297 if (CurrentRegion == OMPD_section) {
1298 // OpenMP [2.7.2, sections Construct, Restrictions]
1299 // Orphaned section directives are prohibited. That is, the section
1300 // directives must appear within the sections construct and must not be
1301 // encountered elsewhere in the sections region.
1302 if (ParentRegion != OMPD_sections &&
1303 ParentRegion != OMPD_parallel_sections) {
1304 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1305 << (ParentRegion != OMPD_unknown)
1306 << getOpenMPDirectiveName(ParentRegion);
1311 if (CurrentRegion == OMPD_master) {
1312 // OpenMP [2.16, Nesting of Regions]
1313 // A master region may not be closely nested inside a worksharing,
1314 // atomic (TODO), or explicit task region.
1315 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1316 ParentRegion == OMPD_task;
1317 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1318 // OpenMP [2.16, Nesting of Regions]
1319 // A critical region may not be nested (closely or otherwise) inside a
1320 // critical region with the same name. Note that this restriction is not
1321 // sufficient to prevent deadlock.
1322 SourceLocation PreviousCriticalLoc;
1324 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1325 OpenMPDirectiveKind K,
1326 const DeclarationNameInfo &DNI,
1329 if (K == OMPD_critical &&
1330 DNI.getName() == CurrentName.getName()) {
1331 PreviousCriticalLoc = Loc;
1336 false /* skip top directive */);
1338 SemaRef.Diag(StartLoc,
1339 diag::err_omp_prohibited_region_critical_same_name)
1340 << CurrentName.getName();
1341 if (PreviousCriticalLoc.isValid())
1342 SemaRef.Diag(PreviousCriticalLoc,
1343 diag::note_omp_previous_critical_region);
1346 } else if (CurrentRegion == OMPD_barrier) {
1347 // OpenMP [2.16, Nesting of Regions]
1348 // A barrier region may not be closely nested inside a worksharing,
1349 // explicit task, critical, ordered(TODO), atomic(TODO), or master
1351 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1352 ParentRegion == OMPD_task ||
1353 ParentRegion == OMPD_master ||
1354 ParentRegion == OMPD_critical;
1355 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
1356 !isOpenMPParallelDirective(CurrentRegion) &&
1357 !isOpenMPSimdDirective(CurrentRegion)) {
1358 // OpenMP [2.16, Nesting of Regions]
1359 // A worksharing region may not be closely nested inside a worksharing,
1360 // explicit task, critical, ordered, atomic, or master region.
1362 NestingProhibited = (isOpenMPWorksharingDirective(ParentRegion) &&
1363 !isOpenMPSimdDirective(ParentRegion)) ||
1364 ParentRegion == OMPD_task ||
1365 ParentRegion == OMPD_master ||
1366 ParentRegion == OMPD_critical;
1367 ShouldBeInParallelRegion = true;
1369 if (NestingProhibited) {
1370 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
1371 << CloseNesting << getOpenMPDirectiveName(ParentRegion)
1372 << ShouldBeInParallelRegion << getOpenMPDirectiveName(CurrentRegion);
1379 StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
1380 const DeclarationNameInfo &DirName,
1381 ArrayRef<OMPClause *> Clauses,
1383 SourceLocation StartLoc,
1384 SourceLocation EndLoc) {
1385 StmtResult Res = StmtError();
1386 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
1389 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
1390 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
1391 bool ErrorFound = false;
1392 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
1394 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1396 // Check default data sharing attributes for referenced variables.
1397 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1398 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1399 if (DSAChecker.isErrorFound())
1401 // Generate list of implicitly defined firstprivate variables.
1402 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
1404 if (!DSAChecker.getImplicitFirstprivate().empty()) {
1405 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1406 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1407 SourceLocation(), SourceLocation())) {
1408 ClausesWithImplicit.push_back(Implicit);
1409 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1410 DSAChecker.getImplicitFirstprivate().size();
1418 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1422 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1423 VarsWithInheritedDSA);
1426 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1427 VarsWithInheritedDSA);
1430 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1434 assert(ClausesWithImplicit.empty() &&
1435 "No clauses are allowed for 'omp section' directive");
1436 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1439 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1443 assert(ClausesWithImplicit.empty() &&
1444 "No clauses are allowed for 'omp master' directive");
1445 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1448 assert(ClausesWithImplicit.empty() &&
1449 "No clauses are allowed for 'omp critical' directive");
1450 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1452 case OMPD_parallel_for:
1453 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1454 EndLoc, VarsWithInheritedDSA);
1456 case OMPD_parallel_sections:
1457 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1462 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1464 case OMPD_taskyield:
1465 assert(ClausesWithImplicit.empty() &&
1466 "No clauses are allowed for 'omp taskyield' directive");
1467 assert(AStmt == nullptr &&
1468 "No associated statement allowed for 'omp taskyield' directive");
1469 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1472 assert(ClausesWithImplicit.empty() &&
1473 "No clauses are allowed for 'omp barrier' directive");
1474 assert(AStmt == nullptr &&
1475 "No associated statement allowed for 'omp barrier' directive");
1476 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1479 assert(ClausesWithImplicit.empty() &&
1480 "No clauses are allowed for 'omp taskwait' directive");
1481 assert(AStmt == nullptr &&
1482 "No associated statement allowed for 'omp taskwait' directive");
1483 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1486 assert(AStmt == nullptr &&
1487 "No associated statement allowed for 'omp flush' directive");
1488 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
1490 case OMPD_threadprivate:
1491 llvm_unreachable("OpenMP Directive is not allowed");
1493 llvm_unreachable("Unknown OpenMP directive");
1496 for (auto P : VarsWithInheritedDSA) {
1497 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1498 << P.first << P.second->getSourceRange();
1500 if (!VarsWithInheritedDSA.empty())
1508 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
1510 SourceLocation StartLoc,
1511 SourceLocation EndLoc) {
1512 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
1513 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
1514 // 1.2.2 OpenMP Language Terminology
1515 // Structured block - An executable statement with a single entry at the
1516 // top and a single exit at the bottom.
1517 // The point of exit cannot be a branch out of the structured block.
1518 // longjmp() and throw() must not violate the entry/exit criteria.
1519 CS->getCapturedDecl()->setNothrow();
1521 getCurFunction()->setHasBranchProtectedScope();
1523 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
1528 /// \brief Helper class for checking canonical form of the OpenMP loops and
1529 /// extracting iteration space of each loop in the loop nest, that will be used
1530 /// for IR generation.
1531 class OpenMPIterationSpaceChecker {
1532 /// \brief Reference to Sema.
1534 /// \brief A location for diagnostics (when there is no some better location).
1535 SourceLocation DefaultLoc;
1536 /// \brief A location for diagnostics (when increment is not compatible).
1537 SourceLocation ConditionLoc;
1538 /// \brief A source location for referring to condition later.
1539 SourceRange ConditionSrcRange;
1540 /// \brief Loop variable.
1542 /// \brief Lower bound (initializer for the var).
1544 /// \brief Upper bound.
1546 /// \brief Loop step (increment).
1548 /// \brief This flag is true when condition is one of:
1554 /// \brief This flag is true when condition is strict ( < or > ).
1555 bool TestIsStrictOp;
1556 /// \brief This flag is true when step is subtracted on each iteration.
1560 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
1561 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
1562 ConditionSrcRange(SourceRange()), Var(nullptr), LB(nullptr),
1563 UB(nullptr), Step(nullptr), TestIsLessOp(false), TestIsStrictOp(false),
1564 SubtractStep(false) {}
1565 /// \brief Check init-expr for canonical loop form and save loop counter
1566 /// variable - #Var and its initialization value - #LB.
1567 bool CheckInit(Stmt *S);
1568 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
1569 /// for less/greater and for strict/non-strict comparison.
1570 bool CheckCond(Expr *S);
1571 /// \brief Check incr-expr for canonical loop form and return true if it
1572 /// does not conform, otherwise save loop step (#Step).
1573 bool CheckInc(Expr *S);
1574 /// \brief Return the loop counter variable.
1575 VarDecl *GetLoopVar() const { return Var; }
1576 /// \brief Return true if any expression is dependent.
1577 bool Dependent() const;
1580 /// \brief Check the right-hand side of an assignment in the increment
1582 bool CheckIncRHS(Expr *RHS);
1583 /// \brief Helper to set loop counter variable and its initializer.
1584 bool SetVarAndLB(VarDecl *NewVar, Expr *NewLB);
1585 /// \brief Helper to set upper bound.
1586 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
1587 const SourceLocation &SL);
1588 /// \brief Helper to set loop increment.
1589 bool SetStep(Expr *NewStep, bool Subtract);
1592 bool OpenMPIterationSpaceChecker::Dependent() const {
1594 assert(!LB && !UB && !Step);
1597 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
1598 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
1601 bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar, Expr *NewLB) {
1602 // State consistency checking to ensure correct usage.
1603 assert(Var == nullptr && LB == nullptr && UB == nullptr && Step == nullptr &&
1604 !TestIsLessOp && !TestIsStrictOp);
1605 if (!NewVar || !NewLB)
1612 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
1613 const SourceRange &SR,
1614 const SourceLocation &SL) {
1615 // State consistency checking to ensure correct usage.
1616 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
1617 !TestIsLessOp && !TestIsStrictOp);
1621 TestIsLessOp = LessOp;
1622 TestIsStrictOp = StrictOp;
1623 ConditionSrcRange = SR;
1628 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
1629 // State consistency checking to ensure correct usage.
1630 assert(Var != nullptr && LB != nullptr && Step == nullptr);
1633 if (!NewStep->isValueDependent()) {
1634 // Check that the step is integer expression.
1635 SourceLocation StepLoc = NewStep->getLocStart();
1637 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
1638 if (Val.isInvalid())
1640 NewStep = Val.get();
1642 // OpenMP [2.6, Canonical Loop Form, Restrictions]
1643 // If test-expr is of form var relational-op b and relational-op is < or
1644 // <= then incr-expr must cause var to increase on each iteration of the
1645 // loop. If test-expr is of form var relational-op b and relational-op is
1646 // > or >= then incr-expr must cause var to decrease on each iteration of
1648 // If test-expr is of form b relational-op var and relational-op is < or
1649 // <= then incr-expr must cause var to decrease on each iteration of the
1650 // loop. If test-expr is of form b relational-op var and relational-op is
1651 // > or >= then incr-expr must cause var to increase on each iteration of
1653 llvm::APSInt Result;
1654 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
1655 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
1657 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
1658 bool IsConstZero = IsConstant && !Result.getBoolValue();
1659 if (UB && (IsConstZero ||
1660 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
1661 : (!IsConstNeg || (IsUnsigned && !Subtract))))) {
1662 SemaRef.Diag(NewStep->getExprLoc(),
1663 diag::err_omp_loop_incr_not_compatible)
1664 << Var << TestIsLessOp << NewStep->getSourceRange();
1665 SemaRef.Diag(ConditionLoc,
1666 diag::note_omp_loop_cond_requres_compatible_incr)
1667 << TestIsLessOp << ConditionSrcRange;
1673 SubtractStep = Subtract;
1677 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S) {
1678 // Check init-expr for canonical loop form and save loop counter
1679 // variable - #Var and its initialization value - #LB.
1680 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
1682 // integer-type var = lb
1683 // random-access-iterator-type var = lb
1684 // pointer-type var = lb
1687 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
1690 if (Expr *E = dyn_cast<Expr>(S))
1691 S = E->IgnoreParens();
1692 if (auto BO = dyn_cast<BinaryOperator>(S)) {
1693 if (BO->getOpcode() == BO_Assign)
1694 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
1695 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), BO->getLHS());
1696 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
1697 if (DS->isSingleDecl()) {
1698 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
1699 if (Var->hasInit()) {
1700 // Accept non-canonical init form here but emit ext. warning.
1701 if (Var->getInitStyle() != VarDecl::CInit)
1702 SemaRef.Diag(S->getLocStart(),
1703 diag::ext_omp_loop_not_canonical_init)
1704 << S->getSourceRange();
1705 return SetVarAndLB(Var, Var->getInit());
1709 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
1710 if (CE->getOperator() == OO_Equal)
1711 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
1712 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), CE->getArg(1));
1714 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
1715 << S->getSourceRange();
1719 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
1720 /// variable (which may be the loop variable) if possible.
1721 static const VarDecl *GetInitVarDecl(const Expr *E) {
1724 E = E->IgnoreParenImpCasts();
1725 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
1726 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
1727 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
1728 CE->getArg(0) != nullptr)
1729 E = CE->getArg(0)->IgnoreParenImpCasts();
1730 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
1733 return dyn_cast<VarDecl>(DRE->getDecl());
1736 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
1737 // Check test-expr for canonical form, save upper-bound UB, flags for
1738 // less/greater and for strict/non-strict comparison.
1739 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
1740 // var relational-op b
1741 // b relational-op var
1744 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
1747 S = S->IgnoreParenImpCasts();
1748 SourceLocation CondLoc = S->getLocStart();
1749 if (auto BO = dyn_cast<BinaryOperator>(S)) {
1750 if (BO->isRelationalOp()) {
1751 if (GetInitVarDecl(BO->getLHS()) == Var)
1752 return SetUB(BO->getRHS(),
1753 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
1754 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
1755 BO->getSourceRange(), BO->getOperatorLoc());
1756 if (GetInitVarDecl(BO->getRHS()) == Var)
1757 return SetUB(BO->getLHS(),
1758 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
1759 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
1760 BO->getSourceRange(), BO->getOperatorLoc());
1762 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
1763 if (CE->getNumArgs() == 2) {
1764 auto Op = CE->getOperator();
1767 case OO_GreaterEqual:
1770 if (GetInitVarDecl(CE->getArg(0)) == Var)
1771 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
1772 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
1773 CE->getOperatorLoc());
1774 if (GetInitVarDecl(CE->getArg(1)) == Var)
1775 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
1776 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
1777 CE->getOperatorLoc());
1784 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
1785 << S->getSourceRange() << Var;
1789 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
1790 // RHS of canonical loop form increment can be:
1795 RHS = RHS->IgnoreParenImpCasts();
1796 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
1797 if (BO->isAdditiveOp()) {
1798 bool IsAdd = BO->getOpcode() == BO_Add;
1799 if (GetInitVarDecl(BO->getLHS()) == Var)
1800 return SetStep(BO->getRHS(), !IsAdd);
1801 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
1802 return SetStep(BO->getLHS(), false);
1804 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
1805 bool IsAdd = CE->getOperator() == OO_Plus;
1806 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
1807 if (GetInitVarDecl(CE->getArg(0)) == Var)
1808 return SetStep(CE->getArg(1), !IsAdd);
1809 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
1810 return SetStep(CE->getArg(0), false);
1813 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
1814 << RHS->getSourceRange() << Var;
1818 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
1819 // Check incr-expr for canonical loop form and return true if it
1820 // does not conform.
1821 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
1833 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
1836 S = S->IgnoreParens();
1837 if (auto UO = dyn_cast<UnaryOperator>(S)) {
1838 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
1840 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
1841 (UO->isDecrementOp() ? -1 : 1)).get(),
1843 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
1844 switch (BO->getOpcode()) {
1847 if (GetInitVarDecl(BO->getLHS()) == Var)
1848 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
1851 if (GetInitVarDecl(BO->getLHS()) == Var)
1852 return CheckIncRHS(BO->getRHS());
1857 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
1858 switch (CE->getOperator()) {
1861 if (GetInitVarDecl(CE->getArg(0)) == Var)
1863 SemaRef.ActOnIntegerConstant(
1865 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
1870 if (GetInitVarDecl(CE->getArg(0)) == Var)
1871 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
1874 if (GetInitVarDecl(CE->getArg(0)) == Var)
1875 return CheckIncRHS(CE->getArg(1));
1881 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
1882 << S->getSourceRange() << Var;
1887 /// \brief Called on a for stmt to check and extract its iteration space
1888 /// for further processing (such as collapsing).
1889 static bool CheckOpenMPIterationSpace(
1890 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
1891 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
1892 Expr *NestedLoopCountExpr,
1893 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
1894 // OpenMP [2.6, Canonical Loop Form]
1895 // for (init-expr; test-expr; incr-expr) structured-block
1896 auto For = dyn_cast_or_null<ForStmt>(S);
1898 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
1899 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
1900 << NestedLoopCount << (CurrentNestedLoopCount > 0)
1901 << CurrentNestedLoopCount;
1902 if (NestedLoopCount > 1)
1903 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
1904 diag::note_omp_collapse_expr)
1905 << NestedLoopCountExpr->getSourceRange();
1908 assert(For->getBody());
1910 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
1913 auto Init = For->getInit();
1914 if (ISC.CheckInit(Init)) {
1918 bool HasErrors = false;
1920 // Check loop variable's type.
1921 auto Var = ISC.GetLoopVar();
1923 // OpenMP [2.6, Canonical Loop Form]
1924 // Var is one of the following:
1925 // A variable of signed or unsigned integer type.
1926 // For C++, a variable of a random access iterator type.
1927 // For C, a variable of a pointer type.
1928 auto VarType = Var->getType();
1929 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
1930 !VarType->isPointerType() &&
1931 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
1932 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
1933 << SemaRef.getLangOpts().CPlusPlus;
1937 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
1939 // The loop iteration variable(s) in the associated for-loop(s) of a for or
1940 // parallel for construct is (are) private.
1941 // The loop iteration variable in the associated for-loop of a simd construct
1942 // with just one associated for-loop is linear with a constant-linear-step
1943 // that is the increment of the associated for-loop.
1944 // Exclude loop var from the list of variables with implicitly defined data
1945 // sharing attributes.
1946 while (VarsWithImplicitDSA.count(Var) > 0)
1947 VarsWithImplicitDSA.erase(Var);
1949 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
1950 // a Construct, C/C++].
1951 // The loop iteration variable in the associated for-loop of a simd construct
1952 // with just one associated for-loop may be listed in a linear clause with a
1953 // constant-linear-step that is the increment of the associated for-loop.
1954 // The loop iteration variable(s) in the associated for-loop(s) of a for or
1955 // parallel for construct may be listed in a private or lastprivate clause.
1956 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
1957 auto PredeterminedCKind =
1958 isOpenMPSimdDirective(DKind)
1959 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
1961 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
1962 DVar.CKind != PredeterminedCKind) ||
1963 (isOpenMPWorksharingDirective(DKind) && DVar.CKind != OMPC_unknown &&
1964 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
1965 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
1966 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
1967 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
1968 << getOpenMPClauseName(PredeterminedCKind);
1969 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, true);
1972 // Make the loop iteration variable private (for worksharing constructs),
1973 // linear (for simd directives with the only one associated loop) or
1974 // lastprivate (for simd directives with several collapsed loops).
1975 DSA.addDSA(Var, nullptr, PredeterminedCKind);
1978 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
1981 HasErrors |= ISC.CheckCond(For->getCond());
1984 HasErrors |= ISC.CheckInc(For->getInc());
1986 if (ISC.Dependent())
1989 // FIXME: Build loop's iteration space representation.
1993 /// \brief A helper routine to skip no-op (attributed, compound) stmts get the
1994 /// next nested for loop. If \a IgnoreCaptured is true, it skips captured stmt
1995 /// to get the first for loop.
1996 static Stmt *IgnoreContainerStmts(Stmt *S, bool IgnoreCaptured) {
1998 if (auto CapS = dyn_cast_or_null<CapturedStmt>(S))
1999 S = CapS->getCapturedStmt();
2000 // OpenMP [2.8.1, simd construct, Restrictions]
2001 // All loops associated with the construct must be perfectly nested; that is,
2002 // there must be no intervening code nor any OpenMP directive between any two
2005 if (auto AS = dyn_cast_or_null<AttributedStmt>(S))
2006 S = AS->getSubStmt();
2007 else if (auto CS = dyn_cast_or_null<CompoundStmt>(S)) {
2008 if (CS->size() != 1)
2010 S = CS->body_back();
2017 /// \brief Called on a for stmt to check itself and nested loops (if any).
2018 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2019 /// number of collapsed loops otherwise.
2021 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2022 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
2023 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
2024 unsigned NestedLoopCount = 1;
2025 if (NestedLoopCountExpr) {
2026 // Found 'collapse' clause - calculate collapse number.
2027 llvm::APSInt Result;
2028 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2029 NestedLoopCount = Result.getLimitedValue();
2031 // This is helper routine for loop directives (e.g., 'for', 'simd',
2032 // 'for simd', etc.).
2033 Stmt *CurStmt = IgnoreContainerStmts(AStmt, true);
2034 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
2035 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
2036 NestedLoopCount, NestedLoopCountExpr,
2037 VarsWithImplicitDSA))
2039 // Move on to the next nested for loop, or to the loop body.
2040 CurStmt = IgnoreContainerStmts(cast<ForStmt>(CurStmt)->getBody(), false);
2043 // FIXME: Build resulting iteration space for IR generation (collapsing
2044 // iteration spaces when loop count > 1 ('collapse' clause)).
2045 return NestedLoopCount;
2048 static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
2049 auto CollapseFilter = [](const OMPClause *C) -> bool {
2050 return C->getClauseKind() == OMPC_collapse;
2052 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
2053 Clauses, CollapseFilter);
2055 return cast<OMPCollapseClause>(*I)->getNumForLoops();
2059 StmtResult Sema::ActOnOpenMPSimdDirective(
2060 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2061 SourceLocation EndLoc,
2062 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
2063 // In presence of clause 'collapse', it will define the nested loops number.
2064 unsigned NestedLoopCount =
2065 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
2066 *DSAStack, VarsWithImplicitDSA);
2067 if (NestedLoopCount == 0)
2070 getCurFunction()->setHasBranchProtectedScope();
2071 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
2075 StmtResult Sema::ActOnOpenMPForDirective(
2076 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2077 SourceLocation EndLoc,
2078 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
2079 // In presence of clause 'collapse', it will define the nested loops number.
2080 unsigned NestedLoopCount =
2081 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
2082 *DSAStack, VarsWithImplicitDSA);
2083 if (NestedLoopCount == 0)
2086 getCurFunction()->setHasBranchProtectedScope();
2087 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
2091 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
2093 SourceLocation StartLoc,
2094 SourceLocation EndLoc) {
2095 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2096 auto BaseStmt = AStmt;
2097 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
2098 BaseStmt = CS->getCapturedStmt();
2099 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
2100 auto S = C->children();
2103 // All associated statements must be '#pragma omp section' except for
2106 auto SectionStmt = *S;
2107 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
2109 Diag(SectionStmt->getLocStart(),
2110 diag::err_omp_sections_substmt_not_section);
2115 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
2119 getCurFunction()->setHasBranchProtectedScope();
2121 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
2125 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
2126 SourceLocation StartLoc,
2127 SourceLocation EndLoc) {
2128 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2130 getCurFunction()->setHasBranchProtectedScope();
2132 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
2135 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
2137 SourceLocation StartLoc,
2138 SourceLocation EndLoc) {
2139 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2141 getCurFunction()->setHasBranchProtectedScope();
2143 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
2146 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
2147 SourceLocation StartLoc,
2148 SourceLocation EndLoc) {
2149 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2151 getCurFunction()->setHasBranchProtectedScope();
2153 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
2157 Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
2158 Stmt *AStmt, SourceLocation StartLoc,
2159 SourceLocation EndLoc) {
2160 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2162 getCurFunction()->setHasBranchProtectedScope();
2164 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
2168 StmtResult Sema::ActOnOpenMPParallelForDirective(
2169 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2170 SourceLocation EndLoc,
2171 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
2172 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2173 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2174 // 1.2.2 OpenMP Language Terminology
2175 // Structured block - An executable statement with a single entry at the
2176 // top and a single exit at the bottom.
2177 // The point of exit cannot be a branch out of the structured block.
2178 // longjmp() and throw() must not violate the entry/exit criteria.
2179 CS->getCapturedDecl()->setNothrow();
2181 // In presence of clause 'collapse', it will define the nested loops number.
2182 unsigned NestedLoopCount =
2183 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
2184 *this, *DSAStack, VarsWithImplicitDSA);
2185 if (NestedLoopCount == 0)
2188 getCurFunction()->setHasBranchProtectedScope();
2189 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
2190 NestedLoopCount, Clauses, AStmt);
2194 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
2195 Stmt *AStmt, SourceLocation StartLoc,
2196 SourceLocation EndLoc) {
2197 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2198 auto BaseStmt = AStmt;
2199 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
2200 BaseStmt = CS->getCapturedStmt();
2201 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
2202 auto S = C->children();
2205 // All associated statements must be '#pragma omp section' except for
2208 auto SectionStmt = *S;
2209 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
2211 Diag(SectionStmt->getLocStart(),
2212 diag::err_omp_parallel_sections_substmt_not_section);
2217 Diag(AStmt->getLocStart(),
2218 diag::err_omp_parallel_sections_not_compound_stmt);
2222 getCurFunction()->setHasBranchProtectedScope();
2224 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
2228 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
2229 Stmt *AStmt, SourceLocation StartLoc,
2230 SourceLocation EndLoc) {
2231 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2232 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2233 // 1.2.2 OpenMP Language Terminology
2234 // Structured block - An executable statement with a single entry at the
2235 // top and a single exit at the bottom.
2236 // The point of exit cannot be a branch out of the structured block.
2237 // longjmp() and throw() must not violate the entry/exit criteria.
2238 CS->getCapturedDecl()->setNothrow();
2240 getCurFunction()->setHasBranchProtectedScope();
2242 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
2245 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
2246 SourceLocation EndLoc) {
2247 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
2250 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
2251 SourceLocation EndLoc) {
2252 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
2255 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
2256 SourceLocation EndLoc) {
2257 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
2260 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
2261 SourceLocation StartLoc,
2262 SourceLocation EndLoc) {
2263 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
2264 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
2267 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
2268 SourceLocation StartLoc,
2269 SourceLocation LParenLoc,
2270 SourceLocation EndLoc) {
2271 OMPClause *Res = nullptr;
2274 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
2277 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
2279 case OMPC_num_threads:
2280 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
2283 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
2286 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
2289 case OMPC_proc_bind:
2292 case OMPC_firstprivate:
2293 case OMPC_lastprivate:
2295 case OMPC_reduction:
2299 case OMPC_copyprivate:
2303 case OMPC_mergeable:
2304 case OMPC_threadprivate:
2307 llvm_unreachable("Clause is not allowed.");
2312 OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
2313 SourceLocation LParenLoc,
2314 SourceLocation EndLoc) {
2315 Expr *ValExpr = Condition;
2316 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
2317 !Condition->isInstantiationDependent() &&
2318 !Condition->containsUnexpandedParameterPack()) {
2319 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
2320 Condition->getExprLoc(), Condition);
2321 if (Val.isInvalid())
2324 ValExpr = Val.get();
2327 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
2330 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
2331 SourceLocation StartLoc,
2332 SourceLocation LParenLoc,
2333 SourceLocation EndLoc) {
2334 Expr *ValExpr = Condition;
2335 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
2336 !Condition->isInstantiationDependent() &&
2337 !Condition->containsUnexpandedParameterPack()) {
2338 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
2339 Condition->getExprLoc(), Condition);
2340 if (Val.isInvalid())
2343 ValExpr = Val.get();
2346 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
2349 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
2354 class IntConvertDiagnoser : public ICEConvertDiagnoser {
2356 IntConvertDiagnoser()
2357 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
2358 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2359 QualType T) override {
2360 return S.Diag(Loc, diag::err_omp_not_integral) << T;
2362 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2363 QualType T) override {
2364 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
2366 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2368 QualType ConvTy) override {
2369 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
2371 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2372 QualType ConvTy) override {
2373 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
2374 << ConvTy->isEnumeralType() << ConvTy;
2376 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2377 QualType T) override {
2378 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
2380 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2381 QualType ConvTy) override {
2382 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
2383 << ConvTy->isEnumeralType() << ConvTy;
2385 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
2386 QualType) override {
2387 llvm_unreachable("conversion functions are permitted");
2390 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
2393 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
2394 SourceLocation StartLoc,
2395 SourceLocation LParenLoc,
2396 SourceLocation EndLoc) {
2397 Expr *ValExpr = NumThreads;
2398 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
2399 !NumThreads->isInstantiationDependent() &&
2400 !NumThreads->containsUnexpandedParameterPack()) {
2401 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
2403 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
2404 if (Val.isInvalid())
2407 ValExpr = Val.get();
2409 // OpenMP [2.5, Restrictions]
2410 // The num_threads expression must evaluate to a positive integer value.
2411 llvm::APSInt Result;
2412 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
2413 !Result.isStrictlyPositive()) {
2414 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
2415 << "num_threads" << NumThreads->getSourceRange();
2420 return new (Context)
2421 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
2424 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
2425 OpenMPClauseKind CKind) {
2428 if (E->isValueDependent() || E->isTypeDependent() ||
2429 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2431 llvm::APSInt Result;
2432 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
2433 if (ICE.isInvalid())
2435 if (!Result.isStrictlyPositive()) {
2436 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
2437 << getOpenMPClauseName(CKind) << E->getSourceRange();
2443 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
2444 SourceLocation LParenLoc,
2445 SourceLocation EndLoc) {
2446 // OpenMP [2.8.1, simd construct, Description]
2447 // The parameter of the safelen clause must be a constant
2448 // positive integer expression.
2449 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
2450 if (Safelen.isInvalid())
2452 return new (Context)
2453 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
2456 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
2457 SourceLocation StartLoc,
2458 SourceLocation LParenLoc,
2459 SourceLocation EndLoc) {
2460 // OpenMP [2.7.1, loop construct, Description]
2461 // OpenMP [2.8.1, simd construct, Description]
2462 // OpenMP [2.9.6, distribute construct, Description]
2463 // The parameter of the collapse clause must be a constant
2464 // positive integer expression.
2465 ExprResult NumForLoopsResult =
2466 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
2467 if (NumForLoopsResult.isInvalid())
2469 return new (Context)
2470 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
2473 OMPClause *Sema::ActOnOpenMPSimpleClause(
2474 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
2475 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
2476 OMPClause *Res = nullptr;
2480 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
2481 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
2483 case OMPC_proc_bind:
2484 Res = ActOnOpenMPProcBindClause(
2485 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
2490 case OMPC_num_threads:
2495 case OMPC_firstprivate:
2496 case OMPC_lastprivate:
2498 case OMPC_reduction:
2502 case OMPC_copyprivate:
2506 case OMPC_mergeable:
2507 case OMPC_threadprivate:
2510 llvm_unreachable("Clause is not allowed.");
2515 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
2516 SourceLocation KindKwLoc,
2517 SourceLocation StartLoc,
2518 SourceLocation LParenLoc,
2519 SourceLocation EndLoc) {
2520 if (Kind == OMPC_DEFAULT_unknown) {
2522 static_assert(OMPC_DEFAULT_unknown > 0,
2523 "OMPC_DEFAULT_unknown not greater than 0");
2524 std::string Sep(", ");
2525 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
2527 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
2530 case OMPC_DEFAULT_unknown - 2:
2533 case OMPC_DEFAULT_unknown - 1:
2540 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
2541 << Values << getOpenMPClauseName(OMPC_default);
2545 case OMPC_DEFAULT_none:
2546 DSAStack->setDefaultDSANone(KindKwLoc);
2548 case OMPC_DEFAULT_shared:
2549 DSAStack->setDefaultDSAShared(KindKwLoc);
2551 case OMPC_DEFAULT_unknown:
2552 llvm_unreachable("Clause kind is not allowed.");
2555 return new (Context)
2556 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
2559 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
2560 SourceLocation KindKwLoc,
2561 SourceLocation StartLoc,
2562 SourceLocation LParenLoc,
2563 SourceLocation EndLoc) {
2564 if (Kind == OMPC_PROC_BIND_unknown) {
2566 std::string Sep(", ");
2567 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
2569 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
2572 case OMPC_PROC_BIND_unknown - 2:
2575 case OMPC_PROC_BIND_unknown - 1:
2582 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
2583 << Values << getOpenMPClauseName(OMPC_proc_bind);
2586 return new (Context)
2587 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
2590 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
2591 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
2592 SourceLocation StartLoc, SourceLocation LParenLoc,
2593 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
2594 SourceLocation EndLoc) {
2595 OMPClause *Res = nullptr;
2598 Res = ActOnOpenMPScheduleClause(
2599 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
2600 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
2604 case OMPC_num_threads:
2608 case OMPC_proc_bind:
2610 case OMPC_firstprivate:
2611 case OMPC_lastprivate:
2613 case OMPC_reduction:
2617 case OMPC_copyprivate:
2621 case OMPC_mergeable:
2622 case OMPC_threadprivate:
2625 llvm_unreachable("Clause is not allowed.");
2630 OMPClause *Sema::ActOnOpenMPScheduleClause(
2631 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
2632 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
2633 SourceLocation EndLoc) {
2634 if (Kind == OMPC_SCHEDULE_unknown) {
2636 std::string Sep(", ");
2637 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
2639 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
2642 case OMPC_SCHEDULE_unknown - 2:
2645 case OMPC_SCHEDULE_unknown - 1:
2652 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
2653 << Values << getOpenMPClauseName(OMPC_schedule);
2656 Expr *ValExpr = ChunkSize;
2658 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
2659 !ChunkSize->isInstantiationDependent() &&
2660 !ChunkSize->containsUnexpandedParameterPack()) {
2661 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
2663 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
2664 if (Val.isInvalid())
2667 ValExpr = Val.get();
2669 // OpenMP [2.7.1, Restrictions]
2670 // chunk_size must be a loop invariant integer expression with a positive
2672 llvm::APSInt Result;
2673 if (ValExpr->isIntegerConstantExpr(Result, Context) &&
2674 Result.isSigned() && !Result.isStrictlyPositive()) {
2675 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
2676 << "schedule" << ChunkSize->getSourceRange();
2682 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
2683 EndLoc, Kind, ValExpr);
2686 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
2687 SourceLocation StartLoc,
2688 SourceLocation EndLoc) {
2689 OMPClause *Res = nullptr;
2692 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
2695 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
2698 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
2700 case OMPC_mergeable:
2701 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
2705 case OMPC_num_threads:
2710 case OMPC_firstprivate:
2711 case OMPC_lastprivate:
2713 case OMPC_reduction:
2717 case OMPC_copyprivate:
2719 case OMPC_proc_bind:
2720 case OMPC_threadprivate:
2723 llvm_unreachable("Clause is not allowed.");
2728 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
2729 SourceLocation EndLoc) {
2730 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
2733 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
2734 SourceLocation EndLoc) {
2735 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
2738 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
2739 SourceLocation EndLoc) {
2740 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
2743 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
2744 SourceLocation EndLoc) {
2745 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
2748 OMPClause *Sema::ActOnOpenMPVarListClause(
2749 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
2750 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
2751 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
2752 const DeclarationNameInfo &ReductionId) {
2753 OMPClause *Res = nullptr;
2756 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
2758 case OMPC_firstprivate:
2759 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
2761 case OMPC_lastprivate:
2762 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
2765 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
2767 case OMPC_reduction:
2768 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
2769 EndLoc, ReductionIdScopeSpec, ReductionId);
2772 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
2776 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
2780 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
2782 case OMPC_copyprivate:
2783 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
2786 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
2790 case OMPC_num_threads:
2794 case OMPC_proc_bind:
2799 case OMPC_mergeable:
2800 case OMPC_threadprivate:
2802 llvm_unreachable("Clause is not allowed.");
2807 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
2808 SourceLocation StartLoc,
2809 SourceLocation LParenLoc,
2810 SourceLocation EndLoc) {
2811 SmallVector<Expr *, 8> Vars;
2812 for (auto &RefExpr : VarList) {
2813 assert(RefExpr && "NULL expr in OpenMP private clause.");
2814 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
2815 // It will be analyzed later.
2816 Vars.push_back(RefExpr);
2820 SourceLocation ELoc = RefExpr->getExprLoc();
2821 // OpenMP [2.1, C/C++]
2822 // A list item is a variable name.
2823 // OpenMP [2.9.3.3, Restrictions, p.1]
2824 // A variable that is part of another variable (as an array or
2825 // structure element) cannot appear in a private clause.
2826 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
2827 if (!DE || !isa<VarDecl>(DE->getDecl())) {
2828 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
2831 Decl *D = DE->getDecl();
2832 VarDecl *VD = cast<VarDecl>(D);
2834 QualType Type = VD->getType();
2835 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
2836 // It will be analyzed later.
2841 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
2842 // A variable that appears in a private clause must not have an incomplete
2843 // type or a reference type.
2844 if (RequireCompleteType(ELoc, Type,
2845 diag::err_omp_private_incomplete_type)) {
2848 if (Type->isReferenceType()) {
2849 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
2850 << getOpenMPClauseName(OMPC_private) << Type;
2852 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2853 Diag(VD->getLocation(),
2854 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2859 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
2860 // A variable of class type (or array thereof) that appears in a private
2861 // clause requires an accessible, unambiguous default constructor for the
2863 while (Type.getNonReferenceType()->isArrayType()) {
2864 Type = cast<ArrayType>(Type.getNonReferenceType().getTypePtr())
2867 CXXRecordDecl *RD = getLangOpts().CPlusPlus
2868 ? Type.getNonReferenceType()->getAsCXXRecordDecl()
2870 // FIXME This code must be replaced by actual constructing/destructing of
2871 // the private variable.
2873 CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
2874 PartialDiagnostic PD =
2875 PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
2877 CheckConstructorAccess(ELoc, CD,
2878 InitializedEntity::InitializeTemporary(Type),
2879 CD->getAccess(), PD) == AR_inaccessible ||
2881 Diag(ELoc, diag::err_omp_required_method)
2882 << getOpenMPClauseName(OMPC_private) << 0;
2883 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2884 VarDecl::DeclarationOnly;
2885 Diag(VD->getLocation(),
2886 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2888 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
2891 MarkFunctionReferenced(ELoc, CD);
2892 DiagnoseUseOfDecl(CD, ELoc);
2894 CXXDestructorDecl *DD = RD->getDestructor();
2896 if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
2898 Diag(ELoc, diag::err_omp_required_method)
2899 << getOpenMPClauseName(OMPC_private) << 4;
2900 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2901 VarDecl::DeclarationOnly;
2902 Diag(VD->getLocation(),
2903 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2905 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
2908 MarkFunctionReferenced(ELoc, DD);
2909 DiagnoseUseOfDecl(DD, ELoc);
2913 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
2915 // Variables with the predetermined data-sharing attributes may not be
2916 // listed in data-sharing attributes clauses, except for the cases
2917 // listed below. For these exceptions only, listing a predetermined
2918 // variable in a data-sharing attribute clause is allowed and overrides
2919 // the variable's predetermined data-sharing attributes.
2920 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
2921 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
2922 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
2923 << getOpenMPClauseName(OMPC_private);
2924 ReportOriginalDSA(*this, DSAStack, VD, DVar);
2928 DSAStack->addDSA(VD, DE, OMPC_private);
2935 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
2938 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
2939 SourceLocation StartLoc,
2940 SourceLocation LParenLoc,
2941 SourceLocation EndLoc) {
2942 SmallVector<Expr *, 8> Vars;
2943 bool IsImplicitClause =
2944 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
2945 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
2947 for (auto &RefExpr : VarList) {
2948 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
2949 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
2950 // It will be analyzed later.
2951 Vars.push_back(RefExpr);
2955 SourceLocation ELoc = IsImplicitClause ? ImplicitClauseLoc
2956 : RefExpr->getExprLoc();
2957 // OpenMP [2.1, C/C++]
2958 // A list item is a variable name.
2959 // OpenMP [2.9.3.3, Restrictions, p.1]
2960 // A variable that is part of another variable (as an array or
2961 // structure element) cannot appear in a private clause.
2962 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
2963 if (!DE || !isa<VarDecl>(DE->getDecl())) {
2964 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
2967 Decl *D = DE->getDecl();
2968 VarDecl *VD = cast<VarDecl>(D);
2970 QualType Type = VD->getType();
2971 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
2972 // It will be analyzed later.
2977 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
2978 // A variable that appears in a private clause must not have an incomplete
2979 // type or a reference type.
2980 if (RequireCompleteType(ELoc, Type,
2981 diag::err_omp_firstprivate_incomplete_type)) {
2984 if (Type->isReferenceType()) {
2985 if (IsImplicitClause) {
2986 Diag(ImplicitClauseLoc,
2987 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
2989 Diag(RefExpr->getExprLoc(), diag::note_used_here);
2991 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
2992 << getOpenMPClauseName(OMPC_firstprivate) << Type;
2995 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2996 Diag(VD->getLocation(),
2997 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3002 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
3003 // A variable of class type (or array thereof) that appears in a private
3004 // clause requires an accessible, unambiguous copy constructor for the
3006 Type = Context.getBaseElementType(Type);
3007 CXXRecordDecl *RD = getLangOpts().CPlusPlus
3008 ? Type.getNonReferenceType()->getAsCXXRecordDecl()
3010 // FIXME This code must be replaced by actual constructing/destructing of
3011 // the firstprivate variable.
3013 CXXConstructorDecl *CD = LookupCopyingConstructor(RD, 0);
3014 PartialDiagnostic PD =
3015 PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
3017 CheckConstructorAccess(ELoc, CD,
3018 InitializedEntity::InitializeTemporary(Type),
3019 CD->getAccess(), PD) == AR_inaccessible ||
3021 if (IsImplicitClause) {
3022 Diag(ImplicitClauseLoc,
3023 diag::err_omp_task_predetermined_firstprivate_required_method)
3025 Diag(RefExpr->getExprLoc(), diag::note_used_here);
3027 Diag(ELoc, diag::err_omp_required_method)
3028 << getOpenMPClauseName(OMPC_firstprivate) << 1;
3030 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3031 VarDecl::DeclarationOnly;
3032 Diag(VD->getLocation(),
3033 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3035 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3038 MarkFunctionReferenced(ELoc, CD);
3039 DiagnoseUseOfDecl(CD, ELoc);
3041 CXXDestructorDecl *DD = RD->getDestructor();
3043 if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
3045 if (IsImplicitClause) {
3046 Diag(ImplicitClauseLoc,
3047 diag::err_omp_task_predetermined_firstprivate_required_method)
3049 Diag(RefExpr->getExprLoc(), diag::note_used_here);
3051 Diag(ELoc, diag::err_omp_required_method)
3052 << getOpenMPClauseName(OMPC_firstprivate) << 4;
3054 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3055 VarDecl::DeclarationOnly;
3056 Diag(VD->getLocation(),
3057 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3059 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3062 MarkFunctionReferenced(ELoc, DD);
3063 DiagnoseUseOfDecl(DD, ELoc);
3067 // If an implicit firstprivate variable found it was checked already.
3068 if (!IsImplicitClause) {
3069 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
3070 Type = Type.getNonReferenceType().getCanonicalType();
3071 bool IsConstant = Type.isConstant(Context);
3072 Type = Context.getBaseElementType(Type);
3073 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
3074 // A list item that specifies a given variable may not appear in more
3075 // than one clause on the same directive, except that a variable may be
3076 // specified in both firstprivate and lastprivate clauses.
3077 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
3078 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
3079 Diag(ELoc, diag::err_omp_wrong_dsa)
3080 << getOpenMPClauseName(DVar.CKind)
3081 << getOpenMPClauseName(OMPC_firstprivate);
3082 ReportOriginalDSA(*this, DSAStack, VD, DVar);
3086 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
3088 // Variables with the predetermined data-sharing attributes may not be
3089 // listed in data-sharing attributes clauses, except for the cases
3090 // listed below. For these exceptions only, listing a predetermined
3091 // variable in a data-sharing attribute clause is allowed and overrides
3092 // the variable's predetermined data-sharing attributes.
3093 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
3094 // in a Construct, C/C++, p.2]
3095 // Variables with const-qualified type having no mutable member may be
3096 // listed in a firstprivate clause, even if they are static data members.
3097 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
3098 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
3099 Diag(ELoc, diag::err_omp_wrong_dsa)
3100 << getOpenMPClauseName(DVar.CKind)
3101 << getOpenMPClauseName(OMPC_firstprivate);
3102 ReportOriginalDSA(*this, DSAStack, VD, DVar);
3106 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
3107 // OpenMP [2.9.3.4, Restrictions, p.2]
3108 // A list item that is private within a parallel region must not appear
3109 // in a firstprivate clause on a worksharing construct if any of the
3110 // worksharing regions arising from the worksharing construct ever bind
3111 // to any of the parallel regions arising from the parallel construct.
3112 if (isOpenMPWorksharingDirective(CurrDir) &&
3113 !isOpenMPParallelDirective(CurrDir)) {
3114 DVar = DSAStack->getImplicitDSA(VD, true);
3115 if (DVar.CKind != OMPC_shared &&
3116 (isOpenMPParallelDirective(DVar.DKind) ||
3117 DVar.DKind == OMPD_unknown)) {
3118 Diag(ELoc, diag::err_omp_required_access)
3119 << getOpenMPClauseName(OMPC_firstprivate)
3120 << getOpenMPClauseName(OMPC_shared);
3121 ReportOriginalDSA(*this, DSAStack, VD, DVar);
3125 // OpenMP [2.9.3.4, Restrictions, p.3]
3126 // A list item that appears in a reduction clause of a parallel construct
3127 // must not appear in a firstprivate clause on a worksharing or task
3128 // construct if any of the worksharing or task regions arising from the
3129 // worksharing or task construct ever bind to any of the parallel regions
3130 // arising from the parallel construct.
3131 // OpenMP [2.9.3.4, Restrictions, p.4]
3132 // A list item that appears in a reduction clause in worksharing
3133 // construct must not appear in a firstprivate clause in a task construct
3134 // encountered during execution of any of the worksharing regions arising
3135 // from the worksharing construct.
3136 if (CurrDir == OMPD_task) {
3138 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
3139 [](OpenMPDirectiveKind K) -> bool {
3140 return isOpenMPParallelDirective(K) ||
3141 isOpenMPWorksharingDirective(K);
3144 if (DVar.CKind == OMPC_reduction &&
3145 (isOpenMPParallelDirective(DVar.DKind) ||
3146 isOpenMPWorksharingDirective(DVar.DKind))) {
3147 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
3148 << getOpenMPDirectiveName(DVar.DKind);
3149 ReportOriginalDSA(*this, DSAStack, VD, DVar);
3155 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
3162 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
3166 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
3167 SourceLocation StartLoc,
3168 SourceLocation LParenLoc,
3169 SourceLocation EndLoc) {
3170 SmallVector<Expr *, 8> Vars;
3171 for (auto &RefExpr : VarList) {
3172 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
3173 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3174 // It will be analyzed later.
3175 Vars.push_back(RefExpr);
3179 SourceLocation ELoc = RefExpr->getExprLoc();
3180 // OpenMP [2.1, C/C++]
3181 // A list item is a variable name.
3182 // OpenMP [2.14.3.5, Restrictions, p.1]
3183 // A variable that is part of another variable (as an array or structure
3184 // element) cannot appear in a lastprivate clause.
3185 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
3186 if (!DE || !isa<VarDecl>(DE->getDecl())) {
3187 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
3190 Decl *D = DE->getDecl();
3191 VarDecl *VD = cast<VarDecl>(D);
3193 QualType Type = VD->getType();
3194 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
3195 // It will be analyzed later.
3200 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
3201 // A variable that appears in a lastprivate clause must not have an
3202 // incomplete type or a reference type.
3203 if (RequireCompleteType(ELoc, Type,
3204 diag::err_omp_lastprivate_incomplete_type)) {
3207 if (Type->isReferenceType()) {
3208 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
3209 << getOpenMPClauseName(OMPC_lastprivate) << Type;
3211 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3212 Diag(VD->getLocation(),
3213 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3218 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3220 // Variables with the predetermined data-sharing attributes may not be
3221 // listed in data-sharing attributes clauses, except for the cases
3223 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
3224 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
3225 DVar.CKind != OMPC_firstprivate &&
3226 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3227 Diag(ELoc, diag::err_omp_wrong_dsa)
3228 << getOpenMPClauseName(DVar.CKind)
3229 << getOpenMPClauseName(OMPC_lastprivate);
3230 ReportOriginalDSA(*this, DSAStack, VD, DVar);
3234 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
3235 // OpenMP [2.14.3.5, Restrictions, p.2]
3236 // A list item that is private within a parallel region, or that appears in
3237 // the reduction clause of a parallel construct, must not appear in a
3238 // lastprivate clause on a worksharing construct if any of the corresponding
3239 // worksharing regions ever binds to any of the corresponding parallel
3241 if (isOpenMPWorksharingDirective(CurrDir) &&
3242 !isOpenMPParallelDirective(CurrDir)) {
3243 DVar = DSAStack->getImplicitDSA(VD, true);
3244 if (DVar.CKind != OMPC_shared) {
3245 Diag(ELoc, diag::err_omp_required_access)
3246 << getOpenMPClauseName(OMPC_lastprivate)
3247 << getOpenMPClauseName(OMPC_shared);
3248 ReportOriginalDSA(*this, DSAStack, VD, DVar);
3252 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
3253 // A variable of class type (or array thereof) that appears in a
3254 // lastprivate clause requires an accessible, unambiguous default
3255 // constructor for the class type, unless the list item is also specified
3256 // in a firstprivate clause.
3257 // A variable of class type (or array thereof) that appears in a
3258 // lastprivate clause requires an accessible, unambiguous copy assignment
3259 // operator for the class type.
3260 while (Type.getNonReferenceType()->isArrayType())
3261 Type = cast<ArrayType>(Type.getNonReferenceType().getTypePtr())
3263 CXXRecordDecl *RD = getLangOpts().CPlusPlus
3264 ? Type.getNonReferenceType()->getAsCXXRecordDecl()
3266 // FIXME This code must be replaced by actual copying and destructing of the
3267 // lastprivate variable.
3269 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
3270 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
3272 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
3274 Diag(ELoc, diag::err_omp_required_method)
3275 << getOpenMPClauseName(OMPC_lastprivate) << 2;
3276 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3277 VarDecl::DeclarationOnly;
3278 Diag(VD->getLocation(),
3279 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3281 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3284 MarkFunctionReferenced(ELoc, MD);
3285 DiagnoseUseOfDecl(MD, ELoc);
3288 CXXDestructorDecl *DD = RD->getDestructor();
3290 PartialDiagnostic PD =
3291 PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
3292 if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
3294 Diag(ELoc, diag::err_omp_required_method)
3295 << getOpenMPClauseName(OMPC_lastprivate) << 4;
3296 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3297 VarDecl::DeclarationOnly;
3298 Diag(VD->getLocation(),
3299 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3301 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3304 MarkFunctionReferenced(ELoc, DD);
3305 DiagnoseUseOfDecl(DD, ELoc);
3309 if (DVar.CKind != OMPC_firstprivate)
3310 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
3317 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
3321 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
3322 SourceLocation StartLoc,
3323 SourceLocation LParenLoc,
3324 SourceLocation EndLoc) {
3325 SmallVector<Expr *, 8> Vars;
3326 for (auto &RefExpr : VarList) {
3327 assert(RefExpr && "NULL expr in OpenMP shared clause.");
3328 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3329 // It will be analyzed later.
3330 Vars.push_back(RefExpr);
3334 SourceLocation ELoc = RefExpr->getExprLoc();
3335 // OpenMP [2.1, C/C++]
3336 // A list item is a variable name.
3337 // OpenMP [2.14.3.2, Restrictions, p.1]
3338 // A variable that is part of another variable (as an array or structure
3339 // element) cannot appear in a shared unless it is a static data member
3341 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
3342 if (!DE || !isa<VarDecl>(DE->getDecl())) {
3343 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
3346 Decl *D = DE->getDecl();
3347 VarDecl *VD = cast<VarDecl>(D);
3349 QualType Type = VD->getType();
3350 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
3351 // It will be analyzed later.
3356 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
3358 // Variables with the predetermined data-sharing attributes may not be
3359 // listed in data-sharing attributes clauses, except for the cases
3360 // listed below. For these exceptions only, listing a predetermined
3361 // variable in a data-sharing attribute clause is allowed and overrides
3362 // the variable's predetermined data-sharing attributes.
3363 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
3364 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
3366 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
3367 << getOpenMPClauseName(OMPC_shared);
3368 ReportOriginalDSA(*this, DSAStack, VD, DVar);
3372 DSAStack->addDSA(VD, DE, OMPC_shared);
3379 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
3383 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
3387 bool VisitDeclRefExpr(DeclRefExpr *E) {
3388 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
3389 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
3390 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
3392 if (DVar.CKind != OMPC_unknown)
3394 DSAStackTy::DSAVarData DVarPrivate =
3395 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
3396 if (DVarPrivate.CKind != OMPC_unknown)
3402 bool VisitStmt(Stmt *S) {
3403 for (auto Child : S->children()) {
3404 if (Child && Visit(Child))
3409 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
3413 OMPClause *Sema::ActOnOpenMPReductionClause(
3414 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
3415 SourceLocation ColonLoc, SourceLocation EndLoc,
3416 CXXScopeSpec &ReductionIdScopeSpec,
3417 const DeclarationNameInfo &ReductionId) {
3418 // TODO: Allow scope specification search when 'declare reduction' is
3420 assert(ReductionIdScopeSpec.isEmpty() &&
3421 "No support for scoped reduction identifiers yet.");
3423 auto DN = ReductionId.getName();
3424 auto OOK = DN.getCXXOverloadedOperator();
3425 BinaryOperatorKind BOK = BO_Comma;
3427 // OpenMP [2.14.3.6, reduction clause]
3429 // reduction-identifier is either an identifier or one of the following
3430 // operators: +, -, *, &, |, ^, && and ||
3432 // reduction-identifier is either an id-expression or one of the following
3433 // operators: +, -, *, &, |, ^, && and ||
3434 // FIXME: Only 'min' and 'max' identifiers are supported for now.
3459 if (auto II = DN.getAsIdentifierInfo()) {
3460 if (II->isStr("max"))
3462 else if (II->isStr("min"))
3467 SourceRange ReductionIdRange;
3468 if (ReductionIdScopeSpec.isValid()) {
3469 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
3471 ReductionIdRange.setEnd(ReductionId.getEndLoc());
3472 if (BOK == BO_Comma) {
3473 // Not allowed reduction identifier is found.
3474 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
3475 << ReductionIdRange;
3479 SmallVector<Expr *, 8> Vars;
3480 for (auto RefExpr : VarList) {
3481 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
3482 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3483 // It will be analyzed later.
3484 Vars.push_back(RefExpr);
3488 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
3489 RefExpr->isInstantiationDependent() ||
3490 RefExpr->containsUnexpandedParameterPack()) {
3491 // It will be analyzed later.
3492 Vars.push_back(RefExpr);
3496 auto ELoc = RefExpr->getExprLoc();
3497 auto ERange = RefExpr->getSourceRange();
3498 // OpenMP [2.1, C/C++]
3499 // A list item is a variable or array section, subject to the restrictions
3500 // specified in Section 2.4 on page 42 and in each of the sections
3501 // describing clauses and directives for which a list appears.
3502 // OpenMP [2.14.3.3, Restrictions, p.1]
3503 // A variable that is part of another variable (as an array or
3504 // structure element) cannot appear in a private clause.
3505 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
3506 if (!DE || !isa<VarDecl>(DE->getDecl())) {
3507 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
3510 auto D = DE->getDecl();
3511 auto VD = cast<VarDecl>(D);
3512 auto Type = VD->getType();
3513 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
3514 // A variable that appears in a private clause must not have an incomplete
3515 // type or a reference type.
3516 if (RequireCompleteType(ELoc, Type,
3517 diag::err_omp_reduction_incomplete_type))
3519 // OpenMP [2.14.3.6, reduction clause, Restrictions]
3520 // Arrays may not appear in a reduction clause.
3521 if (Type.getNonReferenceType()->isArrayType()) {
3522 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
3524 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3525 Diag(VD->getLocation(),
3526 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3530 // OpenMP [2.14.3.6, reduction clause, Restrictions]
3531 // A list item that appears in a reduction clause must not be
3533 if (Type.getNonReferenceType().isConstant(Context)) {
3534 Diag(ELoc, diag::err_omp_const_variable)
3535 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
3537 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3538 Diag(VD->getLocation(),
3539 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3543 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
3544 // If a list-item is a reference type then it must bind to the same object
3545 // for all threads of the team.
3546 VarDecl *VDDef = VD->getDefinition();
3547 if (Type->isReferenceType() && VDDef) {
3548 DSARefChecker Check(DSAStack);
3549 if (Check.Visit(VDDef->getInit())) {
3550 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
3551 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
3555 // OpenMP [2.14.3.6, reduction clause, Restrictions]
3556 // The type of a list item that appears in a reduction clause must be valid
3557 // for the reduction-identifier. For a max or min reduction in C, the type
3558 // of the list item must be an allowed arithmetic data type: char, int,
3559 // float, double, or _Bool, possibly modified with long, short, signed, or
3560 // unsigned. For a max or min reduction in C++, the type of the list item
3561 // must be an allowed arithmetic data type: char, wchar_t, int, float,
3562 // double, or bool, possibly modified with long, short, signed, or unsigned.
3563 if ((BOK == BO_GT || BOK == BO_LT) &&
3564 !(Type->isScalarType() ||
3565 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
3566 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
3567 << getLangOpts().CPlusPlus;
3569 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3570 Diag(VD->getLocation(),
3571 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3575 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
3576 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
3577 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
3579 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3580 Diag(VD->getLocation(),
3581 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3585 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
3586 getDiagnostics().setSuppressAllDiagnostics(true);
3587 ExprResult ReductionOp =
3588 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
3590 getDiagnostics().setSuppressAllDiagnostics(Suppress);
3591 if (ReductionOp.isInvalid()) {
3592 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
3593 << ReductionIdRange;
3595 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3596 Diag(VD->getLocation(),
3597 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3602 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3604 // Variables with the predetermined data-sharing attributes may not be
3605 // listed in data-sharing attributes clauses, except for the cases
3606 // listed below. For these exceptions only, listing a predetermined
3607 // variable in a data-sharing attribute clause is allowed and overrides
3608 // the variable's predetermined data-sharing attributes.
3609 // OpenMP [2.14.3.6, Restrictions, p.3]
3610 // Any number of reduction clauses can be specified on the directive,
3611 // but a list item can appear only once in the reduction clauses for that
3613 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
3614 if (DVar.CKind == OMPC_reduction) {
3615 Diag(ELoc, diag::err_omp_once_referenced)
3616 << getOpenMPClauseName(OMPC_reduction);
3618 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
3620 } else if (DVar.CKind != OMPC_unknown) {
3621 Diag(ELoc, diag::err_omp_wrong_dsa)
3622 << getOpenMPClauseName(DVar.CKind)
3623 << getOpenMPClauseName(OMPC_reduction);
3624 ReportOriginalDSA(*this, DSAStack, VD, DVar);
3628 // OpenMP [2.14.3.6, Restrictions, p.1]
3629 // A list item that appears in a reduction clause of a worksharing
3630 // construct must be shared in the parallel regions to which any of the
3631 // worksharing regions arising from the worksharing construct bind.
3632 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
3633 if (isOpenMPWorksharingDirective(CurrDir) &&
3634 !isOpenMPParallelDirective(CurrDir)) {
3635 DVar = DSAStack->getImplicitDSA(VD, true);
3636 if (DVar.CKind != OMPC_shared) {
3637 Diag(ELoc, diag::err_omp_required_access)
3638 << getOpenMPClauseName(OMPC_reduction)
3639 << getOpenMPClauseName(OMPC_shared);
3640 ReportOriginalDSA(*this, DSAStack, VD, DVar);
3645 CXXRecordDecl *RD = getLangOpts().CPlusPlus
3646 ? Type.getNonReferenceType()->getAsCXXRecordDecl()
3648 // FIXME This code must be replaced by actual constructing/destructing of
3649 // the reduction variable.
3651 CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
3652 PartialDiagnostic PD =
3653 PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
3655 CheckConstructorAccess(ELoc, CD,
3656 InitializedEntity::InitializeTemporary(Type),
3657 CD->getAccess(), PD) == AR_inaccessible ||
3659 Diag(ELoc, diag::err_omp_required_method)
3660 << getOpenMPClauseName(OMPC_reduction) << 0;
3661 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3662 VarDecl::DeclarationOnly;
3663 Diag(VD->getLocation(),
3664 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3666 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3669 MarkFunctionReferenced(ELoc, CD);
3670 DiagnoseUseOfDecl(CD, ELoc);
3672 CXXDestructorDecl *DD = RD->getDestructor();
3674 if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
3676 Diag(ELoc, diag::err_omp_required_method)
3677 << getOpenMPClauseName(OMPC_reduction) << 4;
3678 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3679 VarDecl::DeclarationOnly;
3680 Diag(VD->getLocation(),
3681 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3683 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3686 MarkFunctionReferenced(ELoc, DD);
3687 DiagnoseUseOfDecl(DD, ELoc);
3691 DSAStack->addDSA(VD, DE, OMPC_reduction);
3698 return OMPReductionClause::Create(
3699 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
3700 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId);
3703 OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
3704 SourceLocation StartLoc,
3705 SourceLocation LParenLoc,
3706 SourceLocation ColonLoc,
3707 SourceLocation EndLoc) {
3708 SmallVector<Expr *, 8> Vars;
3709 for (auto &RefExpr : VarList) {
3710 assert(RefExpr && "NULL expr in OpenMP linear clause.");
3711 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3712 // It will be analyzed later.
3713 Vars.push_back(RefExpr);
3717 // OpenMP [2.14.3.7, linear clause]
3718 // A list item that appears in a linear clause is subject to the private
3719 // clause semantics described in Section 2.14.3.3 on page 159 except as
3720 // noted. In addition, the value of the new list item on each iteration
3721 // of the associated loop(s) corresponds to the value of the original
3722 // list item before entering the construct plus the logical number of
3723 // the iteration times linear-step.
3725 SourceLocation ELoc = RefExpr->getExprLoc();
3726 // OpenMP [2.1, C/C++]
3727 // A list item is a variable name.
3728 // OpenMP [2.14.3.3, Restrictions, p.1]
3729 // A variable that is part of another variable (as an array or
3730 // structure element) cannot appear in a private clause.
3731 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
3732 if (!DE || !isa<VarDecl>(DE->getDecl())) {
3733 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
3737 VarDecl *VD = cast<VarDecl>(DE->getDecl());
3739 // OpenMP [2.14.3.7, linear clause]
3740 // A list-item cannot appear in more than one linear clause.
3741 // A list-item that appears in a linear clause cannot appear in any
3742 // other data-sharing attribute clause.
3743 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
3745 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
3746 << getOpenMPClauseName(OMPC_linear);
3747 ReportOriginalDSA(*this, DSAStack, VD, DVar);
3751 QualType QType = VD->getType();
3752 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
3753 // It will be analyzed later.
3758 // A variable must not have an incomplete type or a reference type.
3759 if (RequireCompleteType(ELoc, QType,
3760 diag::err_omp_linear_incomplete_type)) {
3763 if (QType->isReferenceType()) {
3764 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
3765 << getOpenMPClauseName(OMPC_linear) << QType;
3767 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3768 Diag(VD->getLocation(),
3769 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3774 // A list item must not be const-qualified.
3775 if (QType.isConstant(Context)) {
3776 Diag(ELoc, diag::err_omp_const_variable)
3777 << getOpenMPClauseName(OMPC_linear);
3779 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3780 Diag(VD->getLocation(),
3781 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3786 // A list item must be of integral or pointer type.
3787 QType = QType.getUnqualifiedType().getCanonicalType();
3788 const Type *Ty = QType.getTypePtrOrNull();
3789 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
3790 !Ty->isPointerType())) {
3791 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
3793 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3794 Diag(VD->getLocation(),
3795 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3800 DSAStack->addDSA(VD, DE, OMPC_linear);
3807 Expr *StepExpr = Step;
3808 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3809 !Step->isInstantiationDependent() &&
3810 !Step->containsUnexpandedParameterPack()) {
3811 SourceLocation StepLoc = Step->getLocStart();
3812 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
3813 if (Val.isInvalid())
3815 StepExpr = Val.get();
3817 // Warn about zero linear step (it would be probably better specified as
3818 // making corresponding variables 'const').
3819 llvm::APSInt Result;
3820 if (StepExpr->isIntegerConstantExpr(Result, Context) &&
3821 !Result.isNegative() && !Result.isStrictlyPositive())
3822 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
3823 << (Vars.size() > 1);
3826 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
3830 OMPClause *Sema::ActOnOpenMPAlignedClause(
3831 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
3832 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
3834 SmallVector<Expr *, 8> Vars;
3835 for (auto &RefExpr : VarList) {
3836 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
3837 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3838 // It will be analyzed later.
3839 Vars.push_back(RefExpr);
3843 SourceLocation ELoc = RefExpr->getExprLoc();
3844 // OpenMP [2.1, C/C++]
3845 // A list item is a variable name.
3846 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
3847 if (!DE || !isa<VarDecl>(DE->getDecl())) {
3848 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
3852 VarDecl *VD = cast<VarDecl>(DE->getDecl());
3854 // OpenMP [2.8.1, simd construct, Restrictions]
3855 // The type of list items appearing in the aligned clause must be
3856 // array, pointer, reference to array, or reference to pointer.
3857 QualType QType = DE->getType()
3858 .getNonReferenceType()
3859 .getUnqualifiedType()
3860 .getCanonicalType();
3861 const Type *Ty = QType.getTypePtrOrNull();
3862 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
3863 !Ty->isPointerType())) {
3864 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
3865 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
3867 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3868 Diag(VD->getLocation(),
3869 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3874 // OpenMP [2.8.1, simd construct, Restrictions]
3875 // A list-item cannot appear in more than one aligned clause.
3876 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
3877 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
3878 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
3879 << getOpenMPClauseName(OMPC_aligned);
3886 // OpenMP [2.8.1, simd construct, Description]
3887 // The parameter of the aligned clause, alignment, must be a constant
3888 // positive integer expression.
3889 // If no optional parameter is specified, implementation-defined default
3890 // alignments for SIMD instructions on the target platforms are assumed.
3891 if (Alignment != nullptr) {
3892 ExprResult AlignResult =
3893 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
3894 if (AlignResult.isInvalid())
3896 Alignment = AlignResult.get();
3901 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
3902 EndLoc, Vars, Alignment);
3905 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
3906 SourceLocation StartLoc,
3907 SourceLocation LParenLoc,
3908 SourceLocation EndLoc) {
3909 SmallVector<Expr *, 8> Vars;
3910 for (auto &RefExpr : VarList) {
3911 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
3912 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3913 // It will be analyzed later.
3914 Vars.push_back(RefExpr);
3918 SourceLocation ELoc = RefExpr->getExprLoc();
3919 // OpenMP [2.1, C/C++]
3920 // A list item is a variable name.
3921 // OpenMP [2.14.4.1, Restrictions, p.1]
3922 // A list item that appears in a copyin clause must be threadprivate.
3923 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
3924 if (!DE || !isa<VarDecl>(DE->getDecl())) {
3925 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
3929 Decl *D = DE->getDecl();
3930 VarDecl *VD = cast<VarDecl>(D);
3932 QualType Type = VD->getType();
3933 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
3934 // It will be analyzed later.
3939 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
3940 // A list item that appears in a copyin clause must be threadprivate.
3941 if (!DSAStack->isThreadPrivate(VD)) {
3942 Diag(ELoc, diag::err_omp_required_access)
3943 << getOpenMPClauseName(OMPC_copyin)
3944 << getOpenMPDirectiveName(OMPD_threadprivate);
3948 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
3949 // A variable of class type (or array thereof) that appears in a
3950 // copyin clause requires an accessible, unambiguous copy assignment
3951 // operator for the class type.
3952 Type = Context.getBaseElementType(Type);
3954 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
3955 // FIXME This code must be replaced by actual assignment of the
3956 // threadprivate variable.
3958 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
3959 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
3961 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
3963 Diag(ELoc, diag::err_omp_required_method)
3964 << getOpenMPClauseName(OMPC_copyin) << 2;
3965 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3966 VarDecl::DeclarationOnly;
3967 Diag(VD->getLocation(),
3968 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3970 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3973 MarkFunctionReferenced(ELoc, MD);
3974 DiagnoseUseOfDecl(MD, ELoc);
3978 DSAStack->addDSA(VD, DE, OMPC_copyin);
3985 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
3988 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
3989 SourceLocation StartLoc,
3990 SourceLocation LParenLoc,
3991 SourceLocation EndLoc) {
3992 SmallVector<Expr *, 8> Vars;
3993 for (auto &RefExpr : VarList) {
3994 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
3995 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3996 // It will be analyzed later.
3997 Vars.push_back(RefExpr);
4001 SourceLocation ELoc = RefExpr->getExprLoc();
4002 // OpenMP [2.1, C/C++]
4003 // A list item is a variable name.
4004 // OpenMP [2.14.4.1, Restrictions, p.1]
4005 // A list item that appears in a copyin clause must be threadprivate.
4006 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
4007 if (!DE || !isa<VarDecl>(DE->getDecl())) {
4008 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4012 Decl *D = DE->getDecl();
4013 VarDecl *VD = cast<VarDecl>(D);
4015 QualType Type = VD->getType();
4016 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4017 // It will be analyzed later.
4022 // OpenMP [2.14.4.2, Restrictions, p.2]
4023 // A list item that appears in a copyprivate clause may not appear in a
4024 // private or firstprivate clause on the single construct.
4025 if (!DSAStack->isThreadPrivate(VD)) {
4026 auto DVar = DSAStack->getTopDSA(VD, false);
4027 if (DVar.CKind != OMPC_copyprivate && DVar.CKind != OMPC_unknown &&
4028 !(DVar.CKind == OMPC_private && !DVar.RefExpr)) {
4029 Diag(ELoc, diag::err_omp_wrong_dsa)
4030 << getOpenMPClauseName(DVar.CKind)
4031 << getOpenMPClauseName(OMPC_copyprivate);
4032 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4036 // OpenMP [2.11.4.2, Restrictions, p.1]
4037 // All list items that appear in a copyprivate clause must be either
4038 // threadprivate or private in the enclosing context.
4039 if (DVar.CKind == OMPC_unknown) {
4040 DVar = DSAStack->getImplicitDSA(VD, false);
4041 if (DVar.CKind == OMPC_shared) {
4042 Diag(ELoc, diag::err_omp_required_access)
4043 << getOpenMPClauseName(OMPC_copyprivate)
4044 << "threadprivate or private in the enclosing context";
4045 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4051 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
4052 // A variable of class type (or array thereof) that appears in a
4053 // copyin clause requires an accessible, unambiguous copy assignment
4054 // operator for the class type.
4055 Type = Context.getBaseElementType(Type);
4057 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
4058 // FIXME This code must be replaced by actual assignment of the
4059 // threadprivate variable.
4061 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
4062 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
4064 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
4066 Diag(ELoc, diag::err_omp_required_method)
4067 << getOpenMPClauseName(OMPC_copyprivate) << 2;
4068 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
4069 VarDecl::DeclarationOnly;
4070 Diag(VD->getLocation(),
4071 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4073 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
4076 MarkFunctionReferenced(ELoc, MD);
4077 DiagnoseUseOfDecl(MD, ELoc);
4081 // No need to mark vars as copyprivate, they are already threadprivate or
4082 // implicitly private.
4089 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
4092 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
4093 SourceLocation StartLoc,
4094 SourceLocation LParenLoc,
4095 SourceLocation EndLoc) {
4096 if (VarList.empty())
4099 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);