blob: 81d04a8c2f6d6d1acd7b433e36613aea0f838a37 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// \brief This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000011/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000012///
13//===----------------------------------------------------------------------===//
14
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000016#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000017#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000018#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/StmtCXX.h"
21#include "clang/AST/StmtOpenMP.h"
22#include "clang/AST/StmtVisitor.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023#include "clang/Basic/OpenMPKinds.h"
24#include "clang/Lex/Preprocessor.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000025#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000026#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000027#include "clang/Sema/Scope.h"
28#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000029#include "clang/Sema/SemaInternal.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000030using namespace clang;
31
Alexey Bataev758e55e2013-09-06 18:03:48 +000032//===----------------------------------------------------------------------===//
33// Stack of data-sharing attributes for variables
34//===----------------------------------------------------------------------===//
35
36namespace {
37/// \brief Default data sharing attributes, which can be applied to directive.
38enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000039 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
40 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
41 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000042};
Alexey Bataev7ff55242014-06-19 09:13:45 +000043
Alexey Bataevf29276e2014-06-18 04:14:57 +000044template <class T> struct MatchesAny {
Alexey Bataev23b69422014-06-18 07:08:49 +000045 explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
Alexey Bataevf29276e2014-06-18 04:14:57 +000046 bool operator()(T Kind) {
47 for (auto KindEl : Arr)
48 if (KindEl == Kind)
49 return true;
50 return false;
51 }
52
53private:
54 ArrayRef<T> Arr;
55};
Alexey Bataev23b69422014-06-18 07:08:49 +000056struct MatchesAlways {
Alexey Bataevf29276e2014-06-18 04:14:57 +000057 MatchesAlways() {}
Alexey Bataev7ff55242014-06-19 09:13:45 +000058 template <class T> bool operator()(T) { return true; }
Alexey Bataevf29276e2014-06-18 04:14:57 +000059};
60
61typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
62typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
Alexey Bataev758e55e2013-09-06 18:03:48 +000063
64/// \brief Stack for tracking declarations used in OpenMP directives and
65/// clauses and their data-sharing attributes.
66class DSAStackTy {
67public:
68 struct DSAVarData {
69 OpenMPDirectiveKind DKind;
70 OpenMPClauseKind CKind;
71 DeclRefExpr *RefExpr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000072 SourceLocation ImplicitDSALoc;
73 DSAVarData()
74 : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
75 ImplicitDSALoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000076 };
Alexey Bataeved09d242014-05-28 05:53:51 +000077
Alexey Bataev758e55e2013-09-06 18:03:48 +000078private:
79 struct DSAInfo {
80 OpenMPClauseKind Attributes;
81 DeclRefExpr *RefExpr;
82 };
83 typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000084 typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000085
86 struct SharingMapTy {
87 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000088 AlignedMapTy AlignedMap;
Alexey Bataev758e55e2013-09-06 18:03:48 +000089 DefaultDataSharingAttributes DefaultAttr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000090 SourceLocation DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +000091 OpenMPDirectiveKind Directive;
92 DeclarationNameInfo DirectiveName;
93 Scope *CurScope;
Alexey Bataevbae9a792014-06-27 10:37:06 +000094 SourceLocation ConstructLoc;
Alexey Bataev9fb6e642014-07-22 06:45:04 +000095 bool OrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +000096 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +000097 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +000098 Scope *CurScope, SourceLocation Loc)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000099 : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000100 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
Alexey Bataev13314bf2014-10-09 04:18:56 +0000101 ConstructLoc(Loc), OrderedRegion(false), InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000102 SharingMapTy()
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000103 : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000104 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
Alexey Bataev13314bf2014-10-09 04:18:56 +0000105 ConstructLoc(), OrderedRegion(false), InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000106 };
107
108 typedef SmallVector<SharingMapTy, 64> StackTy;
109
110 /// \brief Stack of used declaration and their data-sharing attributes.
111 StackTy Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000112 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000113
114 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
115
116 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000117
118 /// \brief Checks if the variable is a local for OpenMP region.
119 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000120
Alexey Bataev758e55e2013-09-06 18:03:48 +0000121public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000122 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000123
124 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000125 Scope *CurScope, SourceLocation Loc) {
126 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
127 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000128 }
129
130 void pop() {
131 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
132 Stack.pop_back();
133 }
134
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000135 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000136 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000137 /// for diagnostics.
138 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
139
Alexey Bataev758e55e2013-09-06 18:03:48 +0000140 /// \brief Adds explicit data sharing attribute to the specified declaration.
141 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
142
Alexey Bataev758e55e2013-09-06 18:03:48 +0000143 /// \brief Returns data sharing attributes from top of the stack for the
144 /// specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000145 DSAVarData getTopDSA(VarDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000146 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000147 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000148 /// \brief Checks if the specified variables has data-sharing attributes which
149 /// match specified \a CPred predicate in any directive which matches \a DPred
150 /// predicate.
151 template <class ClausesPredicate, class DirectivesPredicate>
152 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000153 DirectivesPredicate DPred, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000154 /// \brief Checks if the specified variables has data-sharing attributes which
155 /// match specified \a CPred predicate in any innermost directive which
156 /// matches \a DPred predicate.
157 template <class ClausesPredicate, class DirectivesPredicate>
158 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000159 DirectivesPredicate DPred,
160 bool FromParent);
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000161 /// \brief Finds a directive which matches specified \a DPred predicate.
162 template <class NamedDirectivesPredicate>
163 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000164
Alexey Bataev758e55e2013-09-06 18:03:48 +0000165 /// \brief Returns currently analyzed directive.
166 OpenMPDirectiveKind getCurrentDirective() const {
167 return Stack.back().Directive;
168 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000169 /// \brief Returns parent directive.
170 OpenMPDirectiveKind getParentDirective() const {
171 if (Stack.size() > 2)
172 return Stack[Stack.size() - 2].Directive;
173 return OMPD_unknown;
174 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000175
176 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000177 void setDefaultDSANone(SourceLocation Loc) {
178 Stack.back().DefaultAttr = DSA_none;
179 Stack.back().DefaultAttrLoc = Loc;
180 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000181 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000182 void setDefaultDSAShared(SourceLocation Loc) {
183 Stack.back().DefaultAttr = DSA_shared;
184 Stack.back().DefaultAttrLoc = Loc;
185 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000186
187 DefaultDataSharingAttributes getDefaultDSA() const {
188 return Stack.back().DefaultAttr;
189 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000190 SourceLocation getDefaultDSALocation() const {
191 return Stack.back().DefaultAttrLoc;
192 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000193
Alexey Bataevf29276e2014-06-18 04:14:57 +0000194 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000195 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000196 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000197 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000198 }
199
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000200 /// \brief Marks current region as ordered (it has an 'ordered' clause).
201 void setOrderedRegion(bool IsOrdered = true) {
202 Stack.back().OrderedRegion = IsOrdered;
203 }
204 /// \brief Returns true, if parent region is ordered (has associated
205 /// 'ordered' clause), false - otherwise.
206 bool isParentOrderedRegion() const {
207 if (Stack.size() > 2)
208 return Stack[Stack.size() - 2].OrderedRegion;
209 return false;
210 }
211
Alexey Bataev13314bf2014-10-09 04:18:56 +0000212 /// \brief Marks current target region as one with closely nested teams
213 /// region.
214 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
215 if (Stack.size() > 2)
216 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
217 }
218 /// \brief Returns true, if current region has closely nested teams region.
219 bool hasInnerTeamsRegion() const {
220 return getInnerTeamsRegionLoc().isValid();
221 }
222 /// \brief Returns location of the nested teams region (if any).
223 SourceLocation getInnerTeamsRegionLoc() const {
224 if (Stack.size() > 1)
225 return Stack.back().InnerTeamsRegionLoc;
226 return SourceLocation();
227 }
228
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000229 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000230 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000231 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000232};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000233bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
234 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
Alexey Bataev13314bf2014-10-09 04:18:56 +0000235 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000236}
Alexey Bataeved09d242014-05-28 05:53:51 +0000237} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000238
239DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
240 VarDecl *D) {
241 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000242 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000243 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
244 // in a region but not in construct]
245 // File-scope or namespace-scope variables referenced in called routines
246 // in the region are shared unless they appear in a threadprivate
247 // directive.
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000248 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000249 DVar.CKind = OMPC_shared;
250
251 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
252 // in a region but not in construct]
253 // Variables with static storage duration that are declared in called
254 // routines in the region are shared.
255 if (D->hasGlobalStorage())
256 DVar.CKind = OMPC_shared;
257
Alexey Bataev758e55e2013-09-06 18:03:48 +0000258 return DVar;
259 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000260
Alexey Bataev758e55e2013-09-06 18:03:48 +0000261 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000262 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
263 // in a Construct, C/C++, predetermined, p.1]
264 // Variables with automatic storage duration that are declared in a scope
265 // inside the construct are private.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000266 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
267 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
268 DVar.CKind = OMPC_private;
269 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000270 }
271
Alexey Bataev758e55e2013-09-06 18:03:48 +0000272 // Explicitly specified attributes and local variables with predetermined
273 // attributes.
274 if (Iter->SharingMap.count(D)) {
275 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
276 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000277 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000278 return DVar;
279 }
280
281 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
282 // in a Construct, C/C++, implicitly determined, p.1]
283 // In a parallel or task construct, the data-sharing attributes of these
284 // variables are determined by the default clause, if present.
285 switch (Iter->DefaultAttr) {
286 case DSA_shared:
287 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000288 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000289 return DVar;
290 case DSA_none:
291 return DVar;
292 case DSA_unspecified:
293 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
294 // in a Construct, implicitly determined, p.2]
295 // In a parallel construct, if no default clause is present, these
296 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000297 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000298 if (isOpenMPParallelDirective(DVar.DKind) ||
299 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000300 DVar.CKind = OMPC_shared;
301 return DVar;
302 }
303
304 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
305 // in a Construct, implicitly determined, p.4]
306 // In a task construct, if no default clause is present, a variable that in
307 // the enclosing context is determined to be shared by all implicit tasks
308 // bound to the current team is shared.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000309 if (DVar.DKind == OMPD_task) {
310 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000311 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000312 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000313 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
314 // Referenced
Alexey Bataev758e55e2013-09-06 18:03:48 +0000315 // in a Construct, implicitly determined, p.6]
316 // In a task construct, if no default clause is present, a variable
317 // whose data-sharing attribute is not determined by the rules above is
318 // firstprivate.
319 DVarTemp = getDSA(I, D);
320 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000321 DVar.RefExpr = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000322 DVar.DKind = OMPD_task;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000323 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000324 return DVar;
325 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000326 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000327 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000328 }
329 DVar.DKind = OMPD_task;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000330 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000331 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000332 return DVar;
333 }
334 }
335 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
336 // in a Construct, implicitly determined, p.3]
337 // For constructs other than task, if no default clause is present, these
338 // variables inherit their data-sharing attributes from the enclosing
339 // context.
Benjamin Kramer167e9992014-03-02 12:20:24 +0000340 return getDSA(std::next(Iter), D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000341}
342
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000343DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
344 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
345 auto It = Stack.back().AlignedMap.find(D);
346 if (It == Stack.back().AlignedMap.end()) {
347 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
348 Stack.back().AlignedMap[D] = NewDE;
349 return nullptr;
350 } else {
351 assert(It->second && "Unexpected nullptr expr in the aligned map");
352 return It->second;
353 }
354 return nullptr;
355}
356
Alexey Bataev758e55e2013-09-06 18:03:48 +0000357void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
358 if (A == OMPC_threadprivate) {
359 Stack[0].SharingMap[D].Attributes = A;
360 Stack[0].SharingMap[D].RefExpr = E;
361 } else {
362 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
363 Stack.back().SharingMap[D].Attributes = A;
364 Stack.back().SharingMap[D].RefExpr = E;
365 }
366}
367
Alexey Bataeved09d242014-05-28 05:53:51 +0000368bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000369 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000370 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000371 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000372 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000373 ++I;
374 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000375 if (I == E)
376 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000377 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000378 Scope *CurScope = getCurScope();
379 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000380 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000381 }
382 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000383 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000384 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000385}
386
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000387DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000388 DSAVarData DVar;
389
390 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
391 // in a Construct, C/C++, predetermined, p.1]
392 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev26a39242015-01-13 03:35:30 +0000393 if (D->getTLSKind() != VarDecl::TLS_None ||
394 D->getStorageClass() == SC_Register) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000395 DVar.CKind = OMPC_threadprivate;
396 return DVar;
397 }
398 if (Stack[0].SharingMap.count(D)) {
399 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
400 DVar.CKind = OMPC_threadprivate;
401 return DVar;
402 }
403
404 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
405 // in a Construct, C/C++, predetermined, p.1]
406 // Variables with automatic storage duration that are declared in a scope
407 // inside the construct are private.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000408 OpenMPDirectiveKind Kind =
409 FromParent ? getParentDirective() : getCurrentDirective();
410 auto StartI = std::next(Stack.rbegin());
411 auto EndI = std::prev(Stack.rend());
412 if (FromParent && StartI != EndI) {
413 StartI = std::next(StartI);
414 }
415 if (!isParallelOrTaskRegion(Kind)) {
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000416 if (isOpenMPLocal(D, StartI) &&
417 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
418 D->getStorageClass() == SC_None)) ||
419 isa<ParmVarDecl>(D))) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000420 DVar.CKind = OMPC_private;
421 return DVar;
Alexander Musman8dba6642014-04-22 13:09:42 +0000422 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000423
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000424 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
425 // in a Construct, C/C++, predetermined, p.4]
426 // Static data members are shared.
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000427 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
428 // in a Construct, C/C++, predetermined, p.7]
429 // Variables with static storage duration that are declared in a scope
430 // inside the construct are shared.
Alexey Bataev42971a32015-01-20 07:03:46 +0000431 if (D->isStaticDataMember() || D->isStaticLocal()) {
432 DSAVarData DVarTemp =
433 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
434 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
435 return DVar;
436
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000437 DVar.CKind = OMPC_shared;
438 return DVar;
439 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000440 }
441
442 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataev7ff55242014-06-19 09:13:45 +0000443 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
Alexey Bataev758e55e2013-09-06 18:03:48 +0000444 while (Type->isArrayType()) {
445 QualType ElemType = cast<ArrayType>(Type.getTypePtr())->getElementType();
446 Type = ElemType.getNonReferenceType().getCanonicalType();
447 }
448 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
449 // in a Construct, C/C++, predetermined, p.6]
450 // Variables with const qualified type having no mutable member are
451 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000452 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000453 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000454 if (IsConstant &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000455 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000456 // Variables with const-qualified type having no mutable member may be
457 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000458 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
459 MatchesAlways(), FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000460 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
461 return DVar;
462
Alexey Bataev758e55e2013-09-06 18:03:48 +0000463 DVar.CKind = OMPC_shared;
464 return DVar;
465 }
466
Alexey Bataev758e55e2013-09-06 18:03:48 +0000467 // Explicitly specified attributes and local variables with predetermined
468 // attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000469 auto I = std::prev(StartI);
470 if (I->SharingMap.count(D)) {
471 DVar.RefExpr = I->SharingMap[D].RefExpr;
472 DVar.CKind = I->SharingMap[D].Attributes;
473 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000474 }
475
476 return DVar;
477}
478
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000479DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
480 auto StartI = Stack.rbegin();
481 auto EndI = std::prev(Stack.rend());
482 if (FromParent && StartI != EndI) {
483 StartI = std::next(StartI);
484 }
485 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000486}
487
Alexey Bataevf29276e2014-06-18 04:14:57 +0000488template <class ClausesPredicate, class DirectivesPredicate>
489DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000490 DirectivesPredicate DPred,
491 bool FromParent) {
492 auto StartI = std::next(Stack.rbegin());
493 auto EndI = std::prev(Stack.rend());
494 if (FromParent && StartI != EndI) {
495 StartI = std::next(StartI);
496 }
497 for (auto I = StartI, EE = EndI; I != EE; ++I) {
498 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000499 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000500 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000501 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000502 return DVar;
503 }
504 return DSAVarData();
505}
506
Alexey Bataevf29276e2014-06-18 04:14:57 +0000507template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000508DSAStackTy::DSAVarData
509DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
510 DirectivesPredicate DPred, bool FromParent) {
511 auto StartI = std::next(Stack.rbegin());
512 auto EndI = std::prev(Stack.rend());
513 if (FromParent && StartI != EndI) {
514 StartI = std::next(StartI);
515 }
516 for (auto I = StartI, EE = EndI; I != EE; ++I) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000517 if (!DPred(I->Directive))
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000518 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +0000519 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000520 if (CPred(DVar.CKind))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000521 return DVar;
522 return DSAVarData();
523 }
524 return DSAVarData();
525}
526
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000527template <class NamedDirectivesPredicate>
528bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
529 auto StartI = std::next(Stack.rbegin());
530 auto EndI = std::prev(Stack.rend());
531 if (FromParent && StartI != EndI) {
532 StartI = std::next(StartI);
533 }
534 for (auto I = StartI, EE = EndI; I != EE; ++I) {
535 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
536 return true;
537 }
538 return false;
539}
540
Alexey Bataev758e55e2013-09-06 18:03:48 +0000541void Sema::InitDataSharingAttributesStack() {
542 VarDataSharingAttributesStack = new DSAStackTy(*this);
543}
544
545#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
546
Alexey Bataevf841bd92014-12-16 07:00:22 +0000547bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
548 assert(LangOpts.OpenMP && "OpenMP is not allowed");
549 if (DSAStack->getCurrentDirective() != OMPD_unknown) {
550 auto DVarPrivate = DSAStack->getTopDSA(VD, /*FromParent=*/false);
551 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
552 return true;
553 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
554 /*FromParent=*/false);
555 return DVarPrivate.CKind != OMPC_unknown;
556 }
557 return false;
558}
559
Alexey Bataeved09d242014-05-28 05:53:51 +0000560void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000561
562void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
563 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000564 Scope *CurScope, SourceLocation Loc) {
565 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000566 PushExpressionEvaluationContext(PotentiallyEvaluated);
567}
568
569void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000570 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
571 // A variable of class type (or array thereof) that appears in a lastprivate
572 // clause requires an accessible, unambiguous default constructor for the
573 // class type, unless the list item is also specified in a firstprivate
574 // clause.
575 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
576 for (auto C : D->clauses()) {
577 if (auto Clause = dyn_cast<OMPLastprivateClause>(C)) {
578 for (auto VarRef : Clause->varlists()) {
579 if (VarRef->isValueDependent() || VarRef->isTypeDependent())
580 continue;
581 auto VD = cast<VarDecl>(cast<DeclRefExpr>(VarRef)->getDecl());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000582 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000583 if (DVar.CKind == OMPC_lastprivate) {
584 SourceLocation ELoc = VarRef->getExprLoc();
585 auto Type = VarRef->getType();
586 if (Type->isArrayType())
587 Type = QualType(Type->getArrayElementTypeNoTypeQual(), 0);
588 CXXRecordDecl *RD =
Alexey Bataev23b69422014-06-18 07:08:49 +0000589 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
590 // FIXME This code must be replaced by actual constructing of the
591 // lastprivate variable.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000592 if (RD) {
593 CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
594 PartialDiagnostic PD =
595 PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
596 if (!CD ||
597 CheckConstructorAccess(
598 ELoc, CD, InitializedEntity::InitializeTemporary(Type),
599 CD->getAccess(), PD) == AR_inaccessible ||
600 CD->isDeleted()) {
601 Diag(ELoc, diag::err_omp_required_method)
602 << getOpenMPClauseName(OMPC_lastprivate) << 0;
603 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
604 VarDecl::DeclarationOnly;
605 Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl
606 : diag::note_defined_here)
607 << VD;
608 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
609 continue;
610 }
611 MarkFunctionReferenced(ELoc, CD);
612 DiagnoseUseOfDecl(CD, ELoc);
613 }
614 }
615 }
616 }
617 }
618 }
619
Alexey Bataev758e55e2013-09-06 18:03:48 +0000620 DSAStack->pop();
621 DiscardCleanupsInEvaluationContext();
622 PopExpressionEvaluationContext();
623}
624
Alexander Musman3276a272015-03-21 10:12:56 +0000625static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
626 Expr *NumIterations, Sema &SemaRef,
627 Scope *S);
628
Alexey Bataeva769e072013-03-22 06:34:35 +0000629namespace {
630
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000631class VarDeclFilterCCC : public CorrectionCandidateCallback {
632private:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000633 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +0000634
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000635public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000636 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +0000637 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000638 NamedDecl *ND = Candidate.getCorrectionDecl();
639 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
640 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000641 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
642 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +0000643 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000644 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +0000645 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000646};
Alexey Bataeved09d242014-05-28 05:53:51 +0000647} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000648
649ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
650 CXXScopeSpec &ScopeSpec,
651 const DeclarationNameInfo &Id) {
652 LookupResult Lookup(*this, Id, LookupOrdinaryName);
653 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
654
655 if (Lookup.isAmbiguous())
656 return ExprError();
657
658 VarDecl *VD;
659 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000660 if (TypoCorrection Corrected = CorrectTypo(
661 Id, LookupOrdinaryName, CurScope, nullptr,
662 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000663 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000664 PDiag(Lookup.empty()
665 ? diag::err_undeclared_var_use_suggest
666 : diag::err_omp_expected_var_arg_suggest)
667 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +0000668 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000669 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000670 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
671 : diag::err_omp_expected_var_arg)
672 << Id.getName();
673 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000674 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000675 } else {
676 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000677 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000678 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
679 return ExprError();
680 }
681 }
682 Lookup.suppressDiagnostics();
683
684 // OpenMP [2.9.2, Syntax, C/C++]
685 // Variables must be file-scope, namespace-scope, or static block-scope.
686 if (!VD->hasGlobalStorage()) {
687 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000688 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
689 bool IsDecl =
690 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000691 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +0000692 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
693 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000694 return ExprError();
695 }
696
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000697 VarDecl *CanonicalVD = VD->getCanonicalDecl();
698 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000699 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
700 // A threadprivate directive for file-scope variables must appear outside
701 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000702 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
703 !getCurLexicalContext()->isTranslationUnit()) {
704 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000705 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
706 bool IsDecl =
707 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
708 Diag(VD->getLocation(),
709 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
710 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000711 return ExprError();
712 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000713 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
714 // A threadprivate directive for static class member variables must appear
715 // in the class definition, in the same scope in which the member
716 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000717 if (CanonicalVD->isStaticDataMember() &&
718 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
719 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000720 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
721 bool IsDecl =
722 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
723 Diag(VD->getLocation(),
724 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
725 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000726 return ExprError();
727 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000728 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
729 // A threadprivate directive for namespace-scope variables must appear
730 // outside any definition or declaration other than the namespace
731 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000732 if (CanonicalVD->getDeclContext()->isNamespace() &&
733 (!getCurLexicalContext()->isFileContext() ||
734 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
735 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000736 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
737 bool IsDecl =
738 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
739 Diag(VD->getLocation(),
740 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
741 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000742 return ExprError();
743 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000744 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
745 // A threadprivate directive for static block-scope variables must appear
746 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000747 if (CanonicalVD->isStaticLocal() && CurScope &&
748 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000749 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000750 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
751 bool IsDecl =
752 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
753 Diag(VD->getLocation(),
754 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
755 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000756 return ExprError();
757 }
758
759 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
760 // A threadprivate directive must lexically precede all references to any
761 // of the variables in its list.
762 if (VD->isUsed()) {
763 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +0000764 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000765 return ExprError();
766 }
767
768 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataevd178ad42014-03-07 08:03:37 +0000769 ExprResult DE = BuildDeclRefExpr(VD, ExprType, VK_LValue, Id.getLoc());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000770 return DE;
771}
772
Alexey Bataeved09d242014-05-28 05:53:51 +0000773Sema::DeclGroupPtrTy
774Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
775 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000776 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000777 CurContext->addDecl(D);
778 return DeclGroupPtrTy::make(DeclGroupRef(D));
779 }
780 return DeclGroupPtrTy();
781}
782
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000783namespace {
784class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
785 Sema &SemaRef;
786
787public:
788 bool VisitDeclRefExpr(const DeclRefExpr *E) {
789 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
790 if (VD->hasLocalStorage()) {
791 SemaRef.Diag(E->getLocStart(),
792 diag::err_omp_local_var_in_threadprivate_init)
793 << E->getSourceRange();
794 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
795 << VD << VD->getSourceRange();
796 return true;
797 }
798 }
799 return false;
800 }
801 bool VisitStmt(const Stmt *S) {
802 for (auto Child : S->children()) {
803 if (Child && Visit(Child))
804 return true;
805 }
806 return false;
807 }
Alexey Bataev23b69422014-06-18 07:08:49 +0000808 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000809};
810} // namespace
811
Alexey Bataeved09d242014-05-28 05:53:51 +0000812OMPThreadPrivateDecl *
813Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000814 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +0000815 for (auto &RefExpr : VarList) {
816 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000817 VarDecl *VD = cast<VarDecl>(DE->getDecl());
818 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +0000819
820 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
821 // A threadprivate variable must not have an incomplete type.
822 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000823 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000824 continue;
825 }
826
827 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
828 // A threadprivate variable must not have a reference type.
829 if (VD->getType()->isReferenceType()) {
830 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000831 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
832 bool IsDecl =
833 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
834 Diag(VD->getLocation(),
835 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
836 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000837 continue;
838 }
839
Richard Smithfd3834f2013-04-13 02:43:54 +0000840 // Check if this is a TLS variable.
Alexey Bataev26a39242015-01-13 03:35:30 +0000841 if (VD->getTLSKind() != VarDecl::TLS_None ||
842 VD->getStorageClass() == SC_Register) {
843 Diag(ILoc, diag::err_omp_var_thread_local)
844 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +0000845 bool IsDecl =
846 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
847 Diag(VD->getLocation(),
848 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
849 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000850 continue;
851 }
852
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000853 // Check if initial value of threadprivate variable reference variable with
854 // local storage (it is not supported by runtime).
855 if (auto Init = VD->getAnyInitializer()) {
856 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000857 if (Checker.Visit(Init))
858 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000859 }
860
Alexey Bataeved09d242014-05-28 05:53:51 +0000861 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +0000862 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +0000863 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
864 Context, SourceRange(Loc, Loc)));
865 if (auto *ML = Context.getASTMutationListener())
866 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +0000867 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000868 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000869 if (!Vars.empty()) {
870 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
871 Vars);
872 D->setAccess(AS_public);
873 }
874 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +0000875}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000876
Alexey Bataev7ff55242014-06-19 09:13:45 +0000877static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
878 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
879 bool IsLoopIterVar = false) {
880 if (DVar.RefExpr) {
881 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
882 << getOpenMPClauseName(DVar.CKind);
883 return;
884 }
885 enum {
886 PDSA_StaticMemberShared,
887 PDSA_StaticLocalVarShared,
888 PDSA_LoopIterVarPrivate,
889 PDSA_LoopIterVarLinear,
890 PDSA_LoopIterVarLastprivate,
891 PDSA_ConstVarShared,
892 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000893 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000894 PDSA_LocalVarPrivate,
895 PDSA_Implicit
896 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000897 bool ReportHint = false;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000898 auto ReportLoc = VD->getLocation();
Alexey Bataev7ff55242014-06-19 09:13:45 +0000899 if (IsLoopIterVar) {
900 if (DVar.CKind == OMPC_private)
901 Reason = PDSA_LoopIterVarPrivate;
902 else if (DVar.CKind == OMPC_lastprivate)
903 Reason = PDSA_LoopIterVarLastprivate;
904 else
905 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000906 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
907 Reason = PDSA_TaskVarFirstprivate;
908 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000909 } else if (VD->isStaticLocal())
910 Reason = PDSA_StaticLocalVarShared;
911 else if (VD->isStaticDataMember())
912 Reason = PDSA_StaticMemberShared;
913 else if (VD->isFileVarDecl())
914 Reason = PDSA_GlobalVarShared;
915 else if (VD->getType().isConstant(SemaRef.getASTContext()))
916 Reason = PDSA_ConstVarShared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000917 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +0000918 ReportHint = true;
919 Reason = PDSA_LocalVarPrivate;
920 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000921 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000922 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +0000923 << Reason << ReportHint
924 << getOpenMPDirectiveName(Stack->getCurrentDirective());
925 } else if (DVar.ImplicitDSALoc.isValid()) {
926 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
927 << getOpenMPClauseName(DVar.CKind);
928 }
Alexey Bataev7ff55242014-06-19 09:13:45 +0000929}
930
Alexey Bataev758e55e2013-09-06 18:03:48 +0000931namespace {
932class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
933 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000934 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000935 bool ErrorFound;
936 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000937 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev4acb8592014-07-07 13:01:15 +0000938 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +0000939
Alexey Bataev758e55e2013-09-06 18:03:48 +0000940public:
941 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000942 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000943 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +0000944 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
945 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000946
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000947 auto DVar = Stack->getTopDSA(VD, false);
948 // Check if the variable has explicit DSA set and stop analysis if it so.
949 if (DVar.RefExpr) return;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000950
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000951 auto ELoc = E->getExprLoc();
952 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000953 // The default(none) clause requires that each variable that is referenced
954 // in the construct, and does not have a predetermined data-sharing
955 // attribute, must have its data-sharing attribute explicitly determined
956 // by being listed in a data-sharing attribute clause.
957 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000958 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +0000959 VarsWithInheritedDSA.count(VD) == 0) {
960 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000961 return;
962 }
963
964 // OpenMP [2.9.3.6, Restrictions, p.2]
965 // A list item that appears in a reduction clause of the innermost
966 // enclosing worksharing or parallel construct may not be accessed in an
967 // explicit task.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000968 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000969 [](OpenMPDirectiveKind K) -> bool {
970 return isOpenMPParallelDirective(K) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +0000971 isOpenMPWorksharingDirective(K) ||
972 isOpenMPTeamsDirective(K);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000973 },
974 false);
Alexey Bataevc5e02582014-06-16 07:08:35 +0000975 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
976 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000977 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
978 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +0000979 return;
980 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000981
982 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000983 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000984 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000985 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000986 }
987 }
988 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000989 for (auto *C : S->clauses()) {
990 // Skip analysis of arguments of implicitly defined firstprivate clause
991 // for task directives.
992 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
993 for (auto *CC : C->children()) {
994 if (CC)
995 Visit(CC);
996 }
997 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000998 }
999 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001000 for (auto *C : S->children()) {
1001 if (C && !isa<OMPExecutableDirective>(C))
1002 Visit(C);
1003 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001004 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001005
1006 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001007 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001008 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1009 return VarsWithInheritedDSA;
1010 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001011
Alexey Bataev7ff55242014-06-19 09:13:45 +00001012 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1013 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001014};
Alexey Bataeved09d242014-05-28 05:53:51 +00001015} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001016
Alexey Bataevbae9a792014-06-27 10:37:06 +00001017void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001018 switch (DKind) {
1019 case OMPD_parallel: {
1020 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1021 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001022 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001023 std::make_pair(".global_tid.", KmpInt32PtrTy),
1024 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1025 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001026 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001027 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1028 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001029 break;
1030 }
1031 case OMPD_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001032 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001033 std::make_pair(StringRef(), QualType()) // __context with shared vars
1034 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001035 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1036 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001037 break;
1038 }
1039 case OMPD_for: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001040 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001041 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001042 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001043 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1044 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001045 break;
1046 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001047 case OMPD_for_simd: {
1048 Sema::CapturedParamNameType Params[] = {
1049 std::make_pair(StringRef(), QualType()) // __context with shared vars
1050 };
1051 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1052 Params);
1053 break;
1054 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001055 case OMPD_sections: {
1056 Sema::CapturedParamNameType Params[] = {
1057 std::make_pair(StringRef(), QualType()) // __context with shared vars
1058 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001059 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1060 Params);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001061 break;
1062 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001063 case OMPD_section: {
1064 Sema::CapturedParamNameType Params[] = {
1065 std::make_pair(StringRef(), QualType()) // __context with shared vars
1066 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001067 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1068 Params);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001069 break;
1070 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001071 case OMPD_single: {
1072 Sema::CapturedParamNameType Params[] = {
1073 std::make_pair(StringRef(), QualType()) // __context with shared vars
1074 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001075 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1076 Params);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001077 break;
1078 }
Alexander Musman80c22892014-07-17 08:54:58 +00001079 case OMPD_master: {
1080 Sema::CapturedParamNameType Params[] = {
1081 std::make_pair(StringRef(), QualType()) // __context with shared vars
1082 };
1083 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1084 Params);
1085 break;
1086 }
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001087 case OMPD_critical: {
1088 Sema::CapturedParamNameType Params[] = {
1089 std::make_pair(StringRef(), QualType()) // __context with shared vars
1090 };
1091 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1092 Params);
1093 break;
1094 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001095 case OMPD_parallel_for: {
1096 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1097 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1098 Sema::CapturedParamNameType Params[] = {
1099 std::make_pair(".global_tid.", KmpInt32PtrTy),
1100 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1101 std::make_pair(StringRef(), QualType()) // __context with shared vars
1102 };
1103 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1104 Params);
1105 break;
1106 }
Alexander Musmane4e893b2014-09-23 09:33:00 +00001107 case OMPD_parallel_for_simd: {
1108 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1109 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1110 Sema::CapturedParamNameType Params[] = {
1111 std::make_pair(".global_tid.", KmpInt32PtrTy),
1112 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1113 std::make_pair(StringRef(), QualType()) // __context with shared vars
1114 };
1115 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1116 Params);
1117 break;
1118 }
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001119 case OMPD_parallel_sections: {
1120 Sema::CapturedParamNameType Params[] = {
1121 std::make_pair(StringRef(), QualType()) // __context with shared vars
1122 };
1123 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1124 Params);
1125 break;
1126 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001127 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001128 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001129 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001130 std::make_pair(".global_tid.", KmpInt32Ty),
1131 std::make_pair(".part_id.", KmpInt32Ty),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001132 std::make_pair(StringRef(), QualType()) // __context with shared vars
1133 };
1134 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1135 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001136 // Mark this captured region as inlined, because we don't use outlined
1137 // function directly.
1138 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1139 AlwaysInlineAttr::CreateImplicit(
1140 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001141 break;
1142 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001143 case OMPD_ordered: {
1144 Sema::CapturedParamNameType Params[] = {
1145 std::make_pair(StringRef(), QualType()) // __context with shared vars
1146 };
1147 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1148 Params);
1149 break;
1150 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001151 case OMPD_atomic: {
1152 Sema::CapturedParamNameType Params[] = {
1153 std::make_pair(StringRef(), QualType()) // __context with shared vars
1154 };
1155 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1156 Params);
1157 break;
1158 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001159 case OMPD_target: {
1160 Sema::CapturedParamNameType Params[] = {
1161 std::make_pair(StringRef(), QualType()) // __context with shared vars
1162 };
1163 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1164 Params);
1165 break;
1166 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001167 case OMPD_teams: {
1168 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1169 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1170 Sema::CapturedParamNameType Params[] = {
1171 std::make_pair(".global_tid.", KmpInt32PtrTy),
1172 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1173 std::make_pair(StringRef(), QualType()) // __context with shared vars
1174 };
1175 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1176 Params);
1177 break;
1178 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001179 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001180 case OMPD_taskyield:
1181 case OMPD_barrier:
1182 case OMPD_taskwait:
1183 case OMPD_flush:
Alexey Bataev9959db52014-05-06 10:08:46 +00001184 llvm_unreachable("OpenMP Directive is not allowed");
1185 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001186 llvm_unreachable("Unknown OpenMP directive");
1187 }
1188}
1189
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001190static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1191 OpenMPDirectiveKind CurrentRegion,
1192 const DeclarationNameInfo &CurrentName,
1193 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001194 // Allowed nesting of constructs
1195 // +------------------+-----------------+------------------------------------+
1196 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1197 // +------------------+-----------------+------------------------------------+
1198 // | parallel | parallel | * |
1199 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001200 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001201 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001202 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001203 // | parallel | simd | * |
1204 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001205 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001206 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001207 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001208 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001209 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001210 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001211 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001212 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001213 // | parallel | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001214 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001215 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001216 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001217 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001218 // | parallel | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001219 // +------------------+-----------------+------------------------------------+
1220 // | for | parallel | * |
1221 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001222 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001223 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001224 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001225 // | for | simd | * |
1226 // | for | sections | + |
1227 // | for | section | + |
1228 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001229 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001230 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001231 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001232 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001233 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001234 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001235 // | for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001236 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001237 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001238 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001239 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001240 // | for | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001241 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001242 // | master | parallel | * |
1243 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001244 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001245 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001246 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001247 // | master | simd | * |
1248 // | master | sections | + |
1249 // | master | section | + |
1250 // | master | single | + |
1251 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001252 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001253 // | master |parallel sections| * |
1254 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001255 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001256 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001257 // | master | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001258 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001259 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001260 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001261 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001262 // | master | teams | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001263 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001264 // | critical | parallel | * |
1265 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001266 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001267 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001268 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001269 // | critical | simd | * |
1270 // | critical | sections | + |
1271 // | critical | section | + |
1272 // | critical | single | + |
1273 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001274 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001275 // | critical |parallel sections| * |
1276 // | critical | task | * |
1277 // | critical | taskyield | * |
1278 // | critical | barrier | + |
1279 // | critical | taskwait | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001280 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001281 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001282 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001283 // | critical | teams | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001284 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001285 // | simd | parallel | |
1286 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001287 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001288 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001289 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001290 // | simd | simd | |
1291 // | simd | sections | |
1292 // | simd | section | |
1293 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001294 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001295 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001296 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001297 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001298 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001299 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001300 // | simd | taskwait | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001301 // | simd | flush | |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001302 // | simd | ordered | |
Alexey Bataev0162e452014-07-22 10:10:35 +00001303 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001304 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001305 // | simd | teams | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001306 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001307 // | for simd | parallel | |
1308 // | for simd | for | |
1309 // | for simd | for simd | |
1310 // | for simd | master | |
1311 // | for simd | critical | |
1312 // | for simd | simd | |
1313 // | for simd | sections | |
1314 // | for simd | section | |
1315 // | for simd | single | |
1316 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001317 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001318 // | for simd |parallel sections| |
1319 // | for simd | task | |
1320 // | for simd | taskyield | |
1321 // | for simd | barrier | |
1322 // | for simd | taskwait | |
1323 // | for simd | flush | |
1324 // | for simd | ordered | |
1325 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001326 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001327 // | for simd | teams | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001328 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001329 // | parallel for simd| parallel | |
1330 // | parallel for simd| for | |
1331 // | parallel for simd| for simd | |
1332 // | parallel for simd| master | |
1333 // | parallel for simd| critical | |
1334 // | parallel for simd| simd | |
1335 // | parallel for simd| sections | |
1336 // | parallel for simd| section | |
1337 // | parallel for simd| single | |
1338 // | parallel for simd| parallel for | |
1339 // | parallel for simd|parallel for simd| |
1340 // | parallel for simd|parallel sections| |
1341 // | parallel for simd| task | |
1342 // | parallel for simd| taskyield | |
1343 // | parallel for simd| barrier | |
1344 // | parallel for simd| taskwait | |
1345 // | parallel for simd| flush | |
1346 // | parallel for simd| ordered | |
1347 // | parallel for simd| atomic | |
1348 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001349 // | parallel for simd| teams | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001350 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001351 // | sections | parallel | * |
1352 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001353 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001354 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001355 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001356 // | sections | simd | * |
1357 // | sections | sections | + |
1358 // | sections | section | * |
1359 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001360 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001361 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001362 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001363 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001364 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001365 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001366 // | sections | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001367 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001368 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001369 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001370 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001371 // | sections | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001372 // +------------------+-----------------+------------------------------------+
1373 // | section | parallel | * |
1374 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001375 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001376 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001377 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001378 // | section | simd | * |
1379 // | section | sections | + |
1380 // | section | section | + |
1381 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001382 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001383 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001384 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001385 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001386 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001387 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001388 // | section | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001389 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001390 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001391 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001392 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001393 // | section | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001394 // +------------------+-----------------+------------------------------------+
1395 // | single | parallel | * |
1396 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001397 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001398 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001399 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001400 // | single | simd | * |
1401 // | single | sections | + |
1402 // | single | section | + |
1403 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001404 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001405 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001406 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001407 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001408 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001409 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001410 // | single | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001411 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001412 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001413 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001414 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001415 // | single | teams | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001416 // +------------------+-----------------+------------------------------------+
1417 // | parallel for | parallel | * |
1418 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001419 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001420 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001421 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001422 // | parallel for | simd | * |
1423 // | parallel for | sections | + |
1424 // | parallel for | section | + |
1425 // | parallel for | single | + |
1426 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001427 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001428 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001429 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001430 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001431 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001432 // | parallel for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001433 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001434 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001435 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001436 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001437 // | parallel for | teams | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001438 // +------------------+-----------------+------------------------------------+
1439 // | parallel sections| parallel | * |
1440 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001441 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001442 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001443 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001444 // | parallel sections| simd | * |
1445 // | parallel sections| sections | + |
1446 // | parallel sections| section | * |
1447 // | parallel sections| single | + |
1448 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001449 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001450 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001451 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001452 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001453 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001454 // | parallel sections| taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001455 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001456 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001457 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001458 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001459 // | parallel sections| teams | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001460 // +------------------+-----------------+------------------------------------+
1461 // | task | parallel | * |
1462 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001463 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001464 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001465 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001466 // | task | simd | * |
1467 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001468 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001469 // | task | single | + |
1470 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001471 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001472 // | task |parallel sections| * |
1473 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001474 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001475 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001476 // | task | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001477 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001478 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001479 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001480 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001481 // | task | teams | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001482 // +------------------+-----------------+------------------------------------+
1483 // | ordered | parallel | * |
1484 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001485 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001486 // | ordered | master | * |
1487 // | ordered | critical | * |
1488 // | ordered | simd | * |
1489 // | ordered | sections | + |
1490 // | ordered | section | + |
1491 // | ordered | single | + |
1492 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001493 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001494 // | ordered |parallel sections| * |
1495 // | ordered | task | * |
1496 // | ordered | taskyield | * |
1497 // | ordered | barrier | + |
1498 // | ordered | taskwait | * |
1499 // | ordered | flush | * |
1500 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001501 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001502 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001503 // | ordered | teams | + |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001504 // +------------------+-----------------+------------------------------------+
1505 // | atomic | parallel | |
1506 // | atomic | for | |
1507 // | atomic | for simd | |
1508 // | atomic | master | |
1509 // | atomic | critical | |
1510 // | atomic | simd | |
1511 // | atomic | sections | |
1512 // | atomic | section | |
1513 // | atomic | single | |
1514 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001515 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001516 // | atomic |parallel sections| |
1517 // | atomic | task | |
1518 // | atomic | taskyield | |
1519 // | atomic | barrier | |
1520 // | atomic | taskwait | |
1521 // | atomic | flush | |
1522 // | atomic | ordered | |
1523 // | atomic | atomic | |
1524 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001525 // | atomic | teams | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001526 // +------------------+-----------------+------------------------------------+
1527 // | target | parallel | * |
1528 // | target | for | * |
1529 // | target | for simd | * |
1530 // | target | master | * |
1531 // | target | critical | * |
1532 // | target | simd | * |
1533 // | target | sections | * |
1534 // | target | section | * |
1535 // | target | single | * |
1536 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001537 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001538 // | target |parallel sections| * |
1539 // | target | task | * |
1540 // | target | taskyield | * |
1541 // | target | barrier | * |
1542 // | target | taskwait | * |
1543 // | target | flush | * |
1544 // | target | ordered | * |
1545 // | target | atomic | * |
1546 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001547 // | target | teams | * |
1548 // +------------------+-----------------+------------------------------------+
1549 // | teams | parallel | * |
1550 // | teams | for | + |
1551 // | teams | for simd | + |
1552 // | teams | master | + |
1553 // | teams | critical | + |
1554 // | teams | simd | + |
1555 // | teams | sections | + |
1556 // | teams | section | + |
1557 // | teams | single | + |
1558 // | teams | parallel for | * |
1559 // | teams |parallel for simd| * |
1560 // | teams |parallel sections| * |
1561 // | teams | task | + |
1562 // | teams | taskyield | + |
1563 // | teams | barrier | + |
1564 // | teams | taskwait | + |
1565 // | teams | flush | + |
1566 // | teams | ordered | + |
1567 // | teams | atomic | + |
1568 // | teams | target | + |
1569 // | teams | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001570 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00001571 if (Stack->getCurScope()) {
1572 auto ParentRegion = Stack->getParentDirective();
1573 bool NestingProhibited = false;
1574 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001575 enum {
1576 NoRecommend,
1577 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001578 ShouldBeInOrderedRegion,
1579 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001580 } Recommend = NoRecommend;
Alexey Bataev549210e2014-06-24 04:39:47 +00001581 if (isOpenMPSimdDirective(ParentRegion)) {
1582 // OpenMP [2.16, Nesting of Regions]
1583 // OpenMP constructs may not be nested inside a simd region.
1584 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1585 return true;
1586 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001587 if (ParentRegion == OMPD_atomic) {
1588 // OpenMP [2.16, Nesting of Regions]
1589 // OpenMP constructs may not be nested inside an atomic region.
1590 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1591 return true;
1592 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001593 if (CurrentRegion == OMPD_section) {
1594 // OpenMP [2.7.2, sections Construct, Restrictions]
1595 // Orphaned section directives are prohibited. That is, the section
1596 // directives must appear within the sections construct and must not be
1597 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001598 if (ParentRegion != OMPD_sections &&
1599 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001600 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1601 << (ParentRegion != OMPD_unknown)
1602 << getOpenMPDirectiveName(ParentRegion);
1603 return true;
1604 }
1605 return false;
1606 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001607 // Allow some constructs to be orphaned (they could be used in functions,
1608 // called from OpenMP regions with the required preconditions).
1609 if (ParentRegion == OMPD_unknown)
1610 return false;
Alexander Musman80c22892014-07-17 08:54:58 +00001611 if (CurrentRegion == OMPD_master) {
1612 // OpenMP [2.16, Nesting of Regions]
1613 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001614 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001615 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1616 ParentRegion == OMPD_task;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001617 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1618 // OpenMP [2.16, Nesting of Regions]
1619 // A critical region may not be nested (closely or otherwise) inside a
1620 // critical region with the same name. Note that this restriction is not
1621 // sufficient to prevent deadlock.
1622 SourceLocation PreviousCriticalLoc;
1623 bool DeadLock =
1624 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1625 OpenMPDirectiveKind K,
1626 const DeclarationNameInfo &DNI,
1627 SourceLocation Loc)
1628 ->bool {
1629 if (K == OMPD_critical &&
1630 DNI.getName() == CurrentName.getName()) {
1631 PreviousCriticalLoc = Loc;
1632 return true;
1633 } else
1634 return false;
1635 },
1636 false /* skip top directive */);
1637 if (DeadLock) {
1638 SemaRef.Diag(StartLoc,
1639 diag::err_omp_prohibited_region_critical_same_name)
1640 << CurrentName.getName();
1641 if (PreviousCriticalLoc.isValid())
1642 SemaRef.Diag(PreviousCriticalLoc,
1643 diag::note_omp_previous_critical_region);
1644 return true;
1645 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001646 } else if (CurrentRegion == OMPD_barrier) {
1647 // OpenMP [2.16, Nesting of Regions]
1648 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001649 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001650 NestingProhibited =
1651 isOpenMPWorksharingDirective(ParentRegion) ||
1652 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1653 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001654 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00001655 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001656 // OpenMP [2.16, Nesting of Regions]
1657 // A worksharing region may not be closely nested inside a worksharing,
1658 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001659 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00001660 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001661 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1662 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1663 Recommend = ShouldBeInParallelRegion;
1664 } else if (CurrentRegion == OMPD_ordered) {
1665 // OpenMP [2.16, Nesting of Regions]
1666 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00001667 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001668 // An ordered region must be closely nested inside a loop region (or
1669 // parallel loop region) with an ordered clause.
1670 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00001671 ParentRegion == OMPD_task ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001672 !Stack->isParentOrderedRegion();
1673 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001674 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1675 // OpenMP [2.16, Nesting of Regions]
1676 // If specified, a teams construct must be contained within a target
1677 // construct.
1678 NestingProhibited = ParentRegion != OMPD_target;
1679 Recommend = ShouldBeInTargetRegion;
1680 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1681 }
1682 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1683 // OpenMP [2.16, Nesting of Regions]
1684 // distribute, parallel, parallel sections, parallel workshare, and the
1685 // parallel loop and parallel loop SIMD constructs are the only OpenMP
1686 // constructs that can be closely nested in the teams region.
1687 // TODO: add distribute directive.
1688 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1689 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001690 }
1691 if (NestingProhibited) {
1692 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001693 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1694 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00001695 return true;
1696 }
1697 }
1698 return false;
1699}
1700
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001701StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001702 const DeclarationNameInfo &DirName,
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001703 ArrayRef<OMPClause *> Clauses,
1704 Stmt *AStmt,
1705 SourceLocation StartLoc,
1706 SourceLocation EndLoc) {
1707 StmtResult Res = StmtError();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001708 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00001709 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001710
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001711 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00001712 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001713 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00001714 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00001715 if (AStmt) {
1716 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1717
1718 // Check default data sharing attributes for referenced variables.
1719 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1720 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1721 if (DSAChecker.isErrorFound())
1722 return StmtError();
1723 // Generate list of implicitly defined firstprivate variables.
1724 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00001725
1726 if (!DSAChecker.getImplicitFirstprivate().empty()) {
1727 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1728 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1729 SourceLocation(), SourceLocation())) {
1730 ClausesWithImplicit.push_back(Implicit);
1731 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1732 DSAChecker.getImplicitFirstprivate().size();
1733 } else
1734 ErrorFound = true;
1735 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001736 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001737
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001738 switch (Kind) {
1739 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00001740 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1741 EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001742 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001743 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001744 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1745 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001746 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00001747 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001748 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1749 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001750 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00001751 case OMPD_for_simd:
1752 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
1753 EndLoc, VarsWithInheritedDSA);
1754 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001755 case OMPD_sections:
1756 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1757 EndLoc);
1758 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001759 case OMPD_section:
1760 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00001761 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001762 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1763 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001764 case OMPD_single:
1765 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1766 EndLoc);
1767 break;
Alexander Musman80c22892014-07-17 08:54:58 +00001768 case OMPD_master:
1769 assert(ClausesWithImplicit.empty() &&
1770 "No clauses are allowed for 'omp master' directive");
1771 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1772 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001773 case OMPD_critical:
1774 assert(ClausesWithImplicit.empty() &&
1775 "No clauses are allowed for 'omp critical' directive");
1776 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1777 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001778 case OMPD_parallel_for:
1779 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1780 EndLoc, VarsWithInheritedDSA);
1781 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00001782 case OMPD_parallel_for_simd:
1783 Res = ActOnOpenMPParallelForSimdDirective(
1784 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
1785 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001786 case OMPD_parallel_sections:
1787 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1788 StartLoc, EndLoc);
1789 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001790 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001791 Res =
1792 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1793 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00001794 case OMPD_taskyield:
1795 assert(ClausesWithImplicit.empty() &&
1796 "No clauses are allowed for 'omp taskyield' directive");
1797 assert(AStmt == nullptr &&
1798 "No associated statement allowed for 'omp taskyield' directive");
1799 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1800 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001801 case OMPD_barrier:
1802 assert(ClausesWithImplicit.empty() &&
1803 "No clauses are allowed for 'omp barrier' directive");
1804 assert(AStmt == nullptr &&
1805 "No associated statement allowed for 'omp barrier' directive");
1806 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1807 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00001808 case OMPD_taskwait:
1809 assert(ClausesWithImplicit.empty() &&
1810 "No clauses are allowed for 'omp taskwait' directive");
1811 assert(AStmt == nullptr &&
1812 "No associated statement allowed for 'omp taskwait' directive");
1813 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1814 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00001815 case OMPD_flush:
1816 assert(AStmt == nullptr &&
1817 "No associated statement allowed for 'omp flush' directive");
1818 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
1819 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001820 case OMPD_ordered:
1821 assert(ClausesWithImplicit.empty() &&
1822 "No clauses are allowed for 'omp ordered' directive");
1823 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
1824 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00001825 case OMPD_atomic:
1826 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
1827 EndLoc);
1828 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001829 case OMPD_teams:
1830 Res =
1831 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1832 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001833 case OMPD_target:
1834 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
1835 EndLoc);
1836 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001837 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001838 llvm_unreachable("OpenMP Directive is not allowed");
1839 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001840 llvm_unreachable("Unknown OpenMP directive");
1841 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001842
Alexey Bataev4acb8592014-07-07 13:01:15 +00001843 for (auto P : VarsWithInheritedDSA) {
1844 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1845 << P.first << P.second->getSourceRange();
1846 }
1847 if (!VarsWithInheritedDSA.empty())
1848 return StmtError();
1849
Alexey Bataeved09d242014-05-28 05:53:51 +00001850 if (ErrorFound)
1851 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001852 return Res;
1853}
1854
1855StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
1856 Stmt *AStmt,
1857 SourceLocation StartLoc,
1858 SourceLocation EndLoc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001859 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
1860 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
1861 // 1.2.2 OpenMP Language Terminology
1862 // Structured block - An executable statement with a single entry at the
1863 // top and a single exit at the bottom.
1864 // The point of exit cannot be a branch out of the structured block.
1865 // longjmp() and throw() must not violate the entry/exit criteria.
1866 CS->getCapturedDecl()->setNothrow();
1867
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001868 getCurFunction()->setHasBranchProtectedScope();
1869
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001870 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
1871 AStmt);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001872}
1873
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001874namespace {
1875/// \brief Helper class for checking canonical form of the OpenMP loops and
1876/// extracting iteration space of each loop in the loop nest, that will be used
1877/// for IR generation.
1878class OpenMPIterationSpaceChecker {
1879 /// \brief Reference to Sema.
1880 Sema &SemaRef;
1881 /// \brief A location for diagnostics (when there is no some better location).
1882 SourceLocation DefaultLoc;
1883 /// \brief A location for diagnostics (when increment is not compatible).
1884 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001885 /// \brief A source location for referring to loop init later.
1886 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001887 /// \brief A source location for referring to condition later.
1888 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001889 /// \brief A source location for referring to increment later.
1890 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001891 /// \brief Loop variable.
1892 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001893 /// \brief Reference to loop variable.
1894 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001895 /// \brief Lower bound (initializer for the var).
1896 Expr *LB;
1897 /// \brief Upper bound.
1898 Expr *UB;
1899 /// \brief Loop step (increment).
1900 Expr *Step;
1901 /// \brief This flag is true when condition is one of:
1902 /// Var < UB
1903 /// Var <= UB
1904 /// UB > Var
1905 /// UB >= Var
1906 bool TestIsLessOp;
1907 /// \brief This flag is true when condition is strict ( < or > ).
1908 bool TestIsStrictOp;
1909 /// \brief This flag is true when step is subtracted on each iteration.
1910 bool SubtractStep;
1911
1912public:
1913 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
1914 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00001915 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
1916 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001917 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
1918 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001919 /// \brief Check init-expr for canonical loop form and save loop counter
1920 /// variable - #Var and its initialization value - #LB.
1921 bool CheckInit(Stmt *S);
1922 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
1923 /// for less/greater and for strict/non-strict comparison.
1924 bool CheckCond(Expr *S);
1925 /// \brief Check incr-expr for canonical loop form and return true if it
1926 /// does not conform, otherwise save loop step (#Step).
1927 bool CheckInc(Expr *S);
1928 /// \brief Return the loop counter variable.
1929 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001930 /// \brief Return the reference expression to loop counter variable.
1931 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001932 /// \brief Source range of the loop init.
1933 SourceRange GetInitSrcRange() const { return InitSrcRange; }
1934 /// \brief Source range of the loop condition.
1935 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
1936 /// \brief Source range of the loop increment.
1937 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
1938 /// \brief True if the step should be subtracted.
1939 bool ShouldSubtractStep() const { return SubtractStep; }
1940 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00001941 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001942 /// \brief Build reference expression to the counter be used for codegen.
1943 Expr *BuildCounterVar() const;
1944 /// \brief Build initization of the counter be used for codegen.
1945 Expr *BuildCounterInit() const;
1946 /// \brief Build step of the counter be used for codegen.
1947 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001948 /// \brief Return true if any expression is dependent.
1949 bool Dependent() const;
1950
1951private:
1952 /// \brief Check the right-hand side of an assignment in the increment
1953 /// expression.
1954 bool CheckIncRHS(Expr *RHS);
1955 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001956 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001957 /// \brief Helper to set upper bound.
1958 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
1959 const SourceLocation &SL);
1960 /// \brief Helper to set loop increment.
1961 bool SetStep(Expr *NewStep, bool Subtract);
1962};
1963
1964bool OpenMPIterationSpaceChecker::Dependent() const {
1965 if (!Var) {
1966 assert(!LB && !UB && !Step);
1967 return false;
1968 }
1969 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
1970 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
1971}
1972
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001973bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
1974 DeclRefExpr *NewVarRefExpr,
1975 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001976 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001977 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
1978 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001979 if (!NewVar || !NewLB)
1980 return true;
1981 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001982 VarRef = NewVarRefExpr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001983 LB = NewLB;
1984 return false;
1985}
1986
1987bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
1988 const SourceRange &SR,
1989 const SourceLocation &SL) {
1990 // State consistency checking to ensure correct usage.
1991 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
1992 !TestIsLessOp && !TestIsStrictOp);
1993 if (!NewUB)
1994 return true;
1995 UB = NewUB;
1996 TestIsLessOp = LessOp;
1997 TestIsStrictOp = StrictOp;
1998 ConditionSrcRange = SR;
1999 ConditionLoc = SL;
2000 return false;
2001}
2002
2003bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2004 // State consistency checking to ensure correct usage.
2005 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2006 if (!NewStep)
2007 return true;
2008 if (!NewStep->isValueDependent()) {
2009 // Check that the step is integer expression.
2010 SourceLocation StepLoc = NewStep->getLocStart();
2011 ExprResult Val =
2012 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2013 if (Val.isInvalid())
2014 return true;
2015 NewStep = Val.get();
2016
2017 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2018 // If test-expr is of form var relational-op b and relational-op is < or
2019 // <= then incr-expr must cause var to increase on each iteration of the
2020 // loop. If test-expr is of form var relational-op b and relational-op is
2021 // > or >= then incr-expr must cause var to decrease on each iteration of
2022 // the loop.
2023 // If test-expr is of form b relational-op var and relational-op is < or
2024 // <= then incr-expr must cause var to decrease on each iteration of the
2025 // loop. If test-expr is of form b relational-op var and relational-op is
2026 // > or >= then incr-expr must cause var to increase on each iteration of
2027 // the loop.
2028 llvm::APSInt Result;
2029 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2030 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2031 bool IsConstNeg =
2032 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002033 bool IsConstPos =
2034 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002035 bool IsConstZero = IsConstant && !Result.getBoolValue();
2036 if (UB && (IsConstZero ||
2037 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002038 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002039 SemaRef.Diag(NewStep->getExprLoc(),
2040 diag::err_omp_loop_incr_not_compatible)
2041 << Var << TestIsLessOp << NewStep->getSourceRange();
2042 SemaRef.Diag(ConditionLoc,
2043 diag::note_omp_loop_cond_requres_compatible_incr)
2044 << TestIsLessOp << ConditionSrcRange;
2045 return true;
2046 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002047 if (TestIsLessOp == Subtract) {
2048 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2049 NewStep).get();
2050 Subtract = !Subtract;
2051 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002052 }
2053
2054 Step = NewStep;
2055 SubtractStep = Subtract;
2056 return false;
2057}
2058
2059bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S) {
2060 // Check init-expr for canonical loop form and save loop counter
2061 // variable - #Var and its initialization value - #LB.
2062 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2063 // var = lb
2064 // integer-type var = lb
2065 // random-access-iterator-type var = lb
2066 // pointer-type var = lb
2067 //
2068 if (!S) {
2069 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2070 return true;
2071 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002072 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002073 if (Expr *E = dyn_cast<Expr>(S))
2074 S = E->IgnoreParens();
2075 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2076 if (BO->getOpcode() == BO_Assign)
2077 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002078 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002079 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002080 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2081 if (DS->isSingleDecl()) {
2082 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2083 if (Var->hasInit()) {
2084 // Accept non-canonical init form here but emit ext. warning.
2085 if (Var->getInitStyle() != VarDecl::CInit)
2086 SemaRef.Diag(S->getLocStart(),
2087 diag::ext_omp_loop_not_canonical_init)
2088 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002089 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002090 }
2091 }
2092 }
2093 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2094 if (CE->getOperator() == OO_Equal)
2095 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002096 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2097 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002098
2099 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2100 << S->getSourceRange();
2101 return true;
2102}
2103
Alexey Bataev23b69422014-06-18 07:08:49 +00002104/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002105/// variable (which may be the loop variable) if possible.
2106static const VarDecl *GetInitVarDecl(const Expr *E) {
2107 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002108 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002109 E = E->IgnoreParenImpCasts();
2110 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2111 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2112 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
2113 CE->getArg(0) != nullptr)
2114 E = CE->getArg(0)->IgnoreParenImpCasts();
2115 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2116 if (!DRE)
2117 return nullptr;
2118 return dyn_cast<VarDecl>(DRE->getDecl());
2119}
2120
2121bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2122 // Check test-expr for canonical form, save upper-bound UB, flags for
2123 // less/greater and for strict/non-strict comparison.
2124 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2125 // var relational-op b
2126 // b relational-op var
2127 //
2128 if (!S) {
2129 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2130 return true;
2131 }
2132 S = S->IgnoreParenImpCasts();
2133 SourceLocation CondLoc = S->getLocStart();
2134 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2135 if (BO->isRelationalOp()) {
2136 if (GetInitVarDecl(BO->getLHS()) == Var)
2137 return SetUB(BO->getRHS(),
2138 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2139 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2140 BO->getSourceRange(), BO->getOperatorLoc());
2141 if (GetInitVarDecl(BO->getRHS()) == Var)
2142 return SetUB(BO->getLHS(),
2143 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2144 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2145 BO->getSourceRange(), BO->getOperatorLoc());
2146 }
2147 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2148 if (CE->getNumArgs() == 2) {
2149 auto Op = CE->getOperator();
2150 switch (Op) {
2151 case OO_Greater:
2152 case OO_GreaterEqual:
2153 case OO_Less:
2154 case OO_LessEqual:
2155 if (GetInitVarDecl(CE->getArg(0)) == Var)
2156 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2157 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2158 CE->getOperatorLoc());
2159 if (GetInitVarDecl(CE->getArg(1)) == Var)
2160 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2161 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2162 CE->getOperatorLoc());
2163 break;
2164 default:
2165 break;
2166 }
2167 }
2168 }
2169 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2170 << S->getSourceRange() << Var;
2171 return true;
2172}
2173
2174bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2175 // RHS of canonical loop form increment can be:
2176 // var + incr
2177 // incr + var
2178 // var - incr
2179 //
2180 RHS = RHS->IgnoreParenImpCasts();
2181 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2182 if (BO->isAdditiveOp()) {
2183 bool IsAdd = BO->getOpcode() == BO_Add;
2184 if (GetInitVarDecl(BO->getLHS()) == Var)
2185 return SetStep(BO->getRHS(), !IsAdd);
2186 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2187 return SetStep(BO->getLHS(), false);
2188 }
2189 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2190 bool IsAdd = CE->getOperator() == OO_Plus;
2191 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2192 if (GetInitVarDecl(CE->getArg(0)) == Var)
2193 return SetStep(CE->getArg(1), !IsAdd);
2194 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2195 return SetStep(CE->getArg(0), false);
2196 }
2197 }
2198 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2199 << RHS->getSourceRange() << Var;
2200 return true;
2201}
2202
2203bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2204 // Check incr-expr for canonical loop form and return true if it
2205 // does not conform.
2206 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2207 // ++var
2208 // var++
2209 // --var
2210 // var--
2211 // var += incr
2212 // var -= incr
2213 // var = var + incr
2214 // var = incr + var
2215 // var = var - incr
2216 //
2217 if (!S) {
2218 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2219 return true;
2220 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002221 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002222 S = S->IgnoreParens();
2223 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2224 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2225 return SetStep(
2226 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2227 (UO->isDecrementOp() ? -1 : 1)).get(),
2228 false);
2229 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2230 switch (BO->getOpcode()) {
2231 case BO_AddAssign:
2232 case BO_SubAssign:
2233 if (GetInitVarDecl(BO->getLHS()) == Var)
2234 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2235 break;
2236 case BO_Assign:
2237 if (GetInitVarDecl(BO->getLHS()) == Var)
2238 return CheckIncRHS(BO->getRHS());
2239 break;
2240 default:
2241 break;
2242 }
2243 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2244 switch (CE->getOperator()) {
2245 case OO_PlusPlus:
2246 case OO_MinusMinus:
2247 if (GetInitVarDecl(CE->getArg(0)) == Var)
2248 return SetStep(
2249 SemaRef.ActOnIntegerConstant(
2250 CE->getLocStart(),
2251 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2252 false);
2253 break;
2254 case OO_PlusEqual:
2255 case OO_MinusEqual:
2256 if (GetInitVarDecl(CE->getArg(0)) == Var)
2257 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2258 break;
2259 case OO_Equal:
2260 if (GetInitVarDecl(CE->getArg(0)) == Var)
2261 return CheckIncRHS(CE->getArg(1));
2262 break;
2263 default:
2264 break;
2265 }
2266 }
2267 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2268 << S->getSourceRange() << Var;
2269 return true;
2270}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002271
2272/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002273Expr *
2274OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2275 const bool LimitedType) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002276 ExprResult Diff;
2277 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2278 SemaRef.getLangOpts().CPlusPlus) {
2279 // Upper - Lower
2280 Expr *Upper = TestIsLessOp ? UB : LB;
2281 Expr *Lower = TestIsLessOp ? LB : UB;
2282
2283 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2284
2285 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2286 // BuildBinOp already emitted error, this one is to point user to upper
2287 // and lower bound, and to tell what is passed to 'operator-'.
2288 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2289 << Upper->getSourceRange() << Lower->getSourceRange();
2290 return nullptr;
2291 }
2292 }
2293
2294 if (!Diff.isUsable())
2295 return nullptr;
2296
2297 // Upper - Lower [- 1]
2298 if (TestIsStrictOp)
2299 Diff = SemaRef.BuildBinOp(
2300 S, DefaultLoc, BO_Sub, Diff.get(),
2301 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2302 if (!Diff.isUsable())
2303 return nullptr;
2304
2305 // Upper - Lower [- 1] + Step
2306 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2307 Step->IgnoreImplicit());
2308 if (!Diff.isUsable())
2309 return nullptr;
2310
2311 // Parentheses (for dumping/debugging purposes only).
2312 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2313 if (!Diff.isUsable())
2314 return nullptr;
2315
2316 // (Upper - Lower [- 1] + Step) / Step
2317 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2318 Step->IgnoreImplicit());
2319 if (!Diff.isUsable())
2320 return nullptr;
2321
Alexander Musman174b3ca2014-10-06 11:16:29 +00002322 // OpenMP runtime requires 32-bit or 64-bit loop variables.
2323 if (LimitedType) {
2324 auto &C = SemaRef.Context;
2325 QualType Type = Diff.get()->getType();
2326 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2327 if (NewSize != C.getTypeSize(Type)) {
2328 if (NewSize < C.getTypeSize(Type)) {
2329 assert(NewSize == 64 && "incorrect loop var size");
2330 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2331 << InitSrcRange << ConditionSrcRange;
2332 }
2333 QualType NewType = C.getIntTypeForBitwidth(
2334 NewSize, Type->hasSignedIntegerRepresentation());
2335 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2336 Sema::AA_Converting, true);
2337 if (!Diff.isUsable())
2338 return nullptr;
2339 }
2340 }
2341
Alexander Musmana5f070a2014-10-01 06:03:56 +00002342 return Diff.get();
2343}
2344
2345/// \brief Build reference expression to the counter be used for codegen.
2346Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
2347 return DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2348 GetIncrementSrcRange().getBegin(), Var, false,
2349 DefaultLoc, Var->getType(), VK_LValue);
2350}
2351
2352/// \brief Build initization of the counter be used for codegen.
2353Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2354
2355/// \brief Build step of the counter be used for codegen.
2356Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2357
2358/// \brief Iteration space of a single for loop.
2359struct LoopIterationSpace {
2360 /// \brief This expression calculates the number of iterations in the loop.
2361 /// It is always possible to calculate it before starting the loop.
2362 Expr *NumIterations;
2363 /// \brief The loop counter variable.
2364 Expr *CounterVar;
2365 /// \brief This is initializer for the initial value of #CounterVar.
2366 Expr *CounterInit;
2367 /// \brief This is step for the #CounterVar used to generate its update:
2368 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2369 Expr *CounterStep;
2370 /// \brief Should step be subtracted?
2371 bool Subtract;
2372 /// \brief Source range of the loop init.
2373 SourceRange InitSrcRange;
2374 /// \brief Source range of the loop condition.
2375 SourceRange CondSrcRange;
2376 /// \brief Source range of the loop increment.
2377 SourceRange IncSrcRange;
2378};
2379
Alexey Bataev23b69422014-06-18 07:08:49 +00002380} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002381
2382/// \brief Called on a for stmt to check and extract its iteration space
2383/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00002384static bool CheckOpenMPIterationSpace(
2385 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2386 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2387 Expr *NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002388 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2389 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002390 // OpenMP [2.6, Canonical Loop Form]
2391 // for (init-expr; test-expr; incr-expr) structured-block
2392 auto For = dyn_cast_or_null<ForStmt>(S);
2393 if (!For) {
2394 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002395 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2396 << NestedLoopCount << (CurrentNestedLoopCount > 0)
2397 << CurrentNestedLoopCount;
2398 if (NestedLoopCount > 1)
2399 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2400 diag::note_omp_collapse_expr)
2401 << NestedLoopCountExpr->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002402 return true;
2403 }
2404 assert(For->getBody());
2405
2406 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2407
2408 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002409 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002410 if (ISC.CheckInit(Init)) {
2411 return true;
2412 }
2413
2414 bool HasErrors = false;
2415
2416 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002417 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002418
2419 // OpenMP [2.6, Canonical Loop Form]
2420 // Var is one of the following:
2421 // A variable of signed or unsigned integer type.
2422 // For C++, a variable of a random access iterator type.
2423 // For C, a variable of a pointer type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002424 auto VarType = Var->getType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002425 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2426 !VarType->isPointerType() &&
2427 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2428 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2429 << SemaRef.getLangOpts().CPlusPlus;
2430 HasErrors = true;
2431 }
2432
Alexey Bataev4acb8592014-07-07 13:01:15 +00002433 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2434 // Construct
2435 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2436 // parallel for construct is (are) private.
2437 // The loop iteration variable in the associated for-loop of a simd construct
2438 // with just one associated for-loop is linear with a constant-linear-step
2439 // that is the increment of the associated for-loop.
2440 // Exclude loop var from the list of variables with implicitly defined data
2441 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00002442 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002443
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002444 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2445 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00002446 // The loop iteration variable in the associated for-loop of a simd construct
2447 // with just one associated for-loop may be listed in a linear clause with a
2448 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00002449 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2450 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002451 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002452 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2453 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2454 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002455 auto PredeterminedCKind =
2456 isOpenMPSimdDirective(DKind)
2457 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2458 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002459 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002460 DVar.CKind != PredeterminedCKind) ||
Alexander Musmanf82886e2014-09-18 05:12:34 +00002461 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2462 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
2463 DVar.CKind != OMPC_lastprivate)) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00002464 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002465 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00002466 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2467 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002468 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002469 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002470 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002471 // Make the loop iteration variable private (for worksharing constructs),
2472 // linear (for simd directives with the only one associated loop) or
2473 // lastprivate (for simd directives with several collapsed loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00002474 // FIXME: the next check and error message must be removed once the
2475 // capturing of global variables in loops is fixed.
2476 if (DVar.CKind == OMPC_unknown)
2477 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2478 /*FromParent=*/false);
2479 if (!Var->hasLocalStorage() && DVar.CKind == OMPC_unknown) {
2480 SemaRef.Diag(Init->getLocStart(), diag::err_omp_global_loop_var_dsa)
2481 << getOpenMPClauseName(PredeterminedCKind)
2482 << getOpenMPDirectiveName(DKind);
2483 HasErrors = true;
2484 } else
2485 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002486 }
2487
Alexey Bataev7ff55242014-06-19 09:13:45 +00002488 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00002489
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002490 // Check test-expr.
2491 HasErrors |= ISC.CheckCond(For->getCond());
2492
2493 // Check incr-expr.
2494 HasErrors |= ISC.CheckInc(For->getInc());
2495
Alexander Musmana5f070a2014-10-01 06:03:56 +00002496 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002497 return HasErrors;
2498
Alexander Musmana5f070a2014-10-01 06:03:56 +00002499 // Build the loop's iteration space representation.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002500 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2501 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
Alexander Musmana5f070a2014-10-01 06:03:56 +00002502 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2503 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2504 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2505 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2506 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2507 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2508 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2509
2510 HasErrors |= (ResultIterSpace.NumIterations == nullptr ||
2511 ResultIterSpace.CounterVar == nullptr ||
2512 ResultIterSpace.CounterInit == nullptr ||
2513 ResultIterSpace.CounterStep == nullptr);
2514
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002515 return HasErrors;
2516}
2517
Alexander Musmana5f070a2014-10-01 06:03:56 +00002518/// \brief Build a variable declaration for OpenMP loop iteration variable.
2519static VarDecl *BuildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
2520 StringRef Name) {
2521 DeclContext *DC = SemaRef.CurContext;
2522 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2523 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2524 VarDecl *Decl =
2525 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
2526 Decl->setImplicit();
2527 return Decl;
2528}
2529
2530/// \brief Build 'VarRef = Start + Iter * Step'.
2531static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2532 SourceLocation Loc, ExprResult VarRef,
2533 ExprResult Start, ExprResult Iter,
2534 ExprResult Step, bool Subtract) {
2535 // Add parentheses (for debugging purposes only).
2536 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2537 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2538 !Step.isUsable())
2539 return ExprError();
2540
2541 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2542 Step.get()->IgnoreImplicit());
2543 if (!Update.isUsable())
2544 return ExprError();
2545
2546 // Build 'VarRef = Start + Iter * Step'.
2547 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2548 Start.get()->IgnoreImplicit(), Update.get());
2549 if (!Update.isUsable())
2550 return ExprError();
2551
2552 Update = SemaRef.PerformImplicitConversion(
2553 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2554 if (!Update.isUsable())
2555 return ExprError();
2556
2557 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2558 return Update;
2559}
2560
2561/// \brief Convert integer expression \a E to make it have at least \a Bits
2562/// bits.
2563static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2564 Sema &SemaRef) {
2565 if (E == nullptr)
2566 return ExprError();
2567 auto &C = SemaRef.Context;
2568 QualType OldType = E->getType();
2569 unsigned HasBits = C.getTypeSize(OldType);
2570 if (HasBits >= Bits)
2571 return ExprResult(E);
2572 // OK to convert to signed, because new type has more bits than old.
2573 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2574 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2575 true);
2576}
2577
2578/// \brief Check if the given expression \a E is a constant integer that fits
2579/// into \a Bits bits.
2580static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2581 if (E == nullptr)
2582 return false;
2583 llvm::APSInt Result;
2584 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2585 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2586 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002587}
2588
2589/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00002590/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2591/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002592static unsigned
2593CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2594 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002595 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00002596 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002597 unsigned NestedLoopCount = 1;
2598 if (NestedLoopCountExpr) {
2599 // Found 'collapse' clause - calculate collapse number.
2600 llvm::APSInt Result;
2601 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2602 NestedLoopCount = Result.getLimitedValue();
2603 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002604 // This is helper routine for loop directives (e.g., 'for', 'simd',
2605 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00002606 SmallVector<LoopIterationSpace, 4> IterSpaces;
2607 IterSpaces.resize(NestedLoopCount);
2608 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002609 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002610 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev4acb8592014-07-07 13:01:15 +00002611 NestedLoopCount, NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002612 VarsWithImplicitDSA, IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00002613 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002614 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002615 // OpenMP [2.8.1, simd construct, Restrictions]
2616 // All loops associated with the construct must be perfectly nested; that
2617 // is, there must be no intervening code nor any OpenMP directive between
2618 // any two loops.
2619 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002620 }
2621
Alexander Musmana5f070a2014-10-01 06:03:56 +00002622 Built.clear(/* size */ NestedLoopCount);
2623
2624 if (SemaRef.CurContext->isDependentContext())
2625 return NestedLoopCount;
2626
2627 // An example of what is generated for the following code:
2628 //
2629 // #pragma omp simd collapse(2)
2630 // for (i = 0; i < NI; ++i)
2631 // for (j = J0; j < NJ; j+=2) {
2632 // <loop body>
2633 // }
2634 //
2635 // We generate the code below.
2636 // Note: the loop body may be outlined in CodeGen.
2637 // Note: some counters may be C++ classes, operator- is used to find number of
2638 // iterations and operator+= to calculate counter value.
2639 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2640 // or i64 is currently supported).
2641 //
2642 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2643 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2644 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2645 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2646 // // similar updates for vars in clauses (e.g. 'linear')
2647 // <loop body (using local i and j)>
2648 // }
2649 // i = NI; // assign final values of counters
2650 // j = NJ;
2651 //
2652
2653 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2654 // the iteration counts of the collapsed for loops.
2655 auto N0 = IterSpaces[0].NumIterations;
2656 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2657 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2658
2659 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2660 return NestedLoopCount;
2661
2662 auto &C = SemaRef.Context;
2663 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
2664
2665 Scope *CurScope = DSA.getCurScope();
2666 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
2667 auto N = IterSpaces[Cnt].NumIterations;
2668 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
2669 if (LastIteration32.isUsable())
2670 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2671 LastIteration32.get(), N);
2672 if (LastIteration64.isUsable())
2673 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2674 LastIteration64.get(), N);
2675 }
2676
2677 // Choose either the 32-bit or 64-bit version.
2678 ExprResult LastIteration = LastIteration64;
2679 if (LastIteration32.isUsable() &&
2680 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
2681 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
2682 FitsInto(
2683 32 /* Bits */,
2684 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
2685 LastIteration64.get(), SemaRef)))
2686 LastIteration = LastIteration32;
2687
2688 if (!LastIteration.isUsable())
2689 return 0;
2690
2691 // Save the number of iterations.
2692 ExprResult NumIterations = LastIteration;
2693 {
2694 LastIteration = SemaRef.BuildBinOp(
2695 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
2696 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2697 if (!LastIteration.isUsable())
2698 return 0;
2699 }
2700
2701 // Calculate the last iteration number beforehand instead of doing this on
2702 // each iteration. Do not do this if the number of iterations may be kfold-ed.
2703 llvm::APSInt Result;
2704 bool IsConstant =
2705 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
2706 ExprResult CalcLastIteration;
2707 if (!IsConstant) {
2708 SourceLocation SaveLoc;
2709 VarDecl *SaveVar =
2710 BuildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
2711 ".omp.last.iteration");
2712 ExprResult SaveRef = SemaRef.BuildDeclRefExpr(
2713 SaveVar, LastIteration.get()->getType(), VK_LValue, SaveLoc);
2714 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
2715 SaveRef.get(), LastIteration.get());
2716 LastIteration = SaveRef;
2717
2718 // Prepare SaveRef + 1.
2719 NumIterations = SemaRef.BuildBinOp(
2720 CurScope, SaveLoc, BO_Add, SaveRef.get(),
2721 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2722 if (!NumIterations.isUsable())
2723 return 0;
2724 }
2725
2726 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
2727
2728 // Precondition tests if there is at least one iteration (LastIteration > 0).
2729 ExprResult PreCond = SemaRef.BuildBinOp(
2730 CurScope, InitLoc, BO_GT, LastIteration.get(),
2731 SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get());
2732
Alexander Musmanc6388682014-12-15 07:07:06 +00002733 QualType VType = LastIteration.get()->getType();
2734 // Build variables passed into runtime, nesessary for worksharing directives.
2735 ExprResult LB, UB, IL, ST, EUB;
2736 if (isOpenMPWorksharingDirective(DKind)) {
2737 // Lower bound variable, initialized with zero.
2738 VarDecl *LBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
2739 LB = SemaRef.BuildDeclRefExpr(LBDecl, VType, VK_LValue, InitLoc);
2740 SemaRef.AddInitializerToDecl(
2741 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2742 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2743
2744 // Upper bound variable, initialized with last iteration number.
2745 VarDecl *UBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
2746 UB = SemaRef.BuildDeclRefExpr(UBDecl, VType, VK_LValue, InitLoc);
2747 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
2748 /*DirectInit*/ false,
2749 /*TypeMayContainAuto*/ false);
2750
2751 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
2752 // This will be used to implement clause 'lastprivate'.
2753 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
2754 VarDecl *ILDecl = BuildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
2755 IL = SemaRef.BuildDeclRefExpr(ILDecl, Int32Ty, VK_LValue, InitLoc);
2756 SemaRef.AddInitializerToDecl(
2757 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2758 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2759
2760 // Stride variable returned by runtime (we initialize it to 1 by default).
2761 VarDecl *STDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
2762 ST = SemaRef.BuildDeclRefExpr(STDecl, VType, VK_LValue, InitLoc);
2763 SemaRef.AddInitializerToDecl(
2764 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
2765 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2766
2767 // Build expression: UB = min(UB, LastIteration)
2768 // It is nesessary for CodeGen of directives with static scheduling.
2769 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
2770 UB.get(), LastIteration.get());
2771 ExprResult CondOp = SemaRef.ActOnConditionalOp(
2772 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
2773 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
2774 CondOp.get());
2775 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
2776 }
2777
2778 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002779 ExprResult IV;
2780 ExprResult Init;
2781 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002782 VarDecl *IVDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
2783 IV = SemaRef.BuildDeclRefExpr(IVDecl, VType, VK_LValue, InitLoc);
2784 Expr *RHS = isOpenMPWorksharingDirective(DKind)
2785 ? LB.get()
2786 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
2787 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
2788 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002789 }
2790
Alexander Musmanc6388682014-12-15 07:07:06 +00002791 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002792 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00002793 ExprResult Cond =
2794 isOpenMPWorksharingDirective(DKind)
2795 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
2796 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
2797 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002798 // Loop condition with 1 iteration separated (IV < LastIteration)
2799 ExprResult SeparatedCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT,
2800 IV.get(), LastIteration.get());
2801
2802 // Loop increment (IV = IV + 1)
2803 SourceLocation IncLoc;
2804 ExprResult Inc =
2805 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
2806 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
2807 if (!Inc.isUsable())
2808 return 0;
2809 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00002810 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
2811 if (!Inc.isUsable())
2812 return 0;
2813
2814 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
2815 // Used for directives with static scheduling.
2816 ExprResult NextLB, NextUB;
2817 if (isOpenMPWorksharingDirective(DKind)) {
2818 // LB + ST
2819 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
2820 if (!NextLB.isUsable())
2821 return 0;
2822 // LB = LB + ST
2823 NextLB =
2824 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
2825 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
2826 if (!NextLB.isUsable())
2827 return 0;
2828 // UB + ST
2829 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
2830 if (!NextUB.isUsable())
2831 return 0;
2832 // UB = UB + ST
2833 NextUB =
2834 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
2835 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
2836 if (!NextUB.isUsable())
2837 return 0;
2838 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002839
2840 // Build updates and final values of the loop counters.
2841 bool HasErrors = false;
2842 Built.Counters.resize(NestedLoopCount);
2843 Built.Updates.resize(NestedLoopCount);
2844 Built.Finals.resize(NestedLoopCount);
2845 {
2846 ExprResult Div;
2847 // Go from inner nested loop to outer.
2848 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
2849 LoopIterationSpace &IS = IterSpaces[Cnt];
2850 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
2851 // Build: Iter = (IV / Div) % IS.NumIters
2852 // where Div is product of previous iterations' IS.NumIters.
2853 ExprResult Iter;
2854 if (Div.isUsable()) {
2855 Iter =
2856 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
2857 } else {
2858 Iter = IV;
2859 assert((Cnt == (int)NestedLoopCount - 1) &&
2860 "unusable div expected on first iteration only");
2861 }
2862
2863 if (Cnt != 0 && Iter.isUsable())
2864 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
2865 IS.NumIterations);
2866 if (!Iter.isUsable()) {
2867 HasErrors = true;
2868 break;
2869 }
2870
2871 // Build update: IS.CounterVar = IS.Start + Iter * IS.Step
2872 ExprResult Update =
2873 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, IS.CounterVar,
2874 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
2875 if (!Update.isUsable()) {
2876 HasErrors = true;
2877 break;
2878 }
2879
2880 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
2881 ExprResult Final = BuildCounterUpdate(
2882 SemaRef, CurScope, UpdLoc, IS.CounterVar, IS.CounterInit,
2883 IS.NumIterations, IS.CounterStep, IS.Subtract);
2884 if (!Final.isUsable()) {
2885 HasErrors = true;
2886 break;
2887 }
2888
2889 // Build Div for the next iteration: Div <- Div * IS.NumIters
2890 if (Cnt != 0) {
2891 if (Div.isUnset())
2892 Div = IS.NumIterations;
2893 else
2894 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
2895 IS.NumIterations);
2896
2897 // Add parentheses (for debugging purposes only).
2898 if (Div.isUsable())
2899 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
2900 if (!Div.isUsable()) {
2901 HasErrors = true;
2902 break;
2903 }
2904 }
2905 if (!Update.isUsable() || !Final.isUsable()) {
2906 HasErrors = true;
2907 break;
2908 }
2909 // Save results
2910 Built.Counters[Cnt] = IS.CounterVar;
2911 Built.Updates[Cnt] = Update.get();
2912 Built.Finals[Cnt] = Final.get();
2913 }
2914 }
2915
2916 if (HasErrors)
2917 return 0;
2918
2919 // Save results
2920 Built.IterationVarRef = IV.get();
2921 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00002922 Built.NumIterations = NumIterations.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002923 Built.CalcLastIteration = CalcLastIteration.get();
2924 Built.PreCond = PreCond.get();
2925 Built.Cond = Cond.get();
2926 Built.SeparatedCond = SeparatedCond.get();
2927 Built.Init = Init.get();
2928 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00002929 Built.LB = LB.get();
2930 Built.UB = UB.get();
2931 Built.IL = IL.get();
2932 Built.ST = ST.get();
2933 Built.EUB = EUB.get();
2934 Built.NLB = NextLB.get();
2935 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002936
Alexey Bataevabfc0692014-06-25 06:52:00 +00002937 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002938}
2939
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002940static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002941 auto CollapseFilter = [](const OMPClause *C) -> bool {
2942 return C->getClauseKind() == OMPC_collapse;
2943 };
2944 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
2945 Clauses, CollapseFilter);
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002946 if (I)
2947 return cast<OMPCollapseClause>(*I)->getNumForLoops();
2948 return nullptr;
2949}
2950
Alexey Bataev4acb8592014-07-07 13:01:15 +00002951StmtResult Sema::ActOnOpenMPSimdDirective(
2952 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2953 SourceLocation EndLoc,
2954 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002955 OMPLoopDirective::HelperExprs B;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002956 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002957 unsigned NestedLoopCount =
2958 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002959 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00002960 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002961 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002962
Alexander Musmana5f070a2014-10-01 06:03:56 +00002963 assert((CurContext->isDependentContext() || B.builtAll()) &&
2964 "omp simd loop exprs were not built");
2965
Alexander Musman3276a272015-03-21 10:12:56 +00002966 if (!CurContext->isDependentContext()) {
2967 // Finalize the clauses that need pre-built expressions for CodeGen.
2968 for (auto C : Clauses) {
2969 if (auto LC = dyn_cast<OMPLinearClause>(C))
2970 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
2971 B.NumIterations, *this, CurScope))
2972 return StmtError();
2973 }
2974 }
2975
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002976 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00002977 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
2978 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002979}
2980
Alexey Bataev4acb8592014-07-07 13:01:15 +00002981StmtResult Sema::ActOnOpenMPForDirective(
2982 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2983 SourceLocation EndLoc,
2984 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002985 OMPLoopDirective::HelperExprs B;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002986 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002987 unsigned NestedLoopCount =
2988 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002989 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00002990 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00002991 return StmtError();
2992
Alexander Musmana5f070a2014-10-01 06:03:56 +00002993 assert((CurContext->isDependentContext() || B.builtAll()) &&
2994 "omp for loop exprs were not built");
2995
Alexey Bataevf29276e2014-06-18 04:14:57 +00002996 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00002997 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
2998 Clauses, AStmt, B);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002999}
3000
Alexander Musmanf82886e2014-09-18 05:12:34 +00003001StmtResult Sema::ActOnOpenMPForSimdDirective(
3002 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3003 SourceLocation EndLoc,
3004 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003005 OMPLoopDirective::HelperExprs B;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003006 // In presence of clause 'collapse', it will define the nested loops number.
3007 unsigned NestedLoopCount =
3008 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003009 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003010 if (NestedLoopCount == 0)
3011 return StmtError();
3012
Alexander Musmanc6388682014-12-15 07:07:06 +00003013 assert((CurContext->isDependentContext() || B.builtAll()) &&
3014 "omp for simd loop exprs were not built");
3015
Alexander Musmanf82886e2014-09-18 05:12:34 +00003016 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003017 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3018 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003019}
3020
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003021StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3022 Stmt *AStmt,
3023 SourceLocation StartLoc,
3024 SourceLocation EndLoc) {
3025 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3026 auto BaseStmt = AStmt;
3027 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3028 BaseStmt = CS->getCapturedStmt();
3029 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3030 auto S = C->children();
3031 if (!S)
3032 return StmtError();
3033 // All associated statements must be '#pragma omp section' except for
3034 // the first one.
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003035 for (++S; S; ++S) {
3036 auto SectionStmt = *S;
3037 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3038 if (SectionStmt)
3039 Diag(SectionStmt->getLocStart(),
3040 diag::err_omp_sections_substmt_not_section);
3041 return StmtError();
3042 }
3043 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003044 } else {
3045 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3046 return StmtError();
3047 }
3048
3049 getCurFunction()->setHasBranchProtectedScope();
3050
3051 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3052 AStmt);
3053}
3054
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003055StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3056 SourceLocation StartLoc,
3057 SourceLocation EndLoc) {
3058 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3059
3060 getCurFunction()->setHasBranchProtectedScope();
3061
3062 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3063}
3064
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003065StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3066 Stmt *AStmt,
3067 SourceLocation StartLoc,
3068 SourceLocation EndLoc) {
Alexey Bataev74a05c92014-07-15 02:55:09 +00003069 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3070
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003071 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00003072
Alexey Bataev3255bf32015-01-19 05:20:46 +00003073 // OpenMP [2.7.3, single Construct, Restrictions]
3074 // The copyprivate clause must not be used with the nowait clause.
3075 OMPClause *Nowait = nullptr;
3076 OMPClause *Copyprivate = nullptr;
3077 for (auto *Clause : Clauses) {
3078 if (Clause->getClauseKind() == OMPC_nowait)
3079 Nowait = Clause;
3080 else if (Clause->getClauseKind() == OMPC_copyprivate)
3081 Copyprivate = Clause;
3082 if (Copyprivate && Nowait) {
3083 Diag(Copyprivate->getLocStart(),
3084 diag::err_omp_single_copyprivate_with_nowait);
3085 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3086 return StmtError();
3087 }
3088 }
3089
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003090 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3091}
3092
Alexander Musman80c22892014-07-17 08:54:58 +00003093StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3094 SourceLocation StartLoc,
3095 SourceLocation EndLoc) {
3096 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3097
3098 getCurFunction()->setHasBranchProtectedScope();
3099
3100 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3101}
3102
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003103StmtResult
3104Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3105 Stmt *AStmt, SourceLocation StartLoc,
3106 SourceLocation EndLoc) {
3107 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3108
3109 getCurFunction()->setHasBranchProtectedScope();
3110
3111 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3112 AStmt);
3113}
3114
Alexey Bataev4acb8592014-07-07 13:01:15 +00003115StmtResult Sema::ActOnOpenMPParallelForDirective(
3116 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3117 SourceLocation EndLoc,
3118 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3119 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3120 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3121 // 1.2.2 OpenMP Language Terminology
3122 // Structured block - An executable statement with a single entry at the
3123 // top and a single exit at the bottom.
3124 // The point of exit cannot be a branch out of the structured block.
3125 // longjmp() and throw() must not violate the entry/exit criteria.
3126 CS->getCapturedDecl()->setNothrow();
3127
Alexander Musmanc6388682014-12-15 07:07:06 +00003128 OMPLoopDirective::HelperExprs B;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003129 // In presence of clause 'collapse', it will define the nested loops number.
3130 unsigned NestedLoopCount =
3131 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003132 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003133 if (NestedLoopCount == 0)
3134 return StmtError();
3135
Alexander Musmana5f070a2014-10-01 06:03:56 +00003136 assert((CurContext->isDependentContext() || B.builtAll()) &&
3137 "omp parallel for loop exprs were not built");
3138
Alexey Bataev4acb8592014-07-07 13:01:15 +00003139 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003140 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3141 NestedLoopCount, Clauses, AStmt, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003142}
3143
Alexander Musmane4e893b2014-09-23 09:33:00 +00003144StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3145 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3146 SourceLocation EndLoc,
3147 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3148 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3149 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3150 // 1.2.2 OpenMP Language Terminology
3151 // Structured block - An executable statement with a single entry at the
3152 // top and a single exit at the bottom.
3153 // The point of exit cannot be a branch out of the structured block.
3154 // longjmp() and throw() must not violate the entry/exit criteria.
3155 CS->getCapturedDecl()->setNothrow();
3156
Alexander Musmanc6388682014-12-15 07:07:06 +00003157 OMPLoopDirective::HelperExprs B;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003158 // In presence of clause 'collapse', it will define the nested loops number.
3159 unsigned NestedLoopCount =
3160 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003161 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003162 if (NestedLoopCount == 0)
3163 return StmtError();
3164
3165 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003166 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00003167 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003168}
3169
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003170StmtResult
3171Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3172 Stmt *AStmt, SourceLocation StartLoc,
3173 SourceLocation EndLoc) {
3174 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3175 auto BaseStmt = AStmt;
3176 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3177 BaseStmt = CS->getCapturedStmt();
3178 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3179 auto S = C->children();
3180 if (!S)
3181 return StmtError();
3182 // All associated statements must be '#pragma omp section' except for
3183 // the first one.
3184 for (++S; S; ++S) {
3185 auto SectionStmt = *S;
3186 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3187 if (SectionStmt)
3188 Diag(SectionStmt->getLocStart(),
3189 diag::err_omp_parallel_sections_substmt_not_section);
3190 return StmtError();
3191 }
3192 }
3193 } else {
3194 Diag(AStmt->getLocStart(),
3195 diag::err_omp_parallel_sections_not_compound_stmt);
3196 return StmtError();
3197 }
3198
3199 getCurFunction()->setHasBranchProtectedScope();
3200
3201 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3202 Clauses, AStmt);
3203}
3204
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003205StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3206 Stmt *AStmt, SourceLocation StartLoc,
3207 SourceLocation EndLoc) {
3208 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3209 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3210 // 1.2.2 OpenMP Language Terminology
3211 // Structured block - An executable statement with a single entry at the
3212 // top and a single exit at the bottom.
3213 // The point of exit cannot be a branch out of the structured block.
3214 // longjmp() and throw() must not violate the entry/exit criteria.
3215 CS->getCapturedDecl()->setNothrow();
3216
3217 getCurFunction()->setHasBranchProtectedScope();
3218
3219 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3220}
3221
Alexey Bataev68446b72014-07-18 07:47:19 +00003222StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3223 SourceLocation EndLoc) {
3224 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3225}
3226
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003227StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3228 SourceLocation EndLoc) {
3229 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3230}
3231
Alexey Bataev2df347a2014-07-18 10:17:07 +00003232StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3233 SourceLocation EndLoc) {
3234 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3235}
3236
Alexey Bataev6125da92014-07-21 11:26:11 +00003237StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3238 SourceLocation StartLoc,
3239 SourceLocation EndLoc) {
3240 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3241 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3242}
3243
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003244StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3245 SourceLocation StartLoc,
3246 SourceLocation EndLoc) {
3247 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3248
3249 getCurFunction()->setHasBranchProtectedScope();
3250
3251 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3252}
3253
Alexey Bataev1d160b12015-03-13 12:27:31 +00003254namespace {
3255/// \brief Helper class for checking expression in 'omp atomic [update]'
3256/// construct.
3257class OpenMPAtomicUpdateChecker {
3258 /// \brief Error results for atomic update expressions.
3259 enum ExprAnalysisErrorCode {
3260 /// \brief A statement is not an expression statement.
3261 NotAnExpression,
3262 /// \brief Expression is not builtin binary or unary operation.
3263 NotABinaryOrUnaryExpression,
3264 /// \brief Unary operation is not post-/pre- increment/decrement operation.
3265 NotAnUnaryIncDecExpression,
3266 /// \brief An expression is not of scalar type.
3267 NotAScalarType,
3268 /// \brief A binary operation is not an assignment operation.
3269 NotAnAssignmentOp,
3270 /// \brief RHS part of the binary operation is not a binary expression.
3271 NotABinaryExpression,
3272 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
3273 /// expression.
3274 NotABinaryOperator,
3275 /// \brief RHS binary operation does not have reference to the updated LHS
3276 /// part.
3277 NotAnUpdateExpression,
3278 /// \brief No errors is found.
3279 NoError
3280 };
3281 /// \brief Reference to Sema.
3282 Sema &SemaRef;
3283 /// \brief A location for note diagnostics (when error is found).
3284 SourceLocation NoteLoc;
3285 /// \brief Atomic operation supposed to be performed on source expression.
3286 BinaryOperatorKind OpKind;
3287 /// \brief 'x' lvalue part of the source atomic expression.
3288 Expr *X;
3289 /// \brief 'x' rvalue part of the source atomic expression, used in the right
3290 /// hand side of the expression. We need this to properly generate RHS part of
3291 /// the source expression (x = x'rval' binop expr or x = expr binop x'rval').
3292 Expr *XRVal;
3293 /// \brief 'expr' rvalue part of the source atomic expression.
3294 Expr *E;
3295
3296public:
3297 OpenMPAtomicUpdateChecker(Sema &SemaRef)
3298 : SemaRef(SemaRef), OpKind(BO_PtrMemD), X(nullptr), XRVal(nullptr),
3299 E(nullptr) {}
3300 /// \brief Check specified statement that it is suitable for 'atomic update'
3301 /// constructs and extract 'x', 'expr' and Operation from the original
3302 /// expression.
3303 /// \param DiagId Diagnostic which should be emitted if error is found.
3304 /// \param NoteId Diagnostic note for the main error message.
3305 /// \return true if statement is not an update expression, false otherwise.
3306 bool checkStatement(Stmt *S, unsigned DiagId, unsigned NoteId);
3307 /// \brief Return the 'x' lvalue part of the source atomic expression.
3308 Expr *getX() const { return X; }
3309 /// \brief Return the 'x' rvalue part of the source atomic expression, used in
3310 /// the RHS part of the source expression.
3311 Expr *getXRVal() const { return XRVal; }
3312 /// \brief Return the 'expr' rvalue part of the source atomic expression.
3313 Expr *getExpr() const { return E; }
3314 /// \brief Return required atomic operation.
3315 BinaryOperatorKind getOpKind() const {return OpKind;}
3316private:
3317 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId,
3318 unsigned NoteId);
3319};
3320} // namespace
3321
3322bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
3323 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
3324 ExprAnalysisErrorCode ErrorFound = NoError;
3325 SourceLocation ErrorLoc, NoteLoc;
3326 SourceRange ErrorRange, NoteRange;
3327 // Allowed constructs are:
3328 // x = x binop expr;
3329 // x = expr binop x;
3330 if (AtomicBinOp->getOpcode() == BO_Assign) {
3331 X = AtomicBinOp->getLHS();
3332 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
3333 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
3334 if (AtomicInnerBinOp->isMultiplicativeOp() ||
3335 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
3336 AtomicInnerBinOp->isBitwiseOp()) {
3337 OpKind = AtomicInnerBinOp->getOpcode();
3338 auto *LHS = AtomicInnerBinOp->getLHS();
3339 auto *RHS = AtomicInnerBinOp->getRHS();
3340 llvm::FoldingSetNodeID XId, LHSId, RHSId;
3341 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
3342 /*Canonical=*/true);
3343 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
3344 /*Canonical=*/true);
3345 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
3346 /*Canonical=*/true);
3347 if (XId == LHSId) {
3348 E = RHS;
3349 XRVal = LHS;
3350 } else if (XId == RHSId) {
3351 E = LHS;
3352 XRVal = RHS;
3353 } else {
3354 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3355 ErrorRange = AtomicInnerBinOp->getSourceRange();
3356 NoteLoc = X->getExprLoc();
3357 NoteRange = X->getSourceRange();
3358 ErrorFound = NotAnUpdateExpression;
3359 }
3360 } else {
3361 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3362 ErrorRange = AtomicInnerBinOp->getSourceRange();
3363 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
3364 NoteRange = SourceRange(NoteLoc, NoteLoc);
3365 ErrorFound = NotABinaryOperator;
3366 }
3367 } else {
3368 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
3369 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
3370 ErrorFound = NotABinaryExpression;
3371 }
3372 } else {
3373 ErrorLoc = AtomicBinOp->getExprLoc();
3374 ErrorRange = AtomicBinOp->getSourceRange();
3375 NoteLoc = AtomicBinOp->getOperatorLoc();
3376 NoteRange = SourceRange(NoteLoc, NoteLoc);
3377 ErrorFound = NotAnAssignmentOp;
3378 }
3379 if (ErrorFound != NoError) {
3380 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3381 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3382 return true;
3383 } else if (SemaRef.CurContext->isDependentContext())
3384 E = X = XRVal = nullptr;
3385 return false;
3386}
3387
3388bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
3389 unsigned NoteId) {
3390 ExprAnalysisErrorCode ErrorFound = NoError;
3391 SourceLocation ErrorLoc, NoteLoc;
3392 SourceRange ErrorRange, NoteRange;
3393 // Allowed constructs are:
3394 // x++;
3395 // x--;
3396 // ++x;
3397 // --x;
3398 // x binop= expr;
3399 // x = x binop expr;
3400 // x = expr binop x;
3401 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
3402 AtomicBody = AtomicBody->IgnoreParenImpCasts();
3403 if (AtomicBody->getType()->isScalarType() ||
3404 AtomicBody->isInstantiationDependent()) {
3405 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
3406 AtomicBody->IgnoreParenImpCasts())) {
3407 // Check for Compound Assignment Operation
3408 OpKind = BinaryOperator::getOpForCompoundAssignment(
3409 AtomicCompAssignOp->getOpcode());
3410 X = AtomicCompAssignOp->getLHS();
3411 XRVal = SemaRef.PerformImplicitConversion(
3412 X, AtomicCompAssignOp->getComputationLHSType(),
3413 Sema::AA_Casting, /*AllowExplicit=*/true).get();
3414 E = AtomicCompAssignOp->getRHS();
3415 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
3416 AtomicBody->IgnoreParenImpCasts())) {
3417 // Check for Binary Operation
3418 return checkBinaryOperation(AtomicBinOp, DiagId, NoteId);
3419 } else if (auto *AtomicUnaryOp =
3420 // Check for Binary Operation
3421 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
3422 // Check for Unary Operation
3423 if (AtomicUnaryOp->isIncrementDecrementOp()) {
3424 OpKind = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
3425 XRVal = X = AtomicUnaryOp->getSubExpr();
3426 E = SemaRef.ActOnIntegerConstant(AtomicUnaryOp->getOperatorLoc(), 1)
3427 .get();
3428 } else {
3429 ErrorFound = NotAnUnaryIncDecExpression;
3430 ErrorLoc = AtomicUnaryOp->getExprLoc();
3431 ErrorRange = AtomicUnaryOp->getSourceRange();
3432 NoteLoc = AtomicUnaryOp->getOperatorLoc();
3433 NoteRange = SourceRange(NoteLoc, NoteLoc);
3434 }
3435 } else {
3436 ErrorFound = NotABinaryOrUnaryExpression;
3437 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
3438 NoteRange = ErrorRange = AtomicBody->getSourceRange();
3439 }
3440 } else {
3441 ErrorFound = NotAScalarType;
3442 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
3443 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3444 }
3445 } else {
3446 ErrorFound = NotAnExpression;
3447 NoteLoc = ErrorLoc = S->getLocStart();
3448 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3449 }
3450 if (ErrorFound != NoError) {
3451 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3452 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3453 return true;
3454 } else if (SemaRef.CurContext->isDependentContext())
3455 E = X = XRVal = nullptr;
3456 return false;
3457}
3458
Alexey Bataev0162e452014-07-22 10:10:35 +00003459StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3460 Stmt *AStmt,
3461 SourceLocation StartLoc,
3462 SourceLocation EndLoc) {
3463 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003464 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00003465 // 1.2.2 OpenMP Language Terminology
3466 // Structured block - An executable statement with a single entry at the
3467 // top and a single exit at the bottom.
3468 // The point of exit cannot be a branch out of the structured block.
3469 // longjmp() and throw() must not violate the entry/exit criteria.
3470 // TODO further analysis of associated statements and clauses.
Alexey Bataevdea47612014-07-23 07:46:59 +00003471 OpenMPClauseKind AtomicKind = OMPC_unknown;
3472 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003473 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00003474 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00003475 C->getClauseKind() == OMPC_update ||
3476 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00003477 if (AtomicKind != OMPC_unknown) {
3478 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3479 << SourceRange(C->getLocStart(), C->getLocEnd());
3480 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3481 << getOpenMPClauseName(AtomicKind);
3482 } else {
3483 AtomicKind = C->getClauseKind();
3484 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003485 }
3486 }
3487 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003488
Alexey Bataev459dec02014-07-24 06:46:57 +00003489 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00003490 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
3491 Body = EWC->getSubExpr();
3492
Alexey Bataev1d160b12015-03-13 12:27:31 +00003493 BinaryOperatorKind OpKind = BO_PtrMemD;
Alexey Bataev62cec442014-11-18 10:14:22 +00003494 Expr *X = nullptr;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003495 Expr *XRVal = nullptr;
Alexey Bataev62cec442014-11-18 10:14:22 +00003496 Expr *V = nullptr;
3497 Expr *E = nullptr;
3498 // OpenMP [2.12.6, atomic Construct]
3499 // In the next expressions:
3500 // * x and v (as applicable) are both l-value expressions with scalar type.
3501 // * During the execution of an atomic region, multiple syntactic
3502 // occurrences of x must designate the same storage location.
3503 // * Neither of v and expr (as applicable) may access the storage location
3504 // designated by x.
3505 // * Neither of x and expr (as applicable) may access the storage location
3506 // designated by v.
3507 // * expr is an expression with scalar type.
3508 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3509 // * binop, binop=, ++, and -- are not overloaded operators.
3510 // * The expression x binop expr must be numerically equivalent to x binop
3511 // (expr). This requirement is satisfied if the operators in expr have
3512 // precedence greater than binop, or by using parentheses around expr or
3513 // subexpressions of expr.
3514 // * The expression expr binop x must be numerically equivalent to (expr)
3515 // binop x. This requirement is satisfied if the operators in expr have
3516 // precedence equal to or greater than binop, or by using parentheses around
3517 // expr or subexpressions of expr.
3518 // * For forms that allow multiple occurrences of x, the number of times
3519 // that x is evaluated is unspecified.
Alexey Bataevf33eba62014-11-28 07:21:40 +00003520 enum {
3521 NotAnExpression,
3522 NotAnAssignmentOp,
3523 NotAScalarType,
3524 NotAnLValue,
3525 NoError
3526 } ErrorFound = NoError;
Alexey Bataevdea47612014-07-23 07:46:59 +00003527 if (AtomicKind == OMPC_read) {
Alexey Bataev62cec442014-11-18 10:14:22 +00003528 SourceLocation ErrorLoc, NoteLoc;
3529 SourceRange ErrorRange, NoteRange;
3530 // If clause is read:
3531 // v = x;
3532 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3533 auto AtomicBinOp =
3534 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3535 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3536 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3537 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3538 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3539 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3540 if (!X->isLValue() || !V->isLValue()) {
3541 auto NotLValueExpr = X->isLValue() ? V : X;
3542 ErrorFound = NotAnLValue;
3543 ErrorLoc = AtomicBinOp->getExprLoc();
3544 ErrorRange = AtomicBinOp->getSourceRange();
3545 NoteLoc = NotLValueExpr->getExprLoc();
3546 NoteRange = NotLValueExpr->getSourceRange();
3547 }
3548 } else if (!X->isInstantiationDependent() ||
3549 !V->isInstantiationDependent()) {
3550 auto NotScalarExpr =
3551 (X->isInstantiationDependent() || X->getType()->isScalarType())
3552 ? V
3553 : X;
3554 ErrorFound = NotAScalarType;
3555 ErrorLoc = AtomicBinOp->getExprLoc();
3556 ErrorRange = AtomicBinOp->getSourceRange();
3557 NoteLoc = NotScalarExpr->getExprLoc();
3558 NoteRange = NotScalarExpr->getSourceRange();
3559 }
3560 } else {
3561 ErrorFound = NotAnAssignmentOp;
3562 ErrorLoc = AtomicBody->getExprLoc();
3563 ErrorRange = AtomicBody->getSourceRange();
3564 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3565 : AtomicBody->getExprLoc();
3566 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3567 : AtomicBody->getSourceRange();
3568 }
3569 } else {
3570 ErrorFound = NotAnExpression;
3571 NoteLoc = ErrorLoc = Body->getLocStart();
3572 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003573 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003574 if (ErrorFound != NoError) {
3575 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3576 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003577 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3578 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00003579 return StmtError();
3580 } else if (CurContext->isDependentContext())
3581 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00003582 } else if (AtomicKind == OMPC_write) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00003583 SourceLocation ErrorLoc, NoteLoc;
3584 SourceRange ErrorRange, NoteRange;
3585 // If clause is write:
3586 // x = expr;
3587 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3588 auto AtomicBinOp =
3589 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3590 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00003591 X = AtomicBinOp->getLHS();
3592 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00003593 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3594 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
3595 if (!X->isLValue()) {
3596 ErrorFound = NotAnLValue;
3597 ErrorLoc = AtomicBinOp->getExprLoc();
3598 ErrorRange = AtomicBinOp->getSourceRange();
3599 NoteLoc = X->getExprLoc();
3600 NoteRange = X->getSourceRange();
3601 }
3602 } else if (!X->isInstantiationDependent() ||
3603 !E->isInstantiationDependent()) {
3604 auto NotScalarExpr =
3605 (X->isInstantiationDependent() || X->getType()->isScalarType())
3606 ? E
3607 : X;
3608 ErrorFound = NotAScalarType;
3609 ErrorLoc = AtomicBinOp->getExprLoc();
3610 ErrorRange = AtomicBinOp->getSourceRange();
3611 NoteLoc = NotScalarExpr->getExprLoc();
3612 NoteRange = NotScalarExpr->getSourceRange();
3613 }
3614 } else {
3615 ErrorFound = NotAnAssignmentOp;
3616 ErrorLoc = AtomicBody->getExprLoc();
3617 ErrorRange = AtomicBody->getSourceRange();
3618 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3619 : AtomicBody->getExprLoc();
3620 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3621 : AtomicBody->getSourceRange();
3622 }
3623 } else {
3624 ErrorFound = NotAnExpression;
3625 NoteLoc = ErrorLoc = Body->getLocStart();
3626 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003627 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00003628 if (ErrorFound != NoError) {
3629 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
3630 << ErrorRange;
3631 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3632 << NoteRange;
3633 return StmtError();
3634 } else if (CurContext->isDependentContext())
3635 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00003636 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003637 // If clause is update:
3638 // x++;
3639 // x--;
3640 // ++x;
3641 // --x;
3642 // x binop= expr;
3643 // x = x binop expr;
3644 // x = expr binop x;
3645 OpenMPAtomicUpdateChecker Checker(*this);
3646 if (Checker.checkStatement(
3647 Body, (AtomicKind == OMPC_update)
3648 ? diag::err_omp_atomic_update_not_expression_statement
3649 : diag::err_omp_atomic_not_expression_statement,
3650 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00003651 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003652 if (!CurContext->isDependentContext()) {
3653 E = Checker.getExpr();
3654 X = Checker.getX();
3655 XRVal = Checker.getXRVal();
3656 OpKind = Checker.getOpKind();
Alexey Bataev67a4f222014-07-23 10:25:33 +00003657 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003658 } else if (AtomicKind == OMPC_capture) {
3659 if (isa<Expr>(Body) && !isa<BinaryOperator>(Body)) {
3660 Diag(Body->getLocStart(),
3661 diag::err_omp_atomic_capture_not_expression_statement);
3662 return StmtError();
3663 } else if (!isa<Expr>(Body) && !isa<CompoundStmt>(Body)) {
3664 Diag(Body->getLocStart(),
3665 diag::err_omp_atomic_capture_not_compound_statement);
3666 return StmtError();
3667 }
Alexey Bataevdea47612014-07-23 07:46:59 +00003668 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003669
3670 getCurFunction()->setHasBranchProtectedScope();
3671
Alexey Bataev62cec442014-11-18 10:14:22 +00003672 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataev1d160b12015-03-13 12:27:31 +00003673 OpKind, X, XRVal, V, E);
Alexey Bataev0162e452014-07-22 10:10:35 +00003674}
3675
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003676StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
3677 Stmt *AStmt,
3678 SourceLocation StartLoc,
3679 SourceLocation EndLoc) {
3680 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3681
Alexey Bataev13314bf2014-10-09 04:18:56 +00003682 // OpenMP [2.16, Nesting of Regions]
3683 // If specified, a teams construct must be contained within a target
3684 // construct. That target construct must contain no statements or directives
3685 // outside of the teams construct.
3686 if (DSAStack->hasInnerTeamsRegion()) {
3687 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
3688 bool OMPTeamsFound = true;
3689 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
3690 auto I = CS->body_begin();
3691 while (I != CS->body_end()) {
3692 auto OED = dyn_cast<OMPExecutableDirective>(*I);
3693 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
3694 OMPTeamsFound = false;
3695 break;
3696 }
3697 ++I;
3698 }
3699 assert(I != CS->body_end() && "Not found statement");
3700 S = *I;
3701 }
3702 if (!OMPTeamsFound) {
3703 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
3704 Diag(DSAStack->getInnerTeamsRegionLoc(),
3705 diag::note_omp_nested_teams_construct_here);
3706 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
3707 << isa<OMPExecutableDirective>(S);
3708 return StmtError();
3709 }
3710 }
3711
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003712 getCurFunction()->setHasBranchProtectedScope();
3713
3714 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3715}
3716
Alexey Bataev13314bf2014-10-09 04:18:56 +00003717StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
3718 Stmt *AStmt, SourceLocation StartLoc,
3719 SourceLocation EndLoc) {
3720 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3721 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3722 // 1.2.2 OpenMP Language Terminology
3723 // Structured block - An executable statement with a single entry at the
3724 // top and a single exit at the bottom.
3725 // The point of exit cannot be a branch out of the structured block.
3726 // longjmp() and throw() must not violate the entry/exit criteria.
3727 CS->getCapturedDecl()->setNothrow();
3728
3729 getCurFunction()->setHasBranchProtectedScope();
3730
3731 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3732}
3733
Alexey Bataeved09d242014-05-28 05:53:51 +00003734OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003735 SourceLocation StartLoc,
3736 SourceLocation LParenLoc,
3737 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00003738 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003739 switch (Kind) {
3740 case OMPC_if:
3741 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
3742 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00003743 case OMPC_final:
3744 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
3745 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00003746 case OMPC_num_threads:
3747 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
3748 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00003749 case OMPC_safelen:
3750 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
3751 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00003752 case OMPC_collapse:
3753 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
3754 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003755 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00003756 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00003757 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003758 case OMPC_private:
3759 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00003760 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003761 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00003762 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00003763 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00003764 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00003765 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00003766 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00003767 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00003768 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00003769 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00003770 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003771 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00003772 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003773 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00003774 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00003775 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00003776 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00003777 case OMPC_seq_cst:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003778 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003779 llvm_unreachable("Clause is not allowed.");
3780 }
3781 return Res;
3782}
3783
Alexey Bataeved09d242014-05-28 05:53:51 +00003784OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003785 SourceLocation LParenLoc,
3786 SourceLocation EndLoc) {
3787 Expr *ValExpr = Condition;
3788 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
3789 !Condition->isInstantiationDependent() &&
3790 !Condition->containsUnexpandedParameterPack()) {
3791 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00003792 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003793 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00003794 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003795
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003796 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003797 }
3798
3799 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
3800}
3801
Alexey Bataev3778b602014-07-17 07:32:53 +00003802OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
3803 SourceLocation StartLoc,
3804 SourceLocation LParenLoc,
3805 SourceLocation EndLoc) {
3806 Expr *ValExpr = Condition;
3807 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
3808 !Condition->isInstantiationDependent() &&
3809 !Condition->containsUnexpandedParameterPack()) {
3810 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
3811 Condition->getExprLoc(), Condition);
3812 if (Val.isInvalid())
3813 return nullptr;
3814
3815 ValExpr = Val.get();
3816 }
3817
3818 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
3819}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003820ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
3821 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00003822 if (!Op)
3823 return ExprError();
3824
3825 class IntConvertDiagnoser : public ICEConvertDiagnoser {
3826 public:
3827 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00003828 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00003829 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
3830 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00003831 return S.Diag(Loc, diag::err_omp_not_integral) << T;
3832 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003833 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3834 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00003835 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
3836 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003837 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3838 QualType T,
3839 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00003840 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
3841 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003842 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3843 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00003844 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00003845 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00003846 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003847 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3848 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00003849 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
3850 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003851 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3852 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00003853 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00003854 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00003855 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003856 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
3857 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00003858 llvm_unreachable("conversion functions are permitted");
3859 }
3860 } ConvertDiagnoser;
3861 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
3862}
3863
3864OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
3865 SourceLocation StartLoc,
3866 SourceLocation LParenLoc,
3867 SourceLocation EndLoc) {
3868 Expr *ValExpr = NumThreads;
3869 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
Alexey Bataev568a8332014-03-06 06:15:19 +00003870 !NumThreads->containsUnexpandedParameterPack()) {
3871 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
3872 ExprResult Val =
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003873 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
Alexey Bataev568a8332014-03-06 06:15:19 +00003874 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00003875 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00003876
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003877 ValExpr = Val.get();
Alexey Bataev568a8332014-03-06 06:15:19 +00003878
3879 // OpenMP [2.5, Restrictions]
3880 // The num_threads expression must evaluate to a positive integer value.
3881 llvm::APSInt Result;
Alexey Bataeved09d242014-05-28 05:53:51 +00003882 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
3883 !Result.isStrictlyPositive()) {
Alexey Bataev568a8332014-03-06 06:15:19 +00003884 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
3885 << "num_threads" << NumThreads->getSourceRange();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00003886 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00003887 }
3888 }
3889
Alexey Bataeved09d242014-05-28 05:53:51 +00003890 return new (Context)
3891 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00003892}
3893
Alexey Bataev62c87d22014-03-21 04:51:18 +00003894ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
3895 OpenMPClauseKind CKind) {
3896 if (!E)
3897 return ExprError();
3898 if (E->isValueDependent() || E->isTypeDependent() ||
3899 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003900 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00003901 llvm::APSInt Result;
3902 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
3903 if (ICE.isInvalid())
3904 return ExprError();
3905 if (!Result.isStrictlyPositive()) {
3906 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
3907 << getOpenMPClauseName(CKind) << E->getSourceRange();
3908 return ExprError();
3909 }
Alexander Musman09184fe2014-09-30 05:29:28 +00003910 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
3911 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
3912 << E->getSourceRange();
3913 return ExprError();
3914 }
Alexey Bataev62c87d22014-03-21 04:51:18 +00003915 return ICE;
3916}
3917
3918OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
3919 SourceLocation LParenLoc,
3920 SourceLocation EndLoc) {
3921 // OpenMP [2.8.1, simd construct, Description]
3922 // The parameter of the safelen clause must be a constant
3923 // positive integer expression.
3924 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
3925 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00003926 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00003927 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003928 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00003929}
3930
Alexander Musman64d33f12014-06-04 07:53:32 +00003931OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
3932 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00003933 SourceLocation LParenLoc,
3934 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00003935 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00003936 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00003937 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00003938 // The parameter of the collapse clause must be a constant
3939 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00003940 ExprResult NumForLoopsResult =
3941 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
3942 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00003943 return nullptr;
3944 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00003945 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00003946}
3947
Alexey Bataeved09d242014-05-28 05:53:51 +00003948OMPClause *Sema::ActOnOpenMPSimpleClause(
3949 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
3950 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00003951 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003952 switch (Kind) {
3953 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00003954 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00003955 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
3956 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003957 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00003958 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00003959 Res = ActOnOpenMPProcBindClause(
3960 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
3961 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00003962 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003963 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00003964 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00003965 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00003966 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00003967 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00003968 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003969 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003970 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00003971 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00003972 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00003973 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00003974 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00003975 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00003976 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00003977 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00003978 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00003979 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00003980 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00003981 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003982 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00003983 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003984 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00003985 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00003986 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00003987 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00003988 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003989 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003990 llvm_unreachable("Clause is not allowed.");
3991 }
3992 return Res;
3993}
3994
3995OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
3996 SourceLocation KindKwLoc,
3997 SourceLocation StartLoc,
3998 SourceLocation LParenLoc,
3999 SourceLocation EndLoc) {
4000 if (Kind == OMPC_DEFAULT_unknown) {
4001 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004002 static_assert(OMPC_DEFAULT_unknown > 0,
4003 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00004004 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004005 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004006 Values += "'";
4007 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
4008 Values += "'";
4009 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004010 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004011 Values += " or ";
4012 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004013 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004014 break;
4015 default:
4016 Values += Sep;
4017 break;
4018 }
4019 }
4020 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004021 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004022 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004023 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004024 switch (Kind) {
4025 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004026 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004027 break;
4028 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004029 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004030 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004031 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004032 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00004033 break;
4034 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004035 return new (Context)
4036 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004037}
4038
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004039OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
4040 SourceLocation KindKwLoc,
4041 SourceLocation StartLoc,
4042 SourceLocation LParenLoc,
4043 SourceLocation EndLoc) {
4044 if (Kind == OMPC_PROC_BIND_unknown) {
4045 std::string Values;
4046 std::string Sep(", ");
4047 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
4048 Values += "'";
4049 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
4050 Values += "'";
4051 switch (i) {
4052 case OMPC_PROC_BIND_unknown - 2:
4053 Values += " or ";
4054 break;
4055 case OMPC_PROC_BIND_unknown - 1:
4056 break;
4057 default:
4058 Values += Sep;
4059 break;
4060 }
4061 }
4062 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004063 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004064 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004065 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004066 return new (Context)
4067 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004068}
4069
Alexey Bataev56dafe82014-06-20 07:16:17 +00004070OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
4071 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
4072 SourceLocation StartLoc, SourceLocation LParenLoc,
4073 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
4074 SourceLocation EndLoc) {
4075 OMPClause *Res = nullptr;
4076 switch (Kind) {
4077 case OMPC_schedule:
4078 Res = ActOnOpenMPScheduleClause(
4079 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
4080 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
4081 break;
4082 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004083 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004084 case OMPC_num_threads:
4085 case OMPC_safelen:
4086 case OMPC_collapse:
4087 case OMPC_default:
4088 case OMPC_proc_bind:
4089 case OMPC_private:
4090 case OMPC_firstprivate:
4091 case OMPC_lastprivate:
4092 case OMPC_shared:
4093 case OMPC_reduction:
4094 case OMPC_linear:
4095 case OMPC_aligned:
4096 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004097 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004098 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004099 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004100 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004101 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004102 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004103 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004104 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004105 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004106 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004107 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004108 case OMPC_seq_cst:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004109 case OMPC_unknown:
4110 llvm_unreachable("Clause is not allowed.");
4111 }
4112 return Res;
4113}
4114
4115OMPClause *Sema::ActOnOpenMPScheduleClause(
4116 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
4117 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
4118 SourceLocation EndLoc) {
4119 if (Kind == OMPC_SCHEDULE_unknown) {
4120 std::string Values;
4121 std::string Sep(", ");
4122 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
4123 Values += "'";
4124 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
4125 Values += "'";
4126 switch (i) {
4127 case OMPC_SCHEDULE_unknown - 2:
4128 Values += " or ";
4129 break;
4130 case OMPC_SCHEDULE_unknown - 1:
4131 break;
4132 default:
4133 Values += Sep;
4134 break;
4135 }
4136 }
4137 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
4138 << Values << getOpenMPClauseName(OMPC_schedule);
4139 return nullptr;
4140 }
4141 Expr *ValExpr = ChunkSize;
4142 if (ChunkSize) {
4143 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
4144 !ChunkSize->isInstantiationDependent() &&
4145 !ChunkSize->containsUnexpandedParameterPack()) {
4146 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
4147 ExprResult Val =
4148 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
4149 if (Val.isInvalid())
4150 return nullptr;
4151
4152 ValExpr = Val.get();
4153
4154 // OpenMP [2.7.1, Restrictions]
4155 // chunk_size must be a loop invariant integer expression with a positive
4156 // value.
4157 llvm::APSInt Result;
4158 if (ValExpr->isIntegerConstantExpr(Result, Context) &&
4159 Result.isSigned() && !Result.isStrictlyPositive()) {
4160 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
4161 << "schedule" << ChunkSize->getSourceRange();
4162 return nullptr;
4163 }
4164 }
4165 }
4166
4167 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
4168 EndLoc, Kind, ValExpr);
4169}
4170
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004171OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
4172 SourceLocation StartLoc,
4173 SourceLocation EndLoc) {
4174 OMPClause *Res = nullptr;
4175 switch (Kind) {
4176 case OMPC_ordered:
4177 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
4178 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00004179 case OMPC_nowait:
4180 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
4181 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004182 case OMPC_untied:
4183 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
4184 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004185 case OMPC_mergeable:
4186 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
4187 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004188 case OMPC_read:
4189 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
4190 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00004191 case OMPC_write:
4192 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
4193 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004194 case OMPC_update:
4195 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
4196 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00004197 case OMPC_capture:
4198 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
4199 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004200 case OMPC_seq_cst:
4201 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
4202 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004203 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004204 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004205 case OMPC_num_threads:
4206 case OMPC_safelen:
4207 case OMPC_collapse:
4208 case OMPC_schedule:
4209 case OMPC_private:
4210 case OMPC_firstprivate:
4211 case OMPC_lastprivate:
4212 case OMPC_shared:
4213 case OMPC_reduction:
4214 case OMPC_linear:
4215 case OMPC_aligned:
4216 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004217 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004218 case OMPC_default:
4219 case OMPC_proc_bind:
4220 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004221 case OMPC_flush:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004222 case OMPC_unknown:
4223 llvm_unreachable("Clause is not allowed.");
4224 }
4225 return Res;
4226}
4227
4228OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
4229 SourceLocation EndLoc) {
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004230 DSAStack->setOrderedRegion();
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004231 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
4232}
4233
Alexey Bataev236070f2014-06-20 11:19:47 +00004234OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
4235 SourceLocation EndLoc) {
4236 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
4237}
4238
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004239OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
4240 SourceLocation EndLoc) {
4241 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
4242}
4243
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004244OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
4245 SourceLocation EndLoc) {
4246 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
4247}
4248
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004249OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
4250 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004251 return new (Context) OMPReadClause(StartLoc, EndLoc);
4252}
4253
Alexey Bataevdea47612014-07-23 07:46:59 +00004254OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
4255 SourceLocation EndLoc) {
4256 return new (Context) OMPWriteClause(StartLoc, EndLoc);
4257}
4258
Alexey Bataev67a4f222014-07-23 10:25:33 +00004259OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
4260 SourceLocation EndLoc) {
4261 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
4262}
4263
Alexey Bataev459dec02014-07-24 06:46:57 +00004264OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
4265 SourceLocation EndLoc) {
4266 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
4267}
4268
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004269OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
4270 SourceLocation EndLoc) {
4271 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
4272}
4273
Alexey Bataevc5e02582014-06-16 07:08:35 +00004274OMPClause *Sema::ActOnOpenMPVarListClause(
4275 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
4276 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
4277 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
4278 const DeclarationNameInfo &ReductionId) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004279 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004280 switch (Kind) {
4281 case OMPC_private:
4282 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4283 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004284 case OMPC_firstprivate:
4285 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4286 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00004287 case OMPC_lastprivate:
4288 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4289 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00004290 case OMPC_shared:
4291 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
4292 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00004293 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00004294 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
4295 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00004296 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00004297 case OMPC_linear:
4298 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
4299 ColonLoc, EndLoc);
4300 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004301 case OMPC_aligned:
4302 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
4303 ColonLoc, EndLoc);
4304 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004305 case OMPC_copyin:
4306 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
4307 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00004308 case OMPC_copyprivate:
4309 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4310 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004311 case OMPC_flush:
4312 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4313 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004314 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004315 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004316 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004317 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004318 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004319 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004320 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004321 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004322 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004323 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004324 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004325 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004326 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004327 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004328 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004329 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004330 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004331 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004332 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004333 llvm_unreachable("Clause is not allowed.");
4334 }
4335 return Res;
4336}
4337
4338OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
4339 SourceLocation StartLoc,
4340 SourceLocation LParenLoc,
4341 SourceLocation EndLoc) {
4342 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00004343 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00004344 for (auto &RefExpr : VarList) {
4345 assert(RefExpr && "NULL expr in OpenMP private clause.");
4346 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004347 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004348 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004349 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004350 continue;
4351 }
4352
Alexey Bataeved09d242014-05-28 05:53:51 +00004353 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004354 // OpenMP [2.1, C/C++]
4355 // A list item is a variable name.
4356 // OpenMP [2.9.3.3, Restrictions, p.1]
4357 // A variable that is part of another variable (as an array or
4358 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004359 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004360 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004361 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004362 continue;
4363 }
4364 Decl *D = DE->getDecl();
4365 VarDecl *VD = cast<VarDecl>(D);
4366
4367 QualType Type = VD->getType();
4368 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4369 // It will be analyzed later.
4370 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004371 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004372 continue;
4373 }
4374
4375 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4376 // A variable that appears in a private clause must not have an incomplete
4377 // type or a reference type.
4378 if (RequireCompleteType(ELoc, Type,
4379 diag::err_omp_private_incomplete_type)) {
4380 continue;
4381 }
4382 if (Type->isReferenceType()) {
4383 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00004384 << getOpenMPClauseName(OMPC_private) << Type;
4385 bool IsDecl =
4386 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4387 Diag(VD->getLocation(),
4388 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4389 << VD;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004390 continue;
4391 }
4392
4393 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
4394 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004395 // clause requires an accessible, unambiguous default constructor for the
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004396 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00004397 while (Type->isArrayType()) {
4398 Type = cast<ArrayType>(Type.getTypePtr())->getElementType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004399 }
4400
Alexey Bataev758e55e2013-09-06 18:03:48 +00004401 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4402 // in a Construct]
4403 // Variables with the predetermined data-sharing attributes may not be
4404 // listed in data-sharing attributes clauses, except for the cases
4405 // listed below. For these exceptions only, listing a predetermined
4406 // variable in a data-sharing attribute clause is allowed and overrides
4407 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004408 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004409 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004410 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4411 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004412 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004413 continue;
4414 }
4415
Alexey Bataev03b340a2014-10-21 03:16:40 +00004416 // Generate helper private variable and initialize it with the default
4417 // value. The address of the original variable is replaced by the address of
4418 // the new private variable in CodeGen. This new variable is not added to
4419 // IdResolver, so the code in the OpenMP region uses original variable for
4420 // proper diagnostics.
4421 auto VDPrivate =
4422 VarDecl::Create(Context, CurContext, DE->getLocStart(),
4423 DE->getExprLoc(), VD->getIdentifier(), VD->getType(),
4424 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4425 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto*/ false);
4426 if (VDPrivate->isInvalidDecl())
4427 continue;
4428 CurContext->addDecl(VDPrivate);
Alexey Bataev07649fb2014-12-16 08:01:48 +00004429 auto VDPrivateRefExpr =
4430 DeclRefExpr::Create(Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4431 /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004432 /*RefersToEnclosingVariableOrCapture*/ false,
Alexey Bataev07649fb2014-12-16 08:01:48 +00004433 /*NameLoc*/ SourceLocation(), DE->getType(),
4434 /*VK*/ VK_LValue);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004435
Alexey Bataev758e55e2013-09-06 18:03:48 +00004436 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004437 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004438 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004439 }
4440
Alexey Bataeved09d242014-05-28 05:53:51 +00004441 if (Vars.empty())
4442 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004443
Alexey Bataev03b340a2014-10-21 03:16:40 +00004444 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
4445 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004446}
4447
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004448namespace {
4449class DiagsUninitializedSeveretyRAII {
4450private:
4451 DiagnosticsEngine &Diags;
4452 SourceLocation SavedLoc;
4453 bool IsIgnored;
4454
4455public:
4456 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
4457 bool IsIgnored)
4458 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
4459 if (!IsIgnored) {
4460 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
4461 /*Map*/ diag::Severity::Ignored, Loc);
4462 }
4463 }
4464 ~DiagsUninitializedSeveretyRAII() {
4465 if (!IsIgnored)
4466 Diags.popMappings(SavedLoc);
4467 }
4468};
4469}
4470
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004471OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
4472 SourceLocation StartLoc,
4473 SourceLocation LParenLoc,
4474 SourceLocation EndLoc) {
4475 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004476 SmallVector<Expr *, 8> PrivateCopies;
4477 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004478 bool IsImplicitClause =
4479 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
4480 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
4481
Alexey Bataeved09d242014-05-28 05:53:51 +00004482 for (auto &RefExpr : VarList) {
4483 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
4484 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004485 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004486 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004487 PrivateCopies.push_back(nullptr);
4488 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004489 continue;
4490 }
4491
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004492 SourceLocation ELoc =
4493 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004494 // OpenMP [2.1, C/C++]
4495 // A list item is a variable name.
4496 // OpenMP [2.9.3.3, Restrictions, p.1]
4497 // A variable that is part of another variable (as an array or
4498 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004499 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004500 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004501 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004502 continue;
4503 }
4504 Decl *D = DE->getDecl();
4505 VarDecl *VD = cast<VarDecl>(D);
4506
4507 QualType Type = VD->getType();
4508 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4509 // It will be analyzed later.
4510 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004511 PrivateCopies.push_back(nullptr);
4512 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004513 continue;
4514 }
4515
4516 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4517 // A variable that appears in a private clause must not have an incomplete
4518 // type or a reference type.
4519 if (RequireCompleteType(ELoc, Type,
4520 diag::err_omp_firstprivate_incomplete_type)) {
4521 continue;
4522 }
4523 if (Type->isReferenceType()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004524 if (IsImplicitClause) {
4525 Diag(ImplicitClauseLoc,
4526 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
4527 << Type;
4528 Diag(RefExpr->getExprLoc(), diag::note_used_here);
4529 } else {
4530 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4531 << getOpenMPClauseName(OMPC_firstprivate) << Type;
4532 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004533 bool IsDecl =
4534 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4535 Diag(VD->getLocation(),
4536 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4537 << VD;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004538 continue;
4539 }
4540
4541 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
4542 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004543 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004544 // class type.
4545 Type = Context.getBaseElementType(Type);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004546
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004547 // If an implicit firstprivate variable found it was checked already.
4548 if (!IsImplicitClause) {
4549 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004550 Type = Type.getNonReferenceType().getCanonicalType();
4551 bool IsConstant = Type.isConstant(Context);
4552 Type = Context.getBaseElementType(Type);
4553 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
4554 // A list item that specifies a given variable may not appear in more
4555 // than one clause on the same directive, except that a variable may be
4556 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004557 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00004558 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004559 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004560 << getOpenMPClauseName(DVar.CKind)
4561 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004562 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004563 continue;
4564 }
4565
4566 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4567 // in a Construct]
4568 // Variables with the predetermined data-sharing attributes may not be
4569 // listed in data-sharing attributes clauses, except for the cases
4570 // listed below. For these exceptions only, listing a predetermined
4571 // variable in a data-sharing attribute clause is allowed and overrides
4572 // the variable's predetermined data-sharing attributes.
4573 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4574 // in a Construct, C/C++, p.2]
4575 // Variables with const-qualified type having no mutable member may be
4576 // listed in a firstprivate clause, even if they are static data members.
4577 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
4578 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
4579 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004580 << getOpenMPClauseName(DVar.CKind)
4581 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004582 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004583 continue;
4584 }
4585
Alexey Bataevf29276e2014-06-18 04:14:57 +00004586 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004587 // OpenMP [2.9.3.4, Restrictions, p.2]
4588 // A list item that is private within a parallel region must not appear
4589 // in a firstprivate clause on a worksharing construct if any of the
4590 // worksharing regions arising from the worksharing construct ever bind
4591 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00004592 if (isOpenMPWorksharingDirective(CurrDir) &&
4593 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004594 DVar = DSAStack->getImplicitDSA(VD, true);
4595 if (DVar.CKind != OMPC_shared &&
4596 (isOpenMPParallelDirective(DVar.DKind) ||
4597 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00004598 Diag(ELoc, diag::err_omp_required_access)
4599 << getOpenMPClauseName(OMPC_firstprivate)
4600 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004601 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004602 continue;
4603 }
4604 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004605 // OpenMP [2.9.3.4, Restrictions, p.3]
4606 // A list item that appears in a reduction clause of a parallel construct
4607 // must not appear in a firstprivate clause on a worksharing or task
4608 // construct if any of the worksharing or task regions arising from the
4609 // worksharing or task construct ever bind to any of the parallel regions
4610 // arising from the parallel construct.
4611 // OpenMP [2.9.3.4, Restrictions, p.4]
4612 // A list item that appears in a reduction clause in worksharing
4613 // construct must not appear in a firstprivate clause in a task construct
4614 // encountered during execution of any of the worksharing regions arising
4615 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004616 if (CurrDir == OMPD_task) {
4617 DVar =
4618 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
4619 [](OpenMPDirectiveKind K) -> bool {
4620 return isOpenMPParallelDirective(K) ||
4621 isOpenMPWorksharingDirective(K);
4622 },
4623 false);
4624 if (DVar.CKind == OMPC_reduction &&
4625 (isOpenMPParallelDirective(DVar.DKind) ||
4626 isOpenMPWorksharingDirective(DVar.DKind))) {
4627 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
4628 << getOpenMPDirectiveName(DVar.DKind);
4629 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4630 continue;
4631 }
4632 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004633 }
4634
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004635 Type = Type.getUnqualifiedType();
4636 auto VDPrivate = VarDecl::Create(Context, CurContext, DE->getLocStart(),
4637 ELoc, VD->getIdentifier(), VD->getType(),
4638 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4639 // Generate helper private variable and initialize it with the value of the
4640 // original variable. The address of the original variable is replaced by
4641 // the address of the new private variable in the CodeGen. This new variable
4642 // is not added to IdResolver, so the code in the OpenMP region uses
4643 // original variable for proper diagnostics and variable capturing.
4644 Expr *VDInitRefExpr = nullptr;
4645 // For arrays generate initializer for single element and replace it by the
4646 // original array element in CodeGen.
4647 if (DE->getType()->isArrayType()) {
4648 auto VDInit = VarDecl::Create(Context, CurContext, DE->getLocStart(),
4649 ELoc, VD->getIdentifier(), Type,
4650 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4651 CurContext->addHiddenDecl(VDInit);
4652 VDInitRefExpr = DeclRefExpr::Create(
4653 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4654 /*TemplateKWLoc*/ SourceLocation(), VDInit,
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004655 /*RefersToEnclosingVariableOrCapture*/ true, ELoc, Type,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004656 /*VK*/ VK_LValue);
4657 VDInit->setIsUsed();
4658 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
4659 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDInit);
4660 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
4661
4662 InitializationSequence InitSeq(*this, Entity, Kind, Init);
4663 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
4664 if (Result.isInvalid())
4665 VDPrivate->setInvalidDecl();
4666 else
4667 VDPrivate->setInit(Result.getAs<Expr>());
4668 } else {
Alexey Bataevf841bd92014-12-16 07:00:22 +00004669 AddInitializerToDecl(
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004670 VDPrivate,
4671 DefaultLvalueConversion(
4672 DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
4673 SourceLocation(), DE->getDecl(),
4674 /*RefersToEnclosingVariableOrCapture=*/true,
4675 DE->getExprLoc(), DE->getType(),
4676 /*VK=*/VK_LValue)).get(),
Alexey Bataevf841bd92014-12-16 07:00:22 +00004677 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004678 }
4679 if (VDPrivate->isInvalidDecl()) {
4680 if (IsImplicitClause) {
4681 Diag(DE->getExprLoc(),
4682 diag::note_omp_task_predetermined_firstprivate_here);
4683 }
4684 continue;
4685 }
4686 CurContext->addDecl(VDPrivate);
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004687 auto VDPrivateRefExpr =
4688 DeclRefExpr::Create(Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4689 /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
4690 /*RefersToEnclosingVariableOrCapture*/ false,
4691 DE->getLocStart(), DE->getType(),
4692 /*VK*/ VK_LValue);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004693 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
4694 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004695 PrivateCopies.push_back(VDPrivateRefExpr);
4696 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004697 }
4698
Alexey Bataeved09d242014-05-28 05:53:51 +00004699 if (Vars.empty())
4700 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004701
4702 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004703 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004704}
4705
Alexander Musman1bb328c2014-06-04 13:06:39 +00004706OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
4707 SourceLocation StartLoc,
4708 SourceLocation LParenLoc,
4709 SourceLocation EndLoc) {
4710 SmallVector<Expr *, 8> Vars;
4711 for (auto &RefExpr : VarList) {
4712 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
4713 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4714 // It will be analyzed later.
4715 Vars.push_back(RefExpr);
4716 continue;
4717 }
4718
4719 SourceLocation ELoc = RefExpr->getExprLoc();
4720 // OpenMP [2.1, C/C++]
4721 // A list item is a variable name.
4722 // OpenMP [2.14.3.5, Restrictions, p.1]
4723 // A variable that is part of another variable (as an array or structure
4724 // element) cannot appear in a lastprivate clause.
4725 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4726 if (!DE || !isa<VarDecl>(DE->getDecl())) {
4727 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4728 continue;
4729 }
4730 Decl *D = DE->getDecl();
4731 VarDecl *VD = cast<VarDecl>(D);
4732
4733 QualType Type = VD->getType();
4734 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4735 // It will be analyzed later.
4736 Vars.push_back(DE);
4737 continue;
4738 }
4739
4740 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
4741 // A variable that appears in a lastprivate clause must not have an
4742 // incomplete type or a reference type.
4743 if (RequireCompleteType(ELoc, Type,
4744 diag::err_omp_lastprivate_incomplete_type)) {
4745 continue;
4746 }
4747 if (Type->isReferenceType()) {
4748 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4749 << getOpenMPClauseName(OMPC_lastprivate) << Type;
4750 bool IsDecl =
4751 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4752 Diag(VD->getLocation(),
4753 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4754 << VD;
4755 continue;
4756 }
4757
4758 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4759 // in a Construct]
4760 // Variables with the predetermined data-sharing attributes may not be
4761 // listed in data-sharing attributes clauses, except for the cases
4762 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004763 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00004764 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
4765 DVar.CKind != OMPC_firstprivate &&
4766 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4767 Diag(ELoc, diag::err_omp_wrong_dsa)
4768 << getOpenMPClauseName(DVar.CKind)
4769 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004770 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00004771 continue;
4772 }
4773
Alexey Bataevf29276e2014-06-18 04:14:57 +00004774 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
4775 // OpenMP [2.14.3.5, Restrictions, p.2]
4776 // A list item that is private within a parallel region, or that appears in
4777 // the reduction clause of a parallel construct, must not appear in a
4778 // lastprivate clause on a worksharing construct if any of the corresponding
4779 // worksharing regions ever binds to any of the corresponding parallel
4780 // regions.
Alexey Bataev549210e2014-06-24 04:39:47 +00004781 if (isOpenMPWorksharingDirective(CurrDir) &&
4782 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004783 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004784 if (DVar.CKind != OMPC_shared) {
4785 Diag(ELoc, diag::err_omp_required_access)
4786 << getOpenMPClauseName(OMPC_lastprivate)
4787 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004788 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004789 continue;
4790 }
4791 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00004792 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00004793 // A variable of class type (or array thereof) that appears in a
4794 // lastprivate clause requires an accessible, unambiguous default
4795 // constructor for the class type, unless the list item is also specified
4796 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00004797 // A variable of class type (or array thereof) that appears in a
4798 // lastprivate clause requires an accessible, unambiguous copy assignment
4799 // operator for the class type.
4800 while (Type.getNonReferenceType()->isArrayType())
4801 Type = cast<ArrayType>(Type.getNonReferenceType().getTypePtr())
4802 ->getElementType();
4803 CXXRecordDecl *RD = getLangOpts().CPlusPlus
4804 ? Type.getNonReferenceType()->getAsCXXRecordDecl()
4805 : nullptr;
Alexey Bataev23b69422014-06-18 07:08:49 +00004806 // FIXME This code must be replaced by actual copying and destructing of the
4807 // lastprivate variable.
Alexander Musman1bb328c2014-06-04 13:06:39 +00004808 if (RD) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00004809 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
4810 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004811 if (MD) {
4812 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
4813 MD->isDeleted()) {
4814 Diag(ELoc, diag::err_omp_required_method)
4815 << getOpenMPClauseName(OMPC_lastprivate) << 2;
4816 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
4817 VarDecl::DeclarationOnly;
4818 Diag(VD->getLocation(),
4819 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4820 << VD;
4821 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
4822 continue;
4823 }
4824 MarkFunctionReferenced(ELoc, MD);
4825 DiagnoseUseOfDecl(MD, ELoc);
Alexander Musman1bb328c2014-06-04 13:06:39 +00004826 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00004827
4828 CXXDestructorDecl *DD = RD->getDestructor();
4829 if (DD) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00004830 PartialDiagnostic PD =
4831 PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
Alexander Musman1bb328c2014-06-04 13:06:39 +00004832 if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
4833 DD->isDeleted()) {
4834 Diag(ELoc, diag::err_omp_required_method)
4835 << getOpenMPClauseName(OMPC_lastprivate) << 4;
4836 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
4837 VarDecl::DeclarationOnly;
4838 Diag(VD->getLocation(),
4839 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4840 << VD;
4841 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
4842 continue;
4843 }
4844 MarkFunctionReferenced(ELoc, DD);
4845 DiagnoseUseOfDecl(DD, ELoc);
4846 }
4847 }
4848
Alexey Bataevf29276e2014-06-18 04:14:57 +00004849 if (DVar.CKind != OMPC_firstprivate)
4850 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00004851 Vars.push_back(DE);
4852 }
4853
4854 if (Vars.empty())
4855 return nullptr;
4856
4857 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
4858 Vars);
4859}
4860
Alexey Bataev758e55e2013-09-06 18:03:48 +00004861OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
4862 SourceLocation StartLoc,
4863 SourceLocation LParenLoc,
4864 SourceLocation EndLoc) {
4865 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00004866 for (auto &RefExpr : VarList) {
4867 assert(RefExpr && "NULL expr in OpenMP shared clause.");
4868 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00004869 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004870 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004871 continue;
4872 }
4873
Alexey Bataeved09d242014-05-28 05:53:51 +00004874 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00004875 // OpenMP [2.1, C/C++]
4876 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00004877 // OpenMP [2.14.3.2, Restrictions, p.1]
4878 // A variable that is part of another variable (as an array or structure
4879 // element) cannot appear in a shared unless it is a static data member
4880 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00004881 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004882 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004883 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00004884 continue;
4885 }
4886 Decl *D = DE->getDecl();
4887 VarDecl *VD = cast<VarDecl>(D);
4888
4889 QualType Type = VD->getType();
4890 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4891 // It will be analyzed later.
4892 Vars.push_back(DE);
4893 continue;
4894 }
4895
4896 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4897 // in a Construct]
4898 // Variables with the predetermined data-sharing attributes may not be
4899 // listed in data-sharing attributes clauses, except for the cases
4900 // listed below. For these exceptions only, listing a predetermined
4901 // variable in a data-sharing attribute clause is allowed and overrides
4902 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004903 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00004904 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
4905 DVar.RefExpr) {
4906 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4907 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004908 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004909 continue;
4910 }
4911
4912 DSAStack->addDSA(VD, DE, OMPC_shared);
4913 Vars.push_back(DE);
4914 }
4915
Alexey Bataeved09d242014-05-28 05:53:51 +00004916 if (Vars.empty())
4917 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00004918
4919 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
4920}
4921
Alexey Bataevc5e02582014-06-16 07:08:35 +00004922namespace {
4923class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
4924 DSAStackTy *Stack;
4925
4926public:
4927 bool VisitDeclRefExpr(DeclRefExpr *E) {
4928 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004929 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00004930 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
4931 return false;
4932 if (DVar.CKind != OMPC_unknown)
4933 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00004934 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004935 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004936 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00004937 return true;
4938 return false;
4939 }
4940 return false;
4941 }
4942 bool VisitStmt(Stmt *S) {
4943 for (auto Child : S->children()) {
4944 if (Child && Visit(Child))
4945 return true;
4946 }
4947 return false;
4948 }
Alexey Bataev23b69422014-06-18 07:08:49 +00004949 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00004950};
Alexey Bataev23b69422014-06-18 07:08:49 +00004951} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00004952
4953OMPClause *Sema::ActOnOpenMPReductionClause(
4954 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
4955 SourceLocation ColonLoc, SourceLocation EndLoc,
4956 CXXScopeSpec &ReductionIdScopeSpec,
4957 const DeclarationNameInfo &ReductionId) {
4958 // TODO: Allow scope specification search when 'declare reduction' is
4959 // supported.
4960 assert(ReductionIdScopeSpec.isEmpty() &&
4961 "No support for scoped reduction identifiers yet.");
4962
4963 auto DN = ReductionId.getName();
4964 auto OOK = DN.getCXXOverloadedOperator();
4965 BinaryOperatorKind BOK = BO_Comma;
4966
4967 // OpenMP [2.14.3.6, reduction clause]
4968 // C
4969 // reduction-identifier is either an identifier or one of the following
4970 // operators: +, -, *, &, |, ^, && and ||
4971 // C++
4972 // reduction-identifier is either an id-expression or one of the following
4973 // operators: +, -, *, &, |, ^, && and ||
4974 // FIXME: Only 'min' and 'max' identifiers are supported for now.
4975 switch (OOK) {
4976 case OO_Plus:
4977 case OO_Minus:
4978 BOK = BO_AddAssign;
4979 break;
4980 case OO_Star:
4981 BOK = BO_MulAssign;
4982 break;
4983 case OO_Amp:
4984 BOK = BO_AndAssign;
4985 break;
4986 case OO_Pipe:
4987 BOK = BO_OrAssign;
4988 break;
4989 case OO_Caret:
4990 BOK = BO_XorAssign;
4991 break;
4992 case OO_AmpAmp:
4993 BOK = BO_LAnd;
4994 break;
4995 case OO_PipePipe:
4996 BOK = BO_LOr;
4997 break;
4998 default:
4999 if (auto II = DN.getAsIdentifierInfo()) {
5000 if (II->isStr("max"))
5001 BOK = BO_GT;
5002 else if (II->isStr("min"))
5003 BOK = BO_LT;
5004 }
5005 break;
5006 }
5007 SourceRange ReductionIdRange;
5008 if (ReductionIdScopeSpec.isValid()) {
5009 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
5010 }
5011 ReductionIdRange.setEnd(ReductionId.getEndLoc());
5012 if (BOK == BO_Comma) {
5013 // Not allowed reduction identifier is found.
5014 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
5015 << ReductionIdRange;
5016 return nullptr;
5017 }
5018
5019 SmallVector<Expr *, 8> Vars;
5020 for (auto RefExpr : VarList) {
5021 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
5022 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5023 // It will be analyzed later.
5024 Vars.push_back(RefExpr);
5025 continue;
5026 }
5027
5028 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5029 RefExpr->isInstantiationDependent() ||
5030 RefExpr->containsUnexpandedParameterPack()) {
5031 // It will be analyzed later.
5032 Vars.push_back(RefExpr);
5033 continue;
5034 }
5035
5036 auto ELoc = RefExpr->getExprLoc();
5037 auto ERange = RefExpr->getSourceRange();
5038 // OpenMP [2.1, C/C++]
5039 // A list item is a variable or array section, subject to the restrictions
5040 // specified in Section 2.4 on page 42 and in each of the sections
5041 // describing clauses and directives for which a list appears.
5042 // OpenMP [2.14.3.3, Restrictions, p.1]
5043 // A variable that is part of another variable (as an array or
5044 // structure element) cannot appear in a private clause.
5045 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
5046 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5047 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
5048 continue;
5049 }
5050 auto D = DE->getDecl();
5051 auto VD = cast<VarDecl>(D);
5052 auto Type = VD->getType();
5053 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5054 // A variable that appears in a private clause must not have an incomplete
5055 // type or a reference type.
5056 if (RequireCompleteType(ELoc, Type,
5057 diag::err_omp_reduction_incomplete_type))
5058 continue;
5059 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5060 // Arrays may not appear in a reduction clause.
5061 if (Type.getNonReferenceType()->isArrayType()) {
5062 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
5063 bool IsDecl =
5064 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5065 Diag(VD->getLocation(),
5066 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5067 << VD;
5068 continue;
5069 }
5070 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5071 // A list item that appears in a reduction clause must not be
5072 // const-qualified.
5073 if (Type.getNonReferenceType().isConstant(Context)) {
5074 Diag(ELoc, diag::err_omp_const_variable)
5075 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
5076 bool IsDecl =
5077 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5078 Diag(VD->getLocation(),
5079 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5080 << VD;
5081 continue;
5082 }
5083 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
5084 // If a list-item is a reference type then it must bind to the same object
5085 // for all threads of the team.
5086 VarDecl *VDDef = VD->getDefinition();
5087 if (Type->isReferenceType() && VDDef) {
5088 DSARefChecker Check(DSAStack);
5089 if (Check.Visit(VDDef->getInit())) {
5090 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
5091 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
5092 continue;
5093 }
5094 }
5095 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5096 // The type of a list item that appears in a reduction clause must be valid
5097 // for the reduction-identifier. For a max or min reduction in C, the type
5098 // of the list item must be an allowed arithmetic data type: char, int,
5099 // float, double, or _Bool, possibly modified with long, short, signed, or
5100 // unsigned. For a max or min reduction in C++, the type of the list item
5101 // must be an allowed arithmetic data type: char, wchar_t, int, float,
5102 // double, or bool, possibly modified with long, short, signed, or unsigned.
5103 if ((BOK == BO_GT || BOK == BO_LT) &&
5104 !(Type->isScalarType() ||
5105 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
5106 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
5107 << getLangOpts().CPlusPlus;
5108 bool IsDecl =
5109 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5110 Diag(VD->getLocation(),
5111 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5112 << VD;
5113 continue;
5114 }
5115 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
5116 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
5117 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
5118 bool IsDecl =
5119 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5120 Diag(VD->getLocation(),
5121 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5122 << VD;
5123 continue;
5124 }
5125 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
5126 getDiagnostics().setSuppressAllDiagnostics(true);
5127 ExprResult ReductionOp =
5128 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
5129 RefExpr, RefExpr);
5130 getDiagnostics().setSuppressAllDiagnostics(Suppress);
5131 if (ReductionOp.isInvalid()) {
5132 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
Alexey Bataev23b69422014-06-18 07:08:49 +00005133 << ReductionIdRange;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005134 bool IsDecl =
5135 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5136 Diag(VD->getLocation(),
5137 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5138 << VD;
5139 continue;
5140 }
5141
5142 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5143 // in a Construct]
5144 // Variables with the predetermined data-sharing attributes may not be
5145 // listed in data-sharing attributes clauses, except for the cases
5146 // listed below. For these exceptions only, listing a predetermined
5147 // variable in a data-sharing attribute clause is allowed and overrides
5148 // the variable's predetermined data-sharing attributes.
5149 // OpenMP [2.14.3.6, Restrictions, p.3]
5150 // Any number of reduction clauses can be specified on the directive,
5151 // but a list item can appear only once in the reduction clauses for that
5152 // directive.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005153 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005154 if (DVar.CKind == OMPC_reduction) {
5155 Diag(ELoc, diag::err_omp_once_referenced)
5156 << getOpenMPClauseName(OMPC_reduction);
5157 if (DVar.RefExpr) {
5158 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
5159 }
5160 } else if (DVar.CKind != OMPC_unknown) {
5161 Diag(ELoc, diag::err_omp_wrong_dsa)
5162 << getOpenMPClauseName(DVar.CKind)
5163 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005164 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005165 continue;
5166 }
5167
5168 // OpenMP [2.14.3.6, Restrictions, p.1]
5169 // A list item that appears in a reduction clause of a worksharing
5170 // construct must be shared in the parallel regions to which any of the
5171 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf29276e2014-06-18 04:14:57 +00005172 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataev549210e2014-06-24 04:39:47 +00005173 if (isOpenMPWorksharingDirective(CurrDir) &&
5174 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005175 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005176 if (DVar.CKind != OMPC_shared) {
5177 Diag(ELoc, diag::err_omp_required_access)
5178 << getOpenMPClauseName(OMPC_reduction)
5179 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005180 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005181 continue;
5182 }
5183 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00005184
5185 CXXRecordDecl *RD = getLangOpts().CPlusPlus
5186 ? Type.getNonReferenceType()->getAsCXXRecordDecl()
5187 : nullptr;
Alexey Bataev23b69422014-06-18 07:08:49 +00005188 // FIXME This code must be replaced by actual constructing/destructing of
5189 // the reduction variable.
Alexey Bataevc5e02582014-06-16 07:08:35 +00005190 if (RD) {
5191 CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
5192 PartialDiagnostic PD =
5193 PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
Alexey Bataev23b69422014-06-18 07:08:49 +00005194 if (!CD ||
5195 CheckConstructorAccess(ELoc, CD,
5196 InitializedEntity::InitializeTemporary(Type),
5197 CD->getAccess(), PD) == AR_inaccessible ||
Alexey Bataevc5e02582014-06-16 07:08:35 +00005198 CD->isDeleted()) {
5199 Diag(ELoc, diag::err_omp_required_method)
5200 << getOpenMPClauseName(OMPC_reduction) << 0;
5201 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5202 VarDecl::DeclarationOnly;
5203 Diag(VD->getLocation(),
5204 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5205 << VD;
5206 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5207 continue;
5208 }
5209 MarkFunctionReferenced(ELoc, CD);
5210 DiagnoseUseOfDecl(CD, ELoc);
5211
5212 CXXDestructorDecl *DD = RD->getDestructor();
5213 if (DD) {
5214 if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
5215 DD->isDeleted()) {
5216 Diag(ELoc, diag::err_omp_required_method)
5217 << getOpenMPClauseName(OMPC_reduction) << 4;
5218 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5219 VarDecl::DeclarationOnly;
5220 Diag(VD->getLocation(),
5221 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5222 << VD;
5223 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5224 continue;
5225 }
5226 MarkFunctionReferenced(ELoc, DD);
5227 DiagnoseUseOfDecl(DD, ELoc);
5228 }
5229 }
5230
5231 DSAStack->addDSA(VD, DE, OMPC_reduction);
5232 Vars.push_back(DE);
5233 }
5234
5235 if (Vars.empty())
5236 return nullptr;
5237
5238 return OMPReductionClause::Create(
5239 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
5240 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId);
5241}
5242
Alexander Musman8dba6642014-04-22 13:09:42 +00005243OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
5244 SourceLocation StartLoc,
5245 SourceLocation LParenLoc,
5246 SourceLocation ColonLoc,
5247 SourceLocation EndLoc) {
5248 SmallVector<Expr *, 8> Vars;
Alexander Musman3276a272015-03-21 10:12:56 +00005249 SmallVector<Expr *, 8> Inits;
Alexey Bataeved09d242014-05-28 05:53:51 +00005250 for (auto &RefExpr : VarList) {
5251 assert(RefExpr && "NULL expr in OpenMP linear clause.");
5252 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00005253 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005254 Vars.push_back(RefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00005255 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005256 continue;
5257 }
5258
5259 // OpenMP [2.14.3.7, linear clause]
5260 // A list item that appears in a linear clause is subject to the private
5261 // clause semantics described in Section 2.14.3.3 on page 159 except as
5262 // noted. In addition, the value of the new list item on each iteration
5263 // of the associated loop(s) corresponds to the value of the original
5264 // list item before entering the construct plus the logical number of
5265 // the iteration times linear-step.
5266
Alexey Bataeved09d242014-05-28 05:53:51 +00005267 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00005268 // OpenMP [2.1, C/C++]
5269 // A list item is a variable name.
5270 // OpenMP [2.14.3.3, Restrictions, p.1]
5271 // A variable that is part of another variable (as an array or
5272 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005273 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005274 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005275 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00005276 continue;
5277 }
5278
5279 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5280
5281 // OpenMP [2.14.3.7, linear clause]
5282 // A list-item cannot appear in more than one linear clause.
5283 // A list-item that appears in a linear clause cannot appear in any
5284 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005285 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00005286 if (DVar.RefExpr) {
5287 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5288 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005289 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00005290 continue;
5291 }
5292
5293 QualType QType = VD->getType();
5294 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
5295 // It will be analyzed later.
5296 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005297 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005298 continue;
5299 }
5300
5301 // A variable must not have an incomplete type or a reference type.
5302 if (RequireCompleteType(ELoc, QType,
5303 diag::err_omp_linear_incomplete_type)) {
5304 continue;
5305 }
5306 if (QType->isReferenceType()) {
5307 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5308 << getOpenMPClauseName(OMPC_linear) << QType;
5309 bool IsDecl =
5310 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5311 Diag(VD->getLocation(),
5312 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5313 << VD;
5314 continue;
5315 }
5316
5317 // A list item must not be const-qualified.
5318 if (QType.isConstant(Context)) {
5319 Diag(ELoc, diag::err_omp_const_variable)
5320 << getOpenMPClauseName(OMPC_linear);
5321 bool IsDecl =
5322 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5323 Diag(VD->getLocation(),
5324 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5325 << VD;
5326 continue;
5327 }
5328
5329 // A list item must be of integral or pointer type.
5330 QType = QType.getUnqualifiedType().getCanonicalType();
5331 const Type *Ty = QType.getTypePtrOrNull();
5332 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
5333 !Ty->isPointerType())) {
5334 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
5335 bool IsDecl =
5336 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5337 Diag(VD->getLocation(),
5338 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5339 << VD;
5340 continue;
5341 }
5342
Alexander Musman3276a272015-03-21 10:12:56 +00005343 // Build var to save initial value.
5344 VarDecl *Init = BuildVarDecl(*this, ELoc, DE->getType(), ".linear.start");
5345 AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
5346 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
5347 CurContext->addDecl(Init);
5348 Init->setIsUsed();
5349 auto InitRef = DeclRefExpr::Create(
5350 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
5351 /*TemplateKWLoc*/ SourceLocation(), Init,
5352 /*isEnclosingLocal*/ false, DE->getLocStart(), DE->getType(),
5353 /*VK*/ VK_LValue);
Alexander Musman8dba6642014-04-22 13:09:42 +00005354 DSAStack->addDSA(VD, DE, OMPC_linear);
5355 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005356 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00005357 }
5358
5359 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005360 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005361
5362 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00005363 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005364 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5365 !Step->isInstantiationDependent() &&
5366 !Step->containsUnexpandedParameterPack()) {
5367 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005368 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00005369 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005370 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005371 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00005372
Alexander Musman3276a272015-03-21 10:12:56 +00005373 // Build var to save the step value.
5374 VarDecl *SaveVar =
5375 BuildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
5376 CurContext->addDecl(SaveVar);
5377 SaveVar->setIsUsed();
5378 ExprResult SaveRef =
5379 BuildDeclRefExpr(SaveVar, StepExpr->getType(), VK_LValue, StepLoc);
5380 ExprResult CalcStep =
5381 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
5382
Alexander Musman8dba6642014-04-22 13:09:42 +00005383 // Warn about zero linear step (it would be probably better specified as
5384 // making corresponding variables 'const').
5385 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00005386 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
5387 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00005388 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
5389 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00005390 if (!IsConstant && CalcStep.isUsable()) {
5391 // Calculate the step beforehand instead of doing this on each iteration.
5392 // (This is not used if the number of iterations may be kfold-ed).
5393 CalcStepExpr = CalcStep.get();
5394 }
Alexander Musman8dba6642014-04-22 13:09:42 +00005395 }
5396
5397 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
Alexander Musman3276a272015-03-21 10:12:56 +00005398 Vars, Inits, StepExpr, CalcStepExpr);
5399}
5400
5401static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
5402 Expr *NumIterations, Sema &SemaRef,
5403 Scope *S) {
5404 // Walk the vars and build update/final expressions for the CodeGen.
5405 SmallVector<Expr *, 8> Updates;
5406 SmallVector<Expr *, 8> Finals;
5407 Expr *Step = Clause.getStep();
5408 Expr *CalcStep = Clause.getCalcStep();
5409 // OpenMP [2.14.3.7, linear clause]
5410 // If linear-step is not specified it is assumed to be 1.
5411 if (Step == nullptr)
5412 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5413 else if (CalcStep)
5414 Step = cast<BinaryOperator>(CalcStep)->getLHS();
5415 bool HasErrors = false;
5416 auto CurInit = Clause.inits().begin();
5417 for (auto &RefExpr : Clause.varlists()) {
5418 Expr *InitExpr = *CurInit;
5419
5420 // Build privatized reference to the current linear var.
5421 auto DE = cast<DeclRefExpr>(RefExpr);
5422 auto PrivateRef = DeclRefExpr::Create(
5423 SemaRef.Context, /*QualifierLoc*/ DE->getQualifierLoc(),
5424 /*TemplateKWLoc*/ SourceLocation(), DE->getDecl(),
5425 /* RefersToEnclosingVariableOrCapture */ true, DE->getLocStart(),
5426 DE->getType(), /*VK*/ VK_LValue);
5427
5428 // Build update: Var = InitExpr + IV * Step
5429 ExprResult Update =
5430 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
5431 InitExpr, IV, Step, /* Subtract */ false);
5432 Update = SemaRef.ActOnFinishFullExpr(Update.get());
5433
5434 // Build final: Var = InitExpr + NumIterations * Step
5435 ExprResult Final =
5436 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), RefExpr, InitExpr,
5437 NumIterations, Step, /* Subtract */ false);
5438 Final = SemaRef.ActOnFinishFullExpr(Final.get());
5439 if (!Update.isUsable() || !Final.isUsable()) {
5440 Updates.push_back(nullptr);
5441 Finals.push_back(nullptr);
5442 HasErrors = true;
5443 } else {
5444 Updates.push_back(Update.get());
5445 Finals.push_back(Final.get());
5446 }
5447 ++CurInit;
5448 }
5449 Clause.setUpdates(Updates);
5450 Clause.setFinals(Finals);
5451 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00005452}
5453
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005454OMPClause *Sema::ActOnOpenMPAlignedClause(
5455 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
5456 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
5457
5458 SmallVector<Expr *, 8> Vars;
5459 for (auto &RefExpr : VarList) {
5460 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
5461 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5462 // It will be analyzed later.
5463 Vars.push_back(RefExpr);
5464 continue;
5465 }
5466
5467 SourceLocation ELoc = RefExpr->getExprLoc();
5468 // OpenMP [2.1, C/C++]
5469 // A list item is a variable name.
5470 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5471 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5472 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5473 continue;
5474 }
5475
5476 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5477
5478 // OpenMP [2.8.1, simd construct, Restrictions]
5479 // The type of list items appearing in the aligned clause must be
5480 // array, pointer, reference to array, or reference to pointer.
5481 QualType QType = DE->getType()
5482 .getNonReferenceType()
5483 .getUnqualifiedType()
5484 .getCanonicalType();
5485 const Type *Ty = QType.getTypePtrOrNull();
5486 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
5487 !Ty->isPointerType())) {
5488 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
5489 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
5490 bool IsDecl =
5491 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5492 Diag(VD->getLocation(),
5493 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5494 << VD;
5495 continue;
5496 }
5497
5498 // OpenMP [2.8.1, simd construct, Restrictions]
5499 // A list-item cannot appear in more than one aligned clause.
5500 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
5501 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
5502 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
5503 << getOpenMPClauseName(OMPC_aligned);
5504 continue;
5505 }
5506
5507 Vars.push_back(DE);
5508 }
5509
5510 // OpenMP [2.8.1, simd construct, Description]
5511 // The parameter of the aligned clause, alignment, must be a constant
5512 // positive integer expression.
5513 // If no optional parameter is specified, implementation-defined default
5514 // alignments for SIMD instructions on the target platforms are assumed.
5515 if (Alignment != nullptr) {
5516 ExprResult AlignResult =
5517 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
5518 if (AlignResult.isInvalid())
5519 return nullptr;
5520 Alignment = AlignResult.get();
5521 }
5522 if (Vars.empty())
5523 return nullptr;
5524
5525 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
5526 EndLoc, Vars, Alignment);
5527}
5528
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005529OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
5530 SourceLocation StartLoc,
5531 SourceLocation LParenLoc,
5532 SourceLocation EndLoc) {
5533 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00005534 for (auto &RefExpr : VarList) {
5535 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
5536 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005537 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005538 Vars.push_back(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005539 continue;
5540 }
5541
Alexey Bataeved09d242014-05-28 05:53:51 +00005542 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005543 // OpenMP [2.1, C/C++]
5544 // A list item is a variable name.
5545 // OpenMP [2.14.4.1, Restrictions, p.1]
5546 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00005547 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005548 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005549 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005550 continue;
5551 }
5552
5553 Decl *D = DE->getDecl();
5554 VarDecl *VD = cast<VarDecl>(D);
5555
5556 QualType Type = VD->getType();
5557 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5558 // It will be analyzed later.
5559 Vars.push_back(DE);
5560 continue;
5561 }
5562
5563 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
5564 // A list item that appears in a copyin clause must be threadprivate.
5565 if (!DSAStack->isThreadPrivate(VD)) {
5566 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00005567 << getOpenMPClauseName(OMPC_copyin)
5568 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005569 continue;
5570 }
5571
5572 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
5573 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00005574 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005575 // operator for the class type.
5576 Type = Context.getBaseElementType(Type);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005577 CXXRecordDecl *RD =
5578 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev23b69422014-06-18 07:08:49 +00005579 // FIXME This code must be replaced by actual assignment of the
5580 // threadprivate variable.
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005581 if (RD) {
5582 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
5583 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005584 if (MD) {
5585 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
5586 MD->isDeleted()) {
5587 Diag(ELoc, diag::err_omp_required_method)
5588 << getOpenMPClauseName(OMPC_copyin) << 2;
5589 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5590 VarDecl::DeclarationOnly;
5591 Diag(VD->getLocation(),
5592 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5593 << VD;
5594 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5595 continue;
5596 }
5597 MarkFunctionReferenced(ELoc, MD);
5598 DiagnoseUseOfDecl(MD, ELoc);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005599 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005600 }
5601
5602 DSAStack->addDSA(VD, DE, OMPC_copyin);
5603 Vars.push_back(DE);
5604 }
5605
Alexey Bataeved09d242014-05-28 05:53:51 +00005606 if (Vars.empty())
5607 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005608
5609 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5610}
5611
Alexey Bataevbae9a792014-06-27 10:37:06 +00005612OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
5613 SourceLocation StartLoc,
5614 SourceLocation LParenLoc,
5615 SourceLocation EndLoc) {
5616 SmallVector<Expr *, 8> Vars;
5617 for (auto &RefExpr : VarList) {
5618 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
5619 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5620 // It will be analyzed later.
5621 Vars.push_back(RefExpr);
5622 continue;
5623 }
5624
5625 SourceLocation ELoc = RefExpr->getExprLoc();
5626 // OpenMP [2.1, C/C++]
5627 // A list item is a variable name.
5628 // OpenMP [2.14.4.1, Restrictions, p.1]
5629 // A list item that appears in a copyin clause must be threadprivate.
5630 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5631 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5632 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5633 continue;
5634 }
5635
5636 Decl *D = DE->getDecl();
5637 VarDecl *VD = cast<VarDecl>(D);
5638
5639 QualType Type = VD->getType();
5640 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5641 // It will be analyzed later.
5642 Vars.push_back(DE);
5643 continue;
5644 }
5645
5646 // OpenMP [2.14.4.2, Restrictions, p.2]
5647 // A list item that appears in a copyprivate clause may not appear in a
5648 // private or firstprivate clause on the single construct.
5649 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005650 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00005651 if (DVar.CKind != OMPC_copyprivate && DVar.CKind != OMPC_unknown &&
5652 !(DVar.CKind == OMPC_private && !DVar.RefExpr)) {
5653 Diag(ELoc, diag::err_omp_wrong_dsa)
5654 << getOpenMPClauseName(DVar.CKind)
5655 << getOpenMPClauseName(OMPC_copyprivate);
5656 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5657 continue;
5658 }
5659
5660 // OpenMP [2.11.4.2, Restrictions, p.1]
5661 // All list items that appear in a copyprivate clause must be either
5662 // threadprivate or private in the enclosing context.
5663 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005664 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00005665 if (DVar.CKind == OMPC_shared) {
5666 Diag(ELoc, diag::err_omp_required_access)
5667 << getOpenMPClauseName(OMPC_copyprivate)
5668 << "threadprivate or private in the enclosing context";
5669 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5670 continue;
5671 }
5672 }
5673 }
5674
5675 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
5676 // A variable of class type (or array thereof) that appears in a
5677 // copyin clause requires an accessible, unambiguous copy assignment
5678 // operator for the class type.
5679 Type = Context.getBaseElementType(Type);
5680 CXXRecordDecl *RD =
5681 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
5682 // FIXME This code must be replaced by actual assignment of the
5683 // threadprivate variable.
5684 if (RD) {
5685 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
5686 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
5687 if (MD) {
5688 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
5689 MD->isDeleted()) {
5690 Diag(ELoc, diag::err_omp_required_method)
5691 << getOpenMPClauseName(OMPC_copyprivate) << 2;
5692 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5693 VarDecl::DeclarationOnly;
5694 Diag(VD->getLocation(),
5695 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5696 << VD;
5697 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5698 continue;
5699 }
5700 MarkFunctionReferenced(ELoc, MD);
5701 DiagnoseUseOfDecl(MD, ELoc);
5702 }
5703 }
5704
5705 // No need to mark vars as copyprivate, they are already threadprivate or
5706 // implicitly private.
5707 Vars.push_back(DE);
5708 }
5709
5710 if (Vars.empty())
5711 return nullptr;
5712
5713 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5714}
5715
Alexey Bataev6125da92014-07-21 11:26:11 +00005716OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
5717 SourceLocation StartLoc,
5718 SourceLocation LParenLoc,
5719 SourceLocation EndLoc) {
5720 if (VarList.empty())
5721 return nullptr;
5722
5723 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
5724}
Alexey Bataevdea47612014-07-23 07:46:59 +00005725