blob: cbe252c7111e7c79f09f42a495172634c60fdfff [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)) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000576 for (auto *C : D->clauses()) {
577 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
578 SmallVector<Expr *, 8> PrivateCopies;
579 for (auto *DE : Clause->varlists()) {
580 if (DE->isValueDependent() || DE->isTypeDependent()) {
581 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000582 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +0000583 }
584 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000585 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000586 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000587 // Generate helper private variable and initialize it with the
588 // default value. The address of the original variable is replaced
589 // by the address of the new private variable in CodeGen. This new
590 // variable is not added to IdResolver, so the code in the OpenMP
591 // region uses original variable for proper diagnostics.
592 auto *VDPrivate = VarDecl::Create(
593 Context, CurContext, DE->getLocStart(), DE->getExprLoc(),
594 VD->getIdentifier(), VD->getType(), VD->getTypeSourceInfo(),
595 SC_Auto);
596 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
597 if (VDPrivate->isInvalidDecl())
598 continue;
599 CurContext->addDecl(VDPrivate);
600 PrivateCopies.push_back(DeclRefExpr::Create(
601 Context, NestedNameSpecifierLoc(), SourceLocation(), VDPrivate,
602 /*RefersToEnclosingVariableOrCapture=*/false, SourceLocation(),
603 DE->getType(), VK_LValue));
604 } else {
605 // The variable is also a firstprivate, so initialization sequence
606 // for private copy is generated already.
607 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000608 }
609 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000610 // Set initializers to private copies if no errors were found.
611 if (PrivateCopies.size() == Clause->varlist_size()) {
612 Clause->setPrivateCopies(PrivateCopies);
613 }
Alexey Bataevf29276e2014-06-18 04:14:57 +0000614 }
615 }
616 }
617
Alexey Bataev758e55e2013-09-06 18:03:48 +0000618 DSAStack->pop();
619 DiscardCleanupsInEvaluationContext();
620 PopExpressionEvaluationContext();
621}
622
Alexander Musman3276a272015-03-21 10:12:56 +0000623static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
624 Expr *NumIterations, Sema &SemaRef,
625 Scope *S);
626
Alexey Bataeva769e072013-03-22 06:34:35 +0000627namespace {
628
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000629class VarDeclFilterCCC : public CorrectionCandidateCallback {
630private:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000631 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +0000632
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000633public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000634 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +0000635 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000636 NamedDecl *ND = Candidate.getCorrectionDecl();
637 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
638 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000639 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
640 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +0000641 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000642 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +0000643 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000644};
Alexey Bataeved09d242014-05-28 05:53:51 +0000645} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000646
647ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
648 CXXScopeSpec &ScopeSpec,
649 const DeclarationNameInfo &Id) {
650 LookupResult Lookup(*this, Id, LookupOrdinaryName);
651 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
652
653 if (Lookup.isAmbiguous())
654 return ExprError();
655
656 VarDecl *VD;
657 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000658 if (TypoCorrection Corrected = CorrectTypo(
659 Id, LookupOrdinaryName, CurScope, nullptr,
660 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000661 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000662 PDiag(Lookup.empty()
663 ? diag::err_undeclared_var_use_suggest
664 : diag::err_omp_expected_var_arg_suggest)
665 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +0000666 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000667 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000668 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
669 : diag::err_omp_expected_var_arg)
670 << Id.getName();
671 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000672 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000673 } else {
674 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000675 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000676 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
677 return ExprError();
678 }
679 }
680 Lookup.suppressDiagnostics();
681
682 // OpenMP [2.9.2, Syntax, C/C++]
683 // Variables must be file-scope, namespace-scope, or static block-scope.
684 if (!VD->hasGlobalStorage()) {
685 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000686 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
687 bool IsDecl =
688 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000689 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +0000690 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
691 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000692 return ExprError();
693 }
694
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000695 VarDecl *CanonicalVD = VD->getCanonicalDecl();
696 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000697 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
698 // A threadprivate directive for file-scope variables must appear outside
699 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000700 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
701 !getCurLexicalContext()->isTranslationUnit()) {
702 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000703 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
704 bool IsDecl =
705 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
706 Diag(VD->getLocation(),
707 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
708 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000709 return ExprError();
710 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000711 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
712 // A threadprivate directive for static class member variables must appear
713 // in the class definition, in the same scope in which the member
714 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000715 if (CanonicalVD->isStaticDataMember() &&
716 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
717 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000718 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
719 bool IsDecl =
720 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
721 Diag(VD->getLocation(),
722 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
723 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000724 return ExprError();
725 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000726 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
727 // A threadprivate directive for namespace-scope variables must appear
728 // outside any definition or declaration other than the namespace
729 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000730 if (CanonicalVD->getDeclContext()->isNamespace() &&
731 (!getCurLexicalContext()->isFileContext() ||
732 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
733 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000734 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
735 bool IsDecl =
736 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
737 Diag(VD->getLocation(),
738 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
739 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000740 return ExprError();
741 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000742 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
743 // A threadprivate directive for static block-scope variables must appear
744 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000745 if (CanonicalVD->isStaticLocal() && CurScope &&
746 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000747 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000748 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
749 bool IsDecl =
750 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
751 Diag(VD->getLocation(),
752 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
753 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000754 return ExprError();
755 }
756
757 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
758 // A threadprivate directive must lexically precede all references to any
759 // of the variables in its list.
Alexey Bataev7c2ed442015-04-08 12:45:41 +0000760 if (VD->isUsed() && !DSAStack->isThreadPrivate(CanonicalVD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000761 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +0000762 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000763 return ExprError();
764 }
765
766 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataevd178ad42014-03-07 08:03:37 +0000767 ExprResult DE = BuildDeclRefExpr(VD, ExprType, VK_LValue, Id.getLoc());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000768 return DE;
769}
770
Alexey Bataeved09d242014-05-28 05:53:51 +0000771Sema::DeclGroupPtrTy
772Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
773 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000774 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000775 CurContext->addDecl(D);
776 return DeclGroupPtrTy::make(DeclGroupRef(D));
777 }
778 return DeclGroupPtrTy();
779}
780
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000781namespace {
782class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
783 Sema &SemaRef;
784
785public:
786 bool VisitDeclRefExpr(const DeclRefExpr *E) {
787 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
788 if (VD->hasLocalStorage()) {
789 SemaRef.Diag(E->getLocStart(),
790 diag::err_omp_local_var_in_threadprivate_init)
791 << E->getSourceRange();
792 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
793 << VD << VD->getSourceRange();
794 return true;
795 }
796 }
797 return false;
798 }
799 bool VisitStmt(const Stmt *S) {
800 for (auto Child : S->children()) {
801 if (Child && Visit(Child))
802 return true;
803 }
804 return false;
805 }
Alexey Bataev23b69422014-06-18 07:08:49 +0000806 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000807};
808} // namespace
809
Alexey Bataeved09d242014-05-28 05:53:51 +0000810OMPThreadPrivateDecl *
811Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000812 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +0000813 for (auto &RefExpr : VarList) {
814 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000815 VarDecl *VD = cast<VarDecl>(DE->getDecl());
816 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +0000817
818 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
819 // A threadprivate variable must not have an incomplete type.
820 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000821 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000822 continue;
823 }
824
825 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
826 // A threadprivate variable must not have a reference type.
827 if (VD->getType()->isReferenceType()) {
828 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000829 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
830 bool IsDecl =
831 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
832 Diag(VD->getLocation(),
833 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
834 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000835 continue;
836 }
837
Richard Smithfd3834f2013-04-13 02:43:54 +0000838 // Check if this is a TLS variable.
Alexey Bataev26a39242015-01-13 03:35:30 +0000839 if (VD->getTLSKind() != VarDecl::TLS_None ||
840 VD->getStorageClass() == SC_Register) {
841 Diag(ILoc, diag::err_omp_var_thread_local)
842 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +0000843 bool IsDecl =
844 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
845 Diag(VD->getLocation(),
846 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
847 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000848 continue;
849 }
850
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000851 // Check if initial value of threadprivate variable reference variable with
852 // local storage (it is not supported by runtime).
853 if (auto Init = VD->getAnyInitializer()) {
854 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000855 if (Checker.Visit(Init))
856 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000857 }
858
Alexey Bataeved09d242014-05-28 05:53:51 +0000859 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +0000860 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +0000861 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
862 Context, SourceRange(Loc, Loc)));
863 if (auto *ML = Context.getASTMutationListener())
864 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +0000865 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000866 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000867 if (!Vars.empty()) {
868 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
869 Vars);
870 D->setAccess(AS_public);
871 }
872 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +0000873}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000874
Alexey Bataev7ff55242014-06-19 09:13:45 +0000875static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
876 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
877 bool IsLoopIterVar = false) {
878 if (DVar.RefExpr) {
879 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
880 << getOpenMPClauseName(DVar.CKind);
881 return;
882 }
883 enum {
884 PDSA_StaticMemberShared,
885 PDSA_StaticLocalVarShared,
886 PDSA_LoopIterVarPrivate,
887 PDSA_LoopIterVarLinear,
888 PDSA_LoopIterVarLastprivate,
889 PDSA_ConstVarShared,
890 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000891 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000892 PDSA_LocalVarPrivate,
893 PDSA_Implicit
894 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000895 bool ReportHint = false;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000896 auto ReportLoc = VD->getLocation();
Alexey Bataev7ff55242014-06-19 09:13:45 +0000897 if (IsLoopIterVar) {
898 if (DVar.CKind == OMPC_private)
899 Reason = PDSA_LoopIterVarPrivate;
900 else if (DVar.CKind == OMPC_lastprivate)
901 Reason = PDSA_LoopIterVarLastprivate;
902 else
903 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000904 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
905 Reason = PDSA_TaskVarFirstprivate;
906 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000907 } else if (VD->isStaticLocal())
908 Reason = PDSA_StaticLocalVarShared;
909 else if (VD->isStaticDataMember())
910 Reason = PDSA_StaticMemberShared;
911 else if (VD->isFileVarDecl())
912 Reason = PDSA_GlobalVarShared;
913 else if (VD->getType().isConstant(SemaRef.getASTContext()))
914 Reason = PDSA_ConstVarShared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000915 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +0000916 ReportHint = true;
917 Reason = PDSA_LocalVarPrivate;
918 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000919 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000920 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +0000921 << Reason << ReportHint
922 << getOpenMPDirectiveName(Stack->getCurrentDirective());
923 } else if (DVar.ImplicitDSALoc.isValid()) {
924 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
925 << getOpenMPClauseName(DVar.CKind);
926 }
Alexey Bataev7ff55242014-06-19 09:13:45 +0000927}
928
Alexey Bataev758e55e2013-09-06 18:03:48 +0000929namespace {
930class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
931 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000932 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000933 bool ErrorFound;
934 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000935 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev4acb8592014-07-07 13:01:15 +0000936 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +0000937
Alexey Bataev758e55e2013-09-06 18:03:48 +0000938public:
939 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000940 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000941 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +0000942 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
943 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000944
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000945 auto DVar = Stack->getTopDSA(VD, false);
946 // Check if the variable has explicit DSA set and stop analysis if it so.
947 if (DVar.RefExpr) return;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000948
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000949 auto ELoc = E->getExprLoc();
950 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000951 // The default(none) clause requires that each variable that is referenced
952 // in the construct, and does not have a predetermined data-sharing
953 // attribute, must have its data-sharing attribute explicitly determined
954 // by being listed in a data-sharing attribute clause.
955 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000956 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +0000957 VarsWithInheritedDSA.count(VD) == 0) {
958 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000959 return;
960 }
961
962 // OpenMP [2.9.3.6, Restrictions, p.2]
963 // A list item that appears in a reduction clause of the innermost
964 // enclosing worksharing or parallel construct may not be accessed in an
965 // explicit task.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000966 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000967 [](OpenMPDirectiveKind K) -> bool {
968 return isOpenMPParallelDirective(K) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +0000969 isOpenMPWorksharingDirective(K) ||
970 isOpenMPTeamsDirective(K);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000971 },
972 false);
Alexey Bataevc5e02582014-06-16 07:08:35 +0000973 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
974 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000975 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
976 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +0000977 return;
978 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000979
980 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000981 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000982 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000983 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000984 }
985 }
986 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000987 for (auto *C : S->clauses()) {
988 // Skip analysis of arguments of implicitly defined firstprivate clause
989 // for task directives.
990 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
991 for (auto *CC : C->children()) {
992 if (CC)
993 Visit(CC);
994 }
995 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000996 }
997 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000998 for (auto *C : S->children()) {
999 if (C && !isa<OMPExecutableDirective>(C))
1000 Visit(C);
1001 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001002 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001003
1004 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001005 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001006 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1007 return VarsWithInheritedDSA;
1008 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001009
Alexey Bataev7ff55242014-06-19 09:13:45 +00001010 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1011 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001012};
Alexey Bataeved09d242014-05-28 05:53:51 +00001013} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001014
Alexey Bataevbae9a792014-06-27 10:37:06 +00001015void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001016 switch (DKind) {
1017 case OMPD_parallel: {
1018 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1019 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001020 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001021 std::make_pair(".global_tid.", KmpInt32PtrTy),
1022 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1023 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001024 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001025 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1026 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001027 break;
1028 }
1029 case OMPD_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001030 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001031 std::make_pair(StringRef(), QualType()) // __context with shared vars
1032 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001033 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1034 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001035 break;
1036 }
1037 case OMPD_for: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001038 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001039 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001040 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001041 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1042 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001043 break;
1044 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001045 case OMPD_for_simd: {
1046 Sema::CapturedParamNameType Params[] = {
1047 std::make_pair(StringRef(), QualType()) // __context with shared vars
1048 };
1049 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1050 Params);
1051 break;
1052 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001053 case OMPD_sections: {
1054 Sema::CapturedParamNameType Params[] = {
1055 std::make_pair(StringRef(), QualType()) // __context with shared vars
1056 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001057 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1058 Params);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001059 break;
1060 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001061 case OMPD_section: {
1062 Sema::CapturedParamNameType Params[] = {
1063 std::make_pair(StringRef(), QualType()) // __context with shared vars
1064 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001065 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1066 Params);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001067 break;
1068 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001069 case OMPD_single: {
1070 Sema::CapturedParamNameType Params[] = {
1071 std::make_pair(StringRef(), QualType()) // __context with shared vars
1072 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001073 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1074 Params);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001075 break;
1076 }
Alexander Musman80c22892014-07-17 08:54:58 +00001077 case OMPD_master: {
1078 Sema::CapturedParamNameType Params[] = {
1079 std::make_pair(StringRef(), QualType()) // __context with shared vars
1080 };
1081 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1082 Params);
1083 break;
1084 }
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001085 case OMPD_critical: {
1086 Sema::CapturedParamNameType Params[] = {
1087 std::make_pair(StringRef(), QualType()) // __context with shared vars
1088 };
1089 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1090 Params);
1091 break;
1092 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001093 case OMPD_parallel_for: {
1094 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1095 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1096 Sema::CapturedParamNameType Params[] = {
1097 std::make_pair(".global_tid.", KmpInt32PtrTy),
1098 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1099 std::make_pair(StringRef(), QualType()) // __context with shared vars
1100 };
1101 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1102 Params);
1103 break;
1104 }
Alexander Musmane4e893b2014-09-23 09:33:00 +00001105 case OMPD_parallel_for_simd: {
1106 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1107 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1108 Sema::CapturedParamNameType Params[] = {
1109 std::make_pair(".global_tid.", KmpInt32PtrTy),
1110 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1111 std::make_pair(StringRef(), QualType()) // __context with shared vars
1112 };
1113 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1114 Params);
1115 break;
1116 }
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001117 case OMPD_parallel_sections: {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001118 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1119 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001120 Sema::CapturedParamNameType Params[] = {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001121 std::make_pair(".global_tid.", KmpInt32PtrTy),
1122 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001123 std::make_pair(StringRef(), QualType()) // __context with shared vars
1124 };
1125 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1126 Params);
1127 break;
1128 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001129 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001130 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001131 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001132 std::make_pair(".global_tid.", KmpInt32Ty),
1133 std::make_pair(".part_id.", KmpInt32Ty),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001134 std::make_pair(StringRef(), QualType()) // __context with shared vars
1135 };
1136 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1137 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001138 // Mark this captured region as inlined, because we don't use outlined
1139 // function directly.
1140 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1141 AlwaysInlineAttr::CreateImplicit(
1142 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001143 break;
1144 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001145 case OMPD_ordered: {
1146 Sema::CapturedParamNameType Params[] = {
1147 std::make_pair(StringRef(), QualType()) // __context with shared vars
1148 };
1149 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1150 Params);
1151 break;
1152 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001153 case OMPD_atomic: {
1154 Sema::CapturedParamNameType Params[] = {
1155 std::make_pair(StringRef(), QualType()) // __context with shared vars
1156 };
1157 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1158 Params);
1159 break;
1160 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001161 case OMPD_target: {
1162 Sema::CapturedParamNameType Params[] = {
1163 std::make_pair(StringRef(), QualType()) // __context with shared vars
1164 };
1165 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1166 Params);
1167 break;
1168 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001169 case OMPD_teams: {
1170 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1171 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1172 Sema::CapturedParamNameType Params[] = {
1173 std::make_pair(".global_tid.", KmpInt32PtrTy),
1174 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1175 std::make_pair(StringRef(), QualType()) // __context with shared vars
1176 };
1177 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1178 Params);
1179 break;
1180 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001181 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001182 case OMPD_taskyield:
1183 case OMPD_barrier:
1184 case OMPD_taskwait:
1185 case OMPD_flush:
Alexey Bataev9959db52014-05-06 10:08:46 +00001186 llvm_unreachable("OpenMP Directive is not allowed");
1187 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001188 llvm_unreachable("Unknown OpenMP directive");
1189 }
1190}
1191
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001192StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1193 ArrayRef<OMPClause *> Clauses) {
1194 if (!S.isUsable()) {
1195 ActOnCapturedRegionError();
1196 return StmtError();
1197 }
1198 // Mark all variables in private list clauses as used in inner region. This is
1199 // required for proper codegen.
1200 for (auto *Clause : Clauses) {
1201 if (isOpenMPPrivate(Clause->getClauseKind())) {
1202 for (auto *VarRef : Clause->children()) {
1203 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001204 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001205 }
1206 }
1207 }
1208 }
1209 return ActOnCapturedRegionEnd(S.get());
1210}
1211
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001212static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1213 OpenMPDirectiveKind CurrentRegion,
1214 const DeclarationNameInfo &CurrentName,
1215 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001216 // Allowed nesting of constructs
1217 // +------------------+-----------------+------------------------------------+
1218 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1219 // +------------------+-----------------+------------------------------------+
1220 // | parallel | parallel | * |
1221 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001222 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001223 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001224 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001225 // | parallel | simd | * |
1226 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001227 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001228 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001229 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001230 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001231 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001232 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001233 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001234 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001235 // | parallel | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001236 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001237 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001238 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001239 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001240 // | parallel | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001241 // +------------------+-----------------+------------------------------------+
1242 // | for | parallel | * |
1243 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001244 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001245 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001246 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001247 // | for | simd | * |
1248 // | for | sections | + |
1249 // | for | section | + |
1250 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001251 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001252 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001253 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001254 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001255 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001256 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001257 // | for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001258 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001259 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001260 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001261 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001262 // | for | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001263 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001264 // | master | parallel | * |
1265 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001266 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001267 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001268 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001269 // | master | simd | * |
1270 // | master | sections | + |
1271 // | master | section | + |
1272 // | master | single | + |
1273 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001274 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001275 // | master |parallel sections| * |
1276 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001277 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001278 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001279 // | master | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001280 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001281 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001282 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001283 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001284 // | master | teams | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001285 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001286 // | critical | parallel | * |
1287 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001288 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001289 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001290 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001291 // | critical | simd | * |
1292 // | critical | sections | + |
1293 // | critical | section | + |
1294 // | critical | single | + |
1295 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001296 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001297 // | critical |parallel sections| * |
1298 // | critical | task | * |
1299 // | critical | taskyield | * |
1300 // | critical | barrier | + |
1301 // | critical | taskwait | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001302 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001303 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001304 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001305 // | critical | teams | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001306 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001307 // | simd | parallel | |
1308 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001309 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001310 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001311 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001312 // | simd | simd | |
1313 // | simd | sections | |
1314 // | simd | section | |
1315 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001316 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001317 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001318 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001319 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001320 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001321 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001322 // | simd | taskwait | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001323 // | simd | flush | |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001324 // | simd | ordered | |
Alexey Bataev0162e452014-07-22 10:10:35 +00001325 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001326 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001327 // | simd | teams | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001328 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001329 // | for simd | parallel | |
1330 // | for simd | for | |
1331 // | for simd | for simd | |
1332 // | for simd | master | |
1333 // | for simd | critical | |
1334 // | for simd | simd | |
1335 // | for simd | sections | |
1336 // | for simd | section | |
1337 // | for simd | single | |
1338 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001339 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001340 // | for simd |parallel sections| |
1341 // | for simd | task | |
1342 // | for simd | taskyield | |
1343 // | for simd | barrier | |
1344 // | for simd | taskwait | |
1345 // | for simd | flush | |
1346 // | for simd | ordered | |
1347 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001348 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001349 // | for simd | teams | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001350 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001351 // | parallel for simd| parallel | |
1352 // | parallel for simd| for | |
1353 // | parallel for simd| for simd | |
1354 // | parallel for simd| master | |
1355 // | parallel for simd| critical | |
1356 // | parallel for simd| simd | |
1357 // | parallel for simd| sections | |
1358 // | parallel for simd| section | |
1359 // | parallel for simd| single | |
1360 // | parallel for simd| parallel for | |
1361 // | parallel for simd|parallel for simd| |
1362 // | parallel for simd|parallel sections| |
1363 // | parallel for simd| task | |
1364 // | parallel for simd| taskyield | |
1365 // | parallel for simd| barrier | |
1366 // | parallel for simd| taskwait | |
1367 // | parallel for simd| flush | |
1368 // | parallel for simd| ordered | |
1369 // | parallel for simd| atomic | |
1370 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001371 // | parallel for simd| teams | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001372 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001373 // | sections | parallel | * |
1374 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001375 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001376 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001377 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001378 // | sections | simd | * |
1379 // | sections | sections | + |
1380 // | sections | section | * |
1381 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001382 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001383 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001384 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001385 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001386 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001387 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001388 // | sections | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001389 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001390 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001391 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001392 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001393 // | sections | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001394 // +------------------+-----------------+------------------------------------+
1395 // | section | parallel | * |
1396 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001397 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001398 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001399 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001400 // | section | simd | * |
1401 // | section | sections | + |
1402 // | section | section | + |
1403 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001404 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001405 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001406 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001407 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001408 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001409 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001410 // | section | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001411 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001412 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001413 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001414 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001415 // | section | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001416 // +------------------+-----------------+------------------------------------+
1417 // | single | parallel | * |
1418 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001419 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001420 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001421 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001422 // | single | simd | * |
1423 // | single | sections | + |
1424 // | single | section | + |
1425 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001426 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001427 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001428 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001429 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001430 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001431 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001432 // | single | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001433 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001434 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001435 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001436 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001437 // | single | teams | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001438 // +------------------+-----------------+------------------------------------+
1439 // | parallel for | parallel | * |
1440 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001441 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001442 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001443 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001444 // | parallel for | simd | * |
1445 // | parallel for | sections | + |
1446 // | parallel for | section | + |
1447 // | parallel for | single | + |
1448 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001449 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001450 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001451 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001452 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001453 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001454 // | parallel for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001455 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001456 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001457 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001458 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001459 // | parallel for | teams | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001460 // +------------------+-----------------+------------------------------------+
1461 // | parallel sections| parallel | * |
1462 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001463 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001464 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001465 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001466 // | parallel sections| simd | * |
1467 // | parallel sections| sections | + |
1468 // | parallel sections| section | * |
1469 // | parallel sections| single | + |
1470 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001471 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001472 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001473 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001474 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001475 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001476 // | parallel sections| taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001477 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001478 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001479 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001480 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001481 // | parallel sections| teams | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001482 // +------------------+-----------------+------------------------------------+
1483 // | task | parallel | * |
1484 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001485 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001486 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001487 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001488 // | task | simd | * |
1489 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001490 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001491 // | task | single | + |
1492 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001493 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001494 // | task |parallel sections| * |
1495 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001496 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001497 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001498 // | task | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001499 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001500 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001501 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001502 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001503 // | task | teams | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001504 // +------------------+-----------------+------------------------------------+
1505 // | ordered | parallel | * |
1506 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001507 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001508 // | ordered | master | * |
1509 // | ordered | critical | * |
1510 // | ordered | simd | * |
1511 // | ordered | sections | + |
1512 // | ordered | section | + |
1513 // | ordered | single | + |
1514 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001515 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001516 // | ordered |parallel sections| * |
1517 // | ordered | task | * |
1518 // | ordered | taskyield | * |
1519 // | ordered | barrier | + |
1520 // | ordered | taskwait | * |
1521 // | ordered | flush | * |
1522 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001523 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001524 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001525 // | ordered | teams | + |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001526 // +------------------+-----------------+------------------------------------+
1527 // | atomic | parallel | |
1528 // | atomic | for | |
1529 // | atomic | for simd | |
1530 // | atomic | master | |
1531 // | atomic | critical | |
1532 // | atomic | simd | |
1533 // | atomic | sections | |
1534 // | atomic | section | |
1535 // | atomic | single | |
1536 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001537 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001538 // | atomic |parallel sections| |
1539 // | atomic | task | |
1540 // | atomic | taskyield | |
1541 // | atomic | barrier | |
1542 // | atomic | taskwait | |
1543 // | atomic | flush | |
1544 // | atomic | ordered | |
1545 // | atomic | atomic | |
1546 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001547 // | atomic | teams | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001548 // +------------------+-----------------+------------------------------------+
1549 // | target | parallel | * |
1550 // | target | for | * |
1551 // | target | for simd | * |
1552 // | target | master | * |
1553 // | target | critical | * |
1554 // | target | simd | * |
1555 // | target | sections | * |
1556 // | target | section | * |
1557 // | target | single | * |
1558 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001559 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001560 // | target |parallel sections| * |
1561 // | target | task | * |
1562 // | target | taskyield | * |
1563 // | target | barrier | * |
1564 // | target | taskwait | * |
1565 // | target | flush | * |
1566 // | target | ordered | * |
1567 // | target | atomic | * |
1568 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001569 // | target | teams | * |
1570 // +------------------+-----------------+------------------------------------+
1571 // | teams | parallel | * |
1572 // | teams | for | + |
1573 // | teams | for simd | + |
1574 // | teams | master | + |
1575 // | teams | critical | + |
1576 // | teams | simd | + |
1577 // | teams | sections | + |
1578 // | teams | section | + |
1579 // | teams | single | + |
1580 // | teams | parallel for | * |
1581 // | teams |parallel for simd| * |
1582 // | teams |parallel sections| * |
1583 // | teams | task | + |
1584 // | teams | taskyield | + |
1585 // | teams | barrier | + |
1586 // | teams | taskwait | + |
1587 // | teams | flush | + |
1588 // | teams | ordered | + |
1589 // | teams | atomic | + |
1590 // | teams | target | + |
1591 // | teams | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001592 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00001593 if (Stack->getCurScope()) {
1594 auto ParentRegion = Stack->getParentDirective();
1595 bool NestingProhibited = false;
1596 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001597 enum {
1598 NoRecommend,
1599 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001600 ShouldBeInOrderedRegion,
1601 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001602 } Recommend = NoRecommend;
Alexey Bataev549210e2014-06-24 04:39:47 +00001603 if (isOpenMPSimdDirective(ParentRegion)) {
1604 // OpenMP [2.16, Nesting of Regions]
1605 // OpenMP constructs may not be nested inside a simd region.
1606 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1607 return true;
1608 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001609 if (ParentRegion == OMPD_atomic) {
1610 // OpenMP [2.16, Nesting of Regions]
1611 // OpenMP constructs may not be nested inside an atomic region.
1612 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1613 return true;
1614 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001615 if (CurrentRegion == OMPD_section) {
1616 // OpenMP [2.7.2, sections Construct, Restrictions]
1617 // Orphaned section directives are prohibited. That is, the section
1618 // directives must appear within the sections construct and must not be
1619 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001620 if (ParentRegion != OMPD_sections &&
1621 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001622 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1623 << (ParentRegion != OMPD_unknown)
1624 << getOpenMPDirectiveName(ParentRegion);
1625 return true;
1626 }
1627 return false;
1628 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001629 // Allow some constructs to be orphaned (they could be used in functions,
1630 // called from OpenMP regions with the required preconditions).
1631 if (ParentRegion == OMPD_unknown)
1632 return false;
Alexander Musman80c22892014-07-17 08:54:58 +00001633 if (CurrentRegion == OMPD_master) {
1634 // OpenMP [2.16, Nesting of Regions]
1635 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001636 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001637 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1638 ParentRegion == OMPD_task;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001639 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1640 // OpenMP [2.16, Nesting of Regions]
1641 // A critical region may not be nested (closely or otherwise) inside a
1642 // critical region with the same name. Note that this restriction is not
1643 // sufficient to prevent deadlock.
1644 SourceLocation PreviousCriticalLoc;
1645 bool DeadLock =
1646 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1647 OpenMPDirectiveKind K,
1648 const DeclarationNameInfo &DNI,
1649 SourceLocation Loc)
1650 ->bool {
1651 if (K == OMPD_critical &&
1652 DNI.getName() == CurrentName.getName()) {
1653 PreviousCriticalLoc = Loc;
1654 return true;
1655 } else
1656 return false;
1657 },
1658 false /* skip top directive */);
1659 if (DeadLock) {
1660 SemaRef.Diag(StartLoc,
1661 diag::err_omp_prohibited_region_critical_same_name)
1662 << CurrentName.getName();
1663 if (PreviousCriticalLoc.isValid())
1664 SemaRef.Diag(PreviousCriticalLoc,
1665 diag::note_omp_previous_critical_region);
1666 return true;
1667 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001668 } else if (CurrentRegion == OMPD_barrier) {
1669 // OpenMP [2.16, Nesting of Regions]
1670 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001671 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001672 NestingProhibited =
1673 isOpenMPWorksharingDirective(ParentRegion) ||
1674 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1675 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001676 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00001677 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001678 // OpenMP [2.16, Nesting of Regions]
1679 // A worksharing region may not be closely nested inside a worksharing,
1680 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001681 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00001682 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001683 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1684 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1685 Recommend = ShouldBeInParallelRegion;
1686 } else if (CurrentRegion == OMPD_ordered) {
1687 // OpenMP [2.16, Nesting of Regions]
1688 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00001689 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001690 // An ordered region must be closely nested inside a loop region (or
1691 // parallel loop region) with an ordered clause.
1692 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00001693 ParentRegion == OMPD_task ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001694 !Stack->isParentOrderedRegion();
1695 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001696 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1697 // OpenMP [2.16, Nesting of Regions]
1698 // If specified, a teams construct must be contained within a target
1699 // construct.
1700 NestingProhibited = ParentRegion != OMPD_target;
1701 Recommend = ShouldBeInTargetRegion;
1702 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1703 }
1704 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1705 // OpenMP [2.16, Nesting of Regions]
1706 // distribute, parallel, parallel sections, parallel workshare, and the
1707 // parallel loop and parallel loop SIMD constructs are the only OpenMP
1708 // constructs that can be closely nested in the teams region.
1709 // TODO: add distribute directive.
1710 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1711 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001712 }
1713 if (NestingProhibited) {
1714 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001715 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1716 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00001717 return true;
1718 }
1719 }
1720 return false;
1721}
1722
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001723StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001724 const DeclarationNameInfo &DirName,
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001725 ArrayRef<OMPClause *> Clauses,
1726 Stmt *AStmt,
1727 SourceLocation StartLoc,
1728 SourceLocation EndLoc) {
1729 StmtResult Res = StmtError();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001730 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00001731 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001732
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001733 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00001734 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001735 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00001736 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00001737 if (AStmt) {
1738 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1739
1740 // Check default data sharing attributes for referenced variables.
1741 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1742 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1743 if (DSAChecker.isErrorFound())
1744 return StmtError();
1745 // Generate list of implicitly defined firstprivate variables.
1746 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00001747
1748 if (!DSAChecker.getImplicitFirstprivate().empty()) {
1749 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1750 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1751 SourceLocation(), SourceLocation())) {
1752 ClausesWithImplicit.push_back(Implicit);
1753 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1754 DSAChecker.getImplicitFirstprivate().size();
1755 } else
1756 ErrorFound = true;
1757 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001758 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001759
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001760 switch (Kind) {
1761 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00001762 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1763 EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001764 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001765 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001766 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1767 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001768 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00001769 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001770 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1771 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001772 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00001773 case OMPD_for_simd:
1774 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
1775 EndLoc, VarsWithInheritedDSA);
1776 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001777 case OMPD_sections:
1778 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1779 EndLoc);
1780 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001781 case OMPD_section:
1782 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00001783 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001784 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1785 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001786 case OMPD_single:
1787 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1788 EndLoc);
1789 break;
Alexander Musman80c22892014-07-17 08:54:58 +00001790 case OMPD_master:
1791 assert(ClausesWithImplicit.empty() &&
1792 "No clauses are allowed for 'omp master' directive");
1793 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1794 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001795 case OMPD_critical:
1796 assert(ClausesWithImplicit.empty() &&
1797 "No clauses are allowed for 'omp critical' directive");
1798 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1799 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001800 case OMPD_parallel_for:
1801 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1802 EndLoc, VarsWithInheritedDSA);
1803 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00001804 case OMPD_parallel_for_simd:
1805 Res = ActOnOpenMPParallelForSimdDirective(
1806 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
1807 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001808 case OMPD_parallel_sections:
1809 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1810 StartLoc, EndLoc);
1811 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001812 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001813 Res =
1814 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1815 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00001816 case OMPD_taskyield:
1817 assert(ClausesWithImplicit.empty() &&
1818 "No clauses are allowed for 'omp taskyield' directive");
1819 assert(AStmt == nullptr &&
1820 "No associated statement allowed for 'omp taskyield' directive");
1821 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1822 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001823 case OMPD_barrier:
1824 assert(ClausesWithImplicit.empty() &&
1825 "No clauses are allowed for 'omp barrier' directive");
1826 assert(AStmt == nullptr &&
1827 "No associated statement allowed for 'omp barrier' directive");
1828 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1829 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00001830 case OMPD_taskwait:
1831 assert(ClausesWithImplicit.empty() &&
1832 "No clauses are allowed for 'omp taskwait' directive");
1833 assert(AStmt == nullptr &&
1834 "No associated statement allowed for 'omp taskwait' directive");
1835 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1836 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00001837 case OMPD_flush:
1838 assert(AStmt == nullptr &&
1839 "No associated statement allowed for 'omp flush' directive");
1840 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
1841 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001842 case OMPD_ordered:
1843 assert(ClausesWithImplicit.empty() &&
1844 "No clauses are allowed for 'omp ordered' directive");
1845 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
1846 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00001847 case OMPD_atomic:
1848 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
1849 EndLoc);
1850 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001851 case OMPD_teams:
1852 Res =
1853 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1854 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001855 case OMPD_target:
1856 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
1857 EndLoc);
1858 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001859 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001860 llvm_unreachable("OpenMP Directive is not allowed");
1861 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001862 llvm_unreachable("Unknown OpenMP directive");
1863 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001864
Alexey Bataev4acb8592014-07-07 13:01:15 +00001865 for (auto P : VarsWithInheritedDSA) {
1866 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1867 << P.first << P.second->getSourceRange();
1868 }
1869 if (!VarsWithInheritedDSA.empty())
1870 return StmtError();
1871
Alexey Bataeved09d242014-05-28 05:53:51 +00001872 if (ErrorFound)
1873 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001874 return Res;
1875}
1876
1877StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
1878 Stmt *AStmt,
1879 SourceLocation StartLoc,
1880 SourceLocation EndLoc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001881 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
1882 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
1883 // 1.2.2 OpenMP Language Terminology
1884 // Structured block - An executable statement with a single entry at the
1885 // top and a single exit at the bottom.
1886 // The point of exit cannot be a branch out of the structured block.
1887 // longjmp() and throw() must not violate the entry/exit criteria.
1888 CS->getCapturedDecl()->setNothrow();
1889
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001890 getCurFunction()->setHasBranchProtectedScope();
1891
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001892 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
1893 AStmt);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001894}
1895
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001896namespace {
1897/// \brief Helper class for checking canonical form of the OpenMP loops and
1898/// extracting iteration space of each loop in the loop nest, that will be used
1899/// for IR generation.
1900class OpenMPIterationSpaceChecker {
1901 /// \brief Reference to Sema.
1902 Sema &SemaRef;
1903 /// \brief A location for diagnostics (when there is no some better location).
1904 SourceLocation DefaultLoc;
1905 /// \brief A location for diagnostics (when increment is not compatible).
1906 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001907 /// \brief A source location for referring to loop init later.
1908 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001909 /// \brief A source location for referring to condition later.
1910 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001911 /// \brief A source location for referring to increment later.
1912 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001913 /// \brief Loop variable.
1914 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001915 /// \brief Reference to loop variable.
1916 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001917 /// \brief Lower bound (initializer for the var).
1918 Expr *LB;
1919 /// \brief Upper bound.
1920 Expr *UB;
1921 /// \brief Loop step (increment).
1922 Expr *Step;
1923 /// \brief This flag is true when condition is one of:
1924 /// Var < UB
1925 /// Var <= UB
1926 /// UB > Var
1927 /// UB >= Var
1928 bool TestIsLessOp;
1929 /// \brief This flag is true when condition is strict ( < or > ).
1930 bool TestIsStrictOp;
1931 /// \brief This flag is true when step is subtracted on each iteration.
1932 bool SubtractStep;
1933
1934public:
1935 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
1936 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00001937 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
1938 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001939 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
1940 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001941 /// \brief Check init-expr for canonical loop form and save loop counter
1942 /// variable - #Var and its initialization value - #LB.
1943 bool CheckInit(Stmt *S);
1944 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
1945 /// for less/greater and for strict/non-strict comparison.
1946 bool CheckCond(Expr *S);
1947 /// \brief Check incr-expr for canonical loop form and return true if it
1948 /// does not conform, otherwise save loop step (#Step).
1949 bool CheckInc(Expr *S);
1950 /// \brief Return the loop counter variable.
1951 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001952 /// \brief Return the reference expression to loop counter variable.
1953 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001954 /// \brief Source range of the loop init.
1955 SourceRange GetInitSrcRange() const { return InitSrcRange; }
1956 /// \brief Source range of the loop condition.
1957 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
1958 /// \brief Source range of the loop increment.
1959 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
1960 /// \brief True if the step should be subtracted.
1961 bool ShouldSubtractStep() const { return SubtractStep; }
1962 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00001963 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001964 /// \brief Build reference expression to the counter be used for codegen.
1965 Expr *BuildCounterVar() const;
1966 /// \brief Build initization of the counter be used for codegen.
1967 Expr *BuildCounterInit() const;
1968 /// \brief Build step of the counter be used for codegen.
1969 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001970 /// \brief Return true if any expression is dependent.
1971 bool Dependent() const;
1972
1973private:
1974 /// \brief Check the right-hand side of an assignment in the increment
1975 /// expression.
1976 bool CheckIncRHS(Expr *RHS);
1977 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001978 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001979 /// \brief Helper to set upper bound.
1980 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
1981 const SourceLocation &SL);
1982 /// \brief Helper to set loop increment.
1983 bool SetStep(Expr *NewStep, bool Subtract);
1984};
1985
1986bool OpenMPIterationSpaceChecker::Dependent() const {
1987 if (!Var) {
1988 assert(!LB && !UB && !Step);
1989 return false;
1990 }
1991 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
1992 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
1993}
1994
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001995bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
1996 DeclRefExpr *NewVarRefExpr,
1997 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001998 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001999 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2000 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002001 if (!NewVar || !NewLB)
2002 return true;
2003 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002004 VarRef = NewVarRefExpr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002005 LB = NewLB;
2006 return false;
2007}
2008
2009bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2010 const SourceRange &SR,
2011 const SourceLocation &SL) {
2012 // State consistency checking to ensure correct usage.
2013 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2014 !TestIsLessOp && !TestIsStrictOp);
2015 if (!NewUB)
2016 return true;
2017 UB = NewUB;
2018 TestIsLessOp = LessOp;
2019 TestIsStrictOp = StrictOp;
2020 ConditionSrcRange = SR;
2021 ConditionLoc = SL;
2022 return false;
2023}
2024
2025bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2026 // State consistency checking to ensure correct usage.
2027 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2028 if (!NewStep)
2029 return true;
2030 if (!NewStep->isValueDependent()) {
2031 // Check that the step is integer expression.
2032 SourceLocation StepLoc = NewStep->getLocStart();
2033 ExprResult Val =
2034 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2035 if (Val.isInvalid())
2036 return true;
2037 NewStep = Val.get();
2038
2039 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2040 // If test-expr is of form var relational-op b and relational-op is < or
2041 // <= then incr-expr must cause var to increase on each iteration of the
2042 // loop. If test-expr is of form var relational-op b and relational-op is
2043 // > or >= then incr-expr must cause var to decrease on each iteration of
2044 // the loop.
2045 // If test-expr is of form b relational-op var and relational-op is < or
2046 // <= then incr-expr must cause var to decrease on each iteration of the
2047 // loop. If test-expr is of form b relational-op var and relational-op is
2048 // > or >= then incr-expr must cause var to increase on each iteration of
2049 // the loop.
2050 llvm::APSInt Result;
2051 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2052 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2053 bool IsConstNeg =
2054 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002055 bool IsConstPos =
2056 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002057 bool IsConstZero = IsConstant && !Result.getBoolValue();
2058 if (UB && (IsConstZero ||
2059 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002060 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002061 SemaRef.Diag(NewStep->getExprLoc(),
2062 diag::err_omp_loop_incr_not_compatible)
2063 << Var << TestIsLessOp << NewStep->getSourceRange();
2064 SemaRef.Diag(ConditionLoc,
2065 diag::note_omp_loop_cond_requres_compatible_incr)
2066 << TestIsLessOp << ConditionSrcRange;
2067 return true;
2068 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002069 if (TestIsLessOp == Subtract) {
2070 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2071 NewStep).get();
2072 Subtract = !Subtract;
2073 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002074 }
2075
2076 Step = NewStep;
2077 SubtractStep = Subtract;
2078 return false;
2079}
2080
2081bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S) {
2082 // Check init-expr for canonical loop form and save loop counter
2083 // variable - #Var and its initialization value - #LB.
2084 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2085 // var = lb
2086 // integer-type var = lb
2087 // random-access-iterator-type var = lb
2088 // pointer-type var = lb
2089 //
2090 if (!S) {
2091 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2092 return true;
2093 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002094 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002095 if (Expr *E = dyn_cast<Expr>(S))
2096 S = E->IgnoreParens();
2097 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2098 if (BO->getOpcode() == BO_Assign)
2099 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002100 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002101 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002102 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2103 if (DS->isSingleDecl()) {
2104 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2105 if (Var->hasInit()) {
2106 // Accept non-canonical init form here but emit ext. warning.
2107 if (Var->getInitStyle() != VarDecl::CInit)
2108 SemaRef.Diag(S->getLocStart(),
2109 diag::ext_omp_loop_not_canonical_init)
2110 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002111 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002112 }
2113 }
2114 }
2115 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2116 if (CE->getOperator() == OO_Equal)
2117 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002118 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2119 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002120
2121 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2122 << S->getSourceRange();
2123 return true;
2124}
2125
Alexey Bataev23b69422014-06-18 07:08:49 +00002126/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002127/// variable (which may be the loop variable) if possible.
2128static const VarDecl *GetInitVarDecl(const Expr *E) {
2129 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002130 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002131 E = E->IgnoreParenImpCasts();
2132 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2133 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2134 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
2135 CE->getArg(0) != nullptr)
2136 E = CE->getArg(0)->IgnoreParenImpCasts();
2137 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2138 if (!DRE)
2139 return nullptr;
2140 return dyn_cast<VarDecl>(DRE->getDecl());
2141}
2142
2143bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2144 // Check test-expr for canonical form, save upper-bound UB, flags for
2145 // less/greater and for strict/non-strict comparison.
2146 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2147 // var relational-op b
2148 // b relational-op var
2149 //
2150 if (!S) {
2151 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2152 return true;
2153 }
2154 S = S->IgnoreParenImpCasts();
2155 SourceLocation CondLoc = S->getLocStart();
2156 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2157 if (BO->isRelationalOp()) {
2158 if (GetInitVarDecl(BO->getLHS()) == Var)
2159 return SetUB(BO->getRHS(),
2160 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2161 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2162 BO->getSourceRange(), BO->getOperatorLoc());
2163 if (GetInitVarDecl(BO->getRHS()) == Var)
2164 return SetUB(BO->getLHS(),
2165 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2166 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2167 BO->getSourceRange(), BO->getOperatorLoc());
2168 }
2169 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2170 if (CE->getNumArgs() == 2) {
2171 auto Op = CE->getOperator();
2172 switch (Op) {
2173 case OO_Greater:
2174 case OO_GreaterEqual:
2175 case OO_Less:
2176 case OO_LessEqual:
2177 if (GetInitVarDecl(CE->getArg(0)) == Var)
2178 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2179 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2180 CE->getOperatorLoc());
2181 if (GetInitVarDecl(CE->getArg(1)) == Var)
2182 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2183 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2184 CE->getOperatorLoc());
2185 break;
2186 default:
2187 break;
2188 }
2189 }
2190 }
2191 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2192 << S->getSourceRange() << Var;
2193 return true;
2194}
2195
2196bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2197 // RHS of canonical loop form increment can be:
2198 // var + incr
2199 // incr + var
2200 // var - incr
2201 //
2202 RHS = RHS->IgnoreParenImpCasts();
2203 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2204 if (BO->isAdditiveOp()) {
2205 bool IsAdd = BO->getOpcode() == BO_Add;
2206 if (GetInitVarDecl(BO->getLHS()) == Var)
2207 return SetStep(BO->getRHS(), !IsAdd);
2208 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2209 return SetStep(BO->getLHS(), false);
2210 }
2211 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2212 bool IsAdd = CE->getOperator() == OO_Plus;
2213 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2214 if (GetInitVarDecl(CE->getArg(0)) == Var)
2215 return SetStep(CE->getArg(1), !IsAdd);
2216 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2217 return SetStep(CE->getArg(0), false);
2218 }
2219 }
2220 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2221 << RHS->getSourceRange() << Var;
2222 return true;
2223}
2224
2225bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2226 // Check incr-expr for canonical loop form and return true if it
2227 // does not conform.
2228 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2229 // ++var
2230 // var++
2231 // --var
2232 // var--
2233 // var += incr
2234 // var -= incr
2235 // var = var + incr
2236 // var = incr + var
2237 // var = var - incr
2238 //
2239 if (!S) {
2240 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2241 return true;
2242 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002243 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002244 S = S->IgnoreParens();
2245 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2246 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2247 return SetStep(
2248 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2249 (UO->isDecrementOp() ? -1 : 1)).get(),
2250 false);
2251 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2252 switch (BO->getOpcode()) {
2253 case BO_AddAssign:
2254 case BO_SubAssign:
2255 if (GetInitVarDecl(BO->getLHS()) == Var)
2256 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2257 break;
2258 case BO_Assign:
2259 if (GetInitVarDecl(BO->getLHS()) == Var)
2260 return CheckIncRHS(BO->getRHS());
2261 break;
2262 default:
2263 break;
2264 }
2265 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2266 switch (CE->getOperator()) {
2267 case OO_PlusPlus:
2268 case OO_MinusMinus:
2269 if (GetInitVarDecl(CE->getArg(0)) == Var)
2270 return SetStep(
2271 SemaRef.ActOnIntegerConstant(
2272 CE->getLocStart(),
2273 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2274 false);
2275 break;
2276 case OO_PlusEqual:
2277 case OO_MinusEqual:
2278 if (GetInitVarDecl(CE->getArg(0)) == Var)
2279 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2280 break;
2281 case OO_Equal:
2282 if (GetInitVarDecl(CE->getArg(0)) == Var)
2283 return CheckIncRHS(CE->getArg(1));
2284 break;
2285 default:
2286 break;
2287 }
2288 }
2289 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2290 << S->getSourceRange() << Var;
2291 return true;
2292}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002293
2294/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002295Expr *
2296OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2297 const bool LimitedType) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002298 ExprResult Diff;
2299 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2300 SemaRef.getLangOpts().CPlusPlus) {
2301 // Upper - Lower
2302 Expr *Upper = TestIsLessOp ? UB : LB;
2303 Expr *Lower = TestIsLessOp ? LB : UB;
2304
2305 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2306
2307 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2308 // BuildBinOp already emitted error, this one is to point user to upper
2309 // and lower bound, and to tell what is passed to 'operator-'.
2310 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2311 << Upper->getSourceRange() << Lower->getSourceRange();
2312 return nullptr;
2313 }
2314 }
2315
2316 if (!Diff.isUsable())
2317 return nullptr;
2318
2319 // Upper - Lower [- 1]
2320 if (TestIsStrictOp)
2321 Diff = SemaRef.BuildBinOp(
2322 S, DefaultLoc, BO_Sub, Diff.get(),
2323 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2324 if (!Diff.isUsable())
2325 return nullptr;
2326
2327 // Upper - Lower [- 1] + Step
2328 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2329 Step->IgnoreImplicit());
2330 if (!Diff.isUsable())
2331 return nullptr;
2332
2333 // Parentheses (for dumping/debugging purposes only).
2334 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2335 if (!Diff.isUsable())
2336 return nullptr;
2337
2338 // (Upper - Lower [- 1] + Step) / Step
2339 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2340 Step->IgnoreImplicit());
2341 if (!Diff.isUsable())
2342 return nullptr;
2343
Alexander Musman174b3ca2014-10-06 11:16:29 +00002344 // OpenMP runtime requires 32-bit or 64-bit loop variables.
2345 if (LimitedType) {
2346 auto &C = SemaRef.Context;
2347 QualType Type = Diff.get()->getType();
2348 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2349 if (NewSize != C.getTypeSize(Type)) {
2350 if (NewSize < C.getTypeSize(Type)) {
2351 assert(NewSize == 64 && "incorrect loop var size");
2352 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2353 << InitSrcRange << ConditionSrcRange;
2354 }
2355 QualType NewType = C.getIntTypeForBitwidth(
2356 NewSize, Type->hasSignedIntegerRepresentation());
2357 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2358 Sema::AA_Converting, true);
2359 if (!Diff.isUsable())
2360 return nullptr;
2361 }
2362 }
2363
Alexander Musmana5f070a2014-10-01 06:03:56 +00002364 return Diff.get();
2365}
2366
2367/// \brief Build reference expression to the counter be used for codegen.
2368Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
2369 return DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2370 GetIncrementSrcRange().getBegin(), Var, false,
2371 DefaultLoc, Var->getType(), VK_LValue);
2372}
2373
2374/// \brief Build initization of the counter be used for codegen.
2375Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2376
2377/// \brief Build step of the counter be used for codegen.
2378Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2379
2380/// \brief Iteration space of a single for loop.
2381struct LoopIterationSpace {
2382 /// \brief This expression calculates the number of iterations in the loop.
2383 /// It is always possible to calculate it before starting the loop.
2384 Expr *NumIterations;
2385 /// \brief The loop counter variable.
2386 Expr *CounterVar;
2387 /// \brief This is initializer for the initial value of #CounterVar.
2388 Expr *CounterInit;
2389 /// \brief This is step for the #CounterVar used to generate its update:
2390 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2391 Expr *CounterStep;
2392 /// \brief Should step be subtracted?
2393 bool Subtract;
2394 /// \brief Source range of the loop init.
2395 SourceRange InitSrcRange;
2396 /// \brief Source range of the loop condition.
2397 SourceRange CondSrcRange;
2398 /// \brief Source range of the loop increment.
2399 SourceRange IncSrcRange;
2400};
2401
Alexey Bataev23b69422014-06-18 07:08:49 +00002402} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002403
2404/// \brief Called on a for stmt to check and extract its iteration space
2405/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00002406static bool CheckOpenMPIterationSpace(
2407 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2408 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2409 Expr *NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002410 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2411 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002412 // OpenMP [2.6, Canonical Loop Form]
2413 // for (init-expr; test-expr; incr-expr) structured-block
2414 auto For = dyn_cast_or_null<ForStmt>(S);
2415 if (!For) {
2416 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002417 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2418 << NestedLoopCount << (CurrentNestedLoopCount > 0)
2419 << CurrentNestedLoopCount;
2420 if (NestedLoopCount > 1)
2421 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2422 diag::note_omp_collapse_expr)
2423 << NestedLoopCountExpr->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002424 return true;
2425 }
2426 assert(For->getBody());
2427
2428 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2429
2430 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002431 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002432 if (ISC.CheckInit(Init)) {
2433 return true;
2434 }
2435
2436 bool HasErrors = false;
2437
2438 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002439 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002440
2441 // OpenMP [2.6, Canonical Loop Form]
2442 // Var is one of the following:
2443 // A variable of signed or unsigned integer type.
2444 // For C++, a variable of a random access iterator type.
2445 // For C, a variable of a pointer type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002446 auto VarType = Var->getType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002447 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2448 !VarType->isPointerType() &&
2449 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2450 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2451 << SemaRef.getLangOpts().CPlusPlus;
2452 HasErrors = true;
2453 }
2454
Alexey Bataev4acb8592014-07-07 13:01:15 +00002455 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2456 // Construct
2457 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2458 // parallel for construct is (are) private.
2459 // The loop iteration variable in the associated for-loop of a simd construct
2460 // with just one associated for-loop is linear with a constant-linear-step
2461 // that is the increment of the associated for-loop.
2462 // Exclude loop var from the list of variables with implicitly defined data
2463 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00002464 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002465
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002466 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2467 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00002468 // The loop iteration variable in the associated for-loop of a simd construct
2469 // with just one associated for-loop may be listed in a linear clause with a
2470 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00002471 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2472 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002473 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002474 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2475 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2476 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002477 auto PredeterminedCKind =
2478 isOpenMPSimdDirective(DKind)
2479 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2480 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002481 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002482 DVar.CKind != PredeterminedCKind) ||
Alexander Musmanf82886e2014-09-18 05:12:34 +00002483 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2484 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
2485 DVar.CKind != OMPC_lastprivate)) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00002486 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002487 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00002488 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2489 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002490 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002491 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002492 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002493 // Make the loop iteration variable private (for worksharing constructs),
2494 // linear (for simd directives with the only one associated loop) or
2495 // lastprivate (for simd directives with several collapsed loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00002496 // FIXME: the next check and error message must be removed once the
2497 // capturing of global variables in loops is fixed.
2498 if (DVar.CKind == OMPC_unknown)
2499 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2500 /*FromParent=*/false);
2501 if (!Var->hasLocalStorage() && DVar.CKind == OMPC_unknown) {
2502 SemaRef.Diag(Init->getLocStart(), diag::err_omp_global_loop_var_dsa)
2503 << getOpenMPClauseName(PredeterminedCKind)
2504 << getOpenMPDirectiveName(DKind);
2505 HasErrors = true;
2506 } else
2507 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002508 }
2509
Alexey Bataev7ff55242014-06-19 09:13:45 +00002510 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00002511
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002512 // Check test-expr.
2513 HasErrors |= ISC.CheckCond(For->getCond());
2514
2515 // Check incr-expr.
2516 HasErrors |= ISC.CheckInc(For->getInc());
2517
Alexander Musmana5f070a2014-10-01 06:03:56 +00002518 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002519 return HasErrors;
2520
Alexander Musmana5f070a2014-10-01 06:03:56 +00002521 // Build the loop's iteration space representation.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002522 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2523 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
Alexander Musmana5f070a2014-10-01 06:03:56 +00002524 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2525 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2526 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2527 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2528 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2529 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2530 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2531
2532 HasErrors |= (ResultIterSpace.NumIterations == nullptr ||
2533 ResultIterSpace.CounterVar == nullptr ||
2534 ResultIterSpace.CounterInit == nullptr ||
2535 ResultIterSpace.CounterStep == nullptr);
2536
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002537 return HasErrors;
2538}
2539
Alexander Musmana5f070a2014-10-01 06:03:56 +00002540/// \brief Build a variable declaration for OpenMP loop iteration variable.
2541static VarDecl *BuildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
2542 StringRef Name) {
2543 DeclContext *DC = SemaRef.CurContext;
2544 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2545 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2546 VarDecl *Decl =
2547 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
2548 Decl->setImplicit();
2549 return Decl;
2550}
2551
2552/// \brief Build 'VarRef = Start + Iter * Step'.
2553static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2554 SourceLocation Loc, ExprResult VarRef,
2555 ExprResult Start, ExprResult Iter,
2556 ExprResult Step, bool Subtract) {
2557 // Add parentheses (for debugging purposes only).
2558 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2559 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2560 !Step.isUsable())
2561 return ExprError();
2562
2563 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2564 Step.get()->IgnoreImplicit());
2565 if (!Update.isUsable())
2566 return ExprError();
2567
2568 // Build 'VarRef = Start + Iter * Step'.
2569 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2570 Start.get()->IgnoreImplicit(), Update.get());
2571 if (!Update.isUsable())
2572 return ExprError();
2573
2574 Update = SemaRef.PerformImplicitConversion(
2575 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2576 if (!Update.isUsable())
2577 return ExprError();
2578
2579 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2580 return Update;
2581}
2582
2583/// \brief Convert integer expression \a E to make it have at least \a Bits
2584/// bits.
2585static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2586 Sema &SemaRef) {
2587 if (E == nullptr)
2588 return ExprError();
2589 auto &C = SemaRef.Context;
2590 QualType OldType = E->getType();
2591 unsigned HasBits = C.getTypeSize(OldType);
2592 if (HasBits >= Bits)
2593 return ExprResult(E);
2594 // OK to convert to signed, because new type has more bits than old.
2595 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2596 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2597 true);
2598}
2599
2600/// \brief Check if the given expression \a E is a constant integer that fits
2601/// into \a Bits bits.
2602static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2603 if (E == nullptr)
2604 return false;
2605 llvm::APSInt Result;
2606 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2607 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2608 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002609}
2610
2611/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00002612/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2613/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002614static unsigned
2615CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2616 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002617 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00002618 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002619 unsigned NestedLoopCount = 1;
2620 if (NestedLoopCountExpr) {
2621 // Found 'collapse' clause - calculate collapse number.
2622 llvm::APSInt Result;
2623 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2624 NestedLoopCount = Result.getLimitedValue();
2625 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002626 // This is helper routine for loop directives (e.g., 'for', 'simd',
2627 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00002628 SmallVector<LoopIterationSpace, 4> IterSpaces;
2629 IterSpaces.resize(NestedLoopCount);
2630 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002631 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002632 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev4acb8592014-07-07 13:01:15 +00002633 NestedLoopCount, NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002634 VarsWithImplicitDSA, IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00002635 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002636 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002637 // OpenMP [2.8.1, simd construct, Restrictions]
2638 // All loops associated with the construct must be perfectly nested; that
2639 // is, there must be no intervening code nor any OpenMP directive between
2640 // any two loops.
2641 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002642 }
2643
Alexander Musmana5f070a2014-10-01 06:03:56 +00002644 Built.clear(/* size */ NestedLoopCount);
2645
2646 if (SemaRef.CurContext->isDependentContext())
2647 return NestedLoopCount;
2648
2649 // An example of what is generated for the following code:
2650 //
2651 // #pragma omp simd collapse(2)
2652 // for (i = 0; i < NI; ++i)
2653 // for (j = J0; j < NJ; j+=2) {
2654 // <loop body>
2655 // }
2656 //
2657 // We generate the code below.
2658 // Note: the loop body may be outlined in CodeGen.
2659 // Note: some counters may be C++ classes, operator- is used to find number of
2660 // iterations and operator+= to calculate counter value.
2661 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2662 // or i64 is currently supported).
2663 //
2664 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2665 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2666 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2667 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2668 // // similar updates for vars in clauses (e.g. 'linear')
2669 // <loop body (using local i and j)>
2670 // }
2671 // i = NI; // assign final values of counters
2672 // j = NJ;
2673 //
2674
2675 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2676 // the iteration counts of the collapsed for loops.
2677 auto N0 = IterSpaces[0].NumIterations;
2678 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2679 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2680
2681 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2682 return NestedLoopCount;
2683
2684 auto &C = SemaRef.Context;
2685 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
2686
2687 Scope *CurScope = DSA.getCurScope();
2688 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
2689 auto N = IterSpaces[Cnt].NumIterations;
2690 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
2691 if (LastIteration32.isUsable())
2692 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2693 LastIteration32.get(), N);
2694 if (LastIteration64.isUsable())
2695 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2696 LastIteration64.get(), N);
2697 }
2698
2699 // Choose either the 32-bit or 64-bit version.
2700 ExprResult LastIteration = LastIteration64;
2701 if (LastIteration32.isUsable() &&
2702 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
2703 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
2704 FitsInto(
2705 32 /* Bits */,
2706 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
2707 LastIteration64.get(), SemaRef)))
2708 LastIteration = LastIteration32;
2709
2710 if (!LastIteration.isUsable())
2711 return 0;
2712
2713 // Save the number of iterations.
2714 ExprResult NumIterations = LastIteration;
2715 {
2716 LastIteration = SemaRef.BuildBinOp(
2717 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
2718 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2719 if (!LastIteration.isUsable())
2720 return 0;
2721 }
2722
2723 // Calculate the last iteration number beforehand instead of doing this on
2724 // each iteration. Do not do this if the number of iterations may be kfold-ed.
2725 llvm::APSInt Result;
2726 bool IsConstant =
2727 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
2728 ExprResult CalcLastIteration;
2729 if (!IsConstant) {
2730 SourceLocation SaveLoc;
2731 VarDecl *SaveVar =
2732 BuildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
2733 ".omp.last.iteration");
2734 ExprResult SaveRef = SemaRef.BuildDeclRefExpr(
2735 SaveVar, LastIteration.get()->getType(), VK_LValue, SaveLoc);
2736 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
2737 SaveRef.get(), LastIteration.get());
2738 LastIteration = SaveRef;
2739
2740 // Prepare SaveRef + 1.
2741 NumIterations = SemaRef.BuildBinOp(
2742 CurScope, SaveLoc, BO_Add, SaveRef.get(),
2743 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2744 if (!NumIterations.isUsable())
2745 return 0;
2746 }
2747
2748 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
2749
2750 // Precondition tests if there is at least one iteration (LastIteration > 0).
2751 ExprResult PreCond = SemaRef.BuildBinOp(
2752 CurScope, InitLoc, BO_GT, LastIteration.get(),
2753 SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get());
2754
Alexander Musmanc6388682014-12-15 07:07:06 +00002755 QualType VType = LastIteration.get()->getType();
2756 // Build variables passed into runtime, nesessary for worksharing directives.
2757 ExprResult LB, UB, IL, ST, EUB;
2758 if (isOpenMPWorksharingDirective(DKind)) {
2759 // Lower bound variable, initialized with zero.
2760 VarDecl *LBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
2761 LB = SemaRef.BuildDeclRefExpr(LBDecl, VType, VK_LValue, InitLoc);
2762 SemaRef.AddInitializerToDecl(
2763 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2764 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2765
2766 // Upper bound variable, initialized with last iteration number.
2767 VarDecl *UBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
2768 UB = SemaRef.BuildDeclRefExpr(UBDecl, VType, VK_LValue, InitLoc);
2769 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
2770 /*DirectInit*/ false,
2771 /*TypeMayContainAuto*/ false);
2772
2773 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
2774 // This will be used to implement clause 'lastprivate'.
2775 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
2776 VarDecl *ILDecl = BuildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
2777 IL = SemaRef.BuildDeclRefExpr(ILDecl, Int32Ty, VK_LValue, InitLoc);
2778 SemaRef.AddInitializerToDecl(
2779 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2780 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2781
2782 // Stride variable returned by runtime (we initialize it to 1 by default).
2783 VarDecl *STDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
2784 ST = SemaRef.BuildDeclRefExpr(STDecl, VType, VK_LValue, InitLoc);
2785 SemaRef.AddInitializerToDecl(
2786 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
2787 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2788
2789 // Build expression: UB = min(UB, LastIteration)
2790 // It is nesessary for CodeGen of directives with static scheduling.
2791 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
2792 UB.get(), LastIteration.get());
2793 ExprResult CondOp = SemaRef.ActOnConditionalOp(
2794 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
2795 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
2796 CondOp.get());
2797 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
2798 }
2799
2800 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002801 ExprResult IV;
2802 ExprResult Init;
2803 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002804 VarDecl *IVDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
2805 IV = SemaRef.BuildDeclRefExpr(IVDecl, VType, VK_LValue, InitLoc);
2806 Expr *RHS = isOpenMPWorksharingDirective(DKind)
2807 ? LB.get()
2808 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
2809 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
2810 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002811 }
2812
Alexander Musmanc6388682014-12-15 07:07:06 +00002813 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002814 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00002815 ExprResult Cond =
2816 isOpenMPWorksharingDirective(DKind)
2817 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
2818 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
2819 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002820 // Loop condition with 1 iteration separated (IV < LastIteration)
2821 ExprResult SeparatedCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT,
2822 IV.get(), LastIteration.get());
2823
2824 // Loop increment (IV = IV + 1)
2825 SourceLocation IncLoc;
2826 ExprResult Inc =
2827 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
2828 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
2829 if (!Inc.isUsable())
2830 return 0;
2831 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00002832 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
2833 if (!Inc.isUsable())
2834 return 0;
2835
2836 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
2837 // Used for directives with static scheduling.
2838 ExprResult NextLB, NextUB;
2839 if (isOpenMPWorksharingDirective(DKind)) {
2840 // LB + ST
2841 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
2842 if (!NextLB.isUsable())
2843 return 0;
2844 // LB = LB + ST
2845 NextLB =
2846 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
2847 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
2848 if (!NextLB.isUsable())
2849 return 0;
2850 // UB + ST
2851 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
2852 if (!NextUB.isUsable())
2853 return 0;
2854 // UB = UB + ST
2855 NextUB =
2856 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
2857 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
2858 if (!NextUB.isUsable())
2859 return 0;
2860 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002861
2862 // Build updates and final values of the loop counters.
2863 bool HasErrors = false;
2864 Built.Counters.resize(NestedLoopCount);
2865 Built.Updates.resize(NestedLoopCount);
2866 Built.Finals.resize(NestedLoopCount);
2867 {
2868 ExprResult Div;
2869 // Go from inner nested loop to outer.
2870 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
2871 LoopIterationSpace &IS = IterSpaces[Cnt];
2872 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
2873 // Build: Iter = (IV / Div) % IS.NumIters
2874 // where Div is product of previous iterations' IS.NumIters.
2875 ExprResult Iter;
2876 if (Div.isUsable()) {
2877 Iter =
2878 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
2879 } else {
2880 Iter = IV;
2881 assert((Cnt == (int)NestedLoopCount - 1) &&
2882 "unusable div expected on first iteration only");
2883 }
2884
2885 if (Cnt != 0 && Iter.isUsable())
2886 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
2887 IS.NumIterations);
2888 if (!Iter.isUsable()) {
2889 HasErrors = true;
2890 break;
2891 }
2892
2893 // Build update: IS.CounterVar = IS.Start + Iter * IS.Step
2894 ExprResult Update =
2895 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, IS.CounterVar,
2896 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
2897 if (!Update.isUsable()) {
2898 HasErrors = true;
2899 break;
2900 }
2901
2902 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
2903 ExprResult Final = BuildCounterUpdate(
2904 SemaRef, CurScope, UpdLoc, IS.CounterVar, IS.CounterInit,
2905 IS.NumIterations, IS.CounterStep, IS.Subtract);
2906 if (!Final.isUsable()) {
2907 HasErrors = true;
2908 break;
2909 }
2910
2911 // Build Div for the next iteration: Div <- Div * IS.NumIters
2912 if (Cnt != 0) {
2913 if (Div.isUnset())
2914 Div = IS.NumIterations;
2915 else
2916 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
2917 IS.NumIterations);
2918
2919 // Add parentheses (for debugging purposes only).
2920 if (Div.isUsable())
2921 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
2922 if (!Div.isUsable()) {
2923 HasErrors = true;
2924 break;
2925 }
2926 }
2927 if (!Update.isUsable() || !Final.isUsable()) {
2928 HasErrors = true;
2929 break;
2930 }
2931 // Save results
2932 Built.Counters[Cnt] = IS.CounterVar;
2933 Built.Updates[Cnt] = Update.get();
2934 Built.Finals[Cnt] = Final.get();
2935 }
2936 }
2937
2938 if (HasErrors)
2939 return 0;
2940
2941 // Save results
2942 Built.IterationVarRef = IV.get();
2943 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00002944 Built.NumIterations = NumIterations.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002945 Built.CalcLastIteration = CalcLastIteration.get();
2946 Built.PreCond = PreCond.get();
2947 Built.Cond = Cond.get();
2948 Built.SeparatedCond = SeparatedCond.get();
2949 Built.Init = Init.get();
2950 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00002951 Built.LB = LB.get();
2952 Built.UB = UB.get();
2953 Built.IL = IL.get();
2954 Built.ST = ST.get();
2955 Built.EUB = EUB.get();
2956 Built.NLB = NextLB.get();
2957 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002958
Alexey Bataevabfc0692014-06-25 06:52:00 +00002959 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002960}
2961
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002962static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002963 auto CollapseFilter = [](const OMPClause *C) -> bool {
2964 return C->getClauseKind() == OMPC_collapse;
2965 };
2966 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
2967 Clauses, CollapseFilter);
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002968 if (I)
2969 return cast<OMPCollapseClause>(*I)->getNumForLoops();
2970 return nullptr;
2971}
2972
Alexey Bataev4acb8592014-07-07 13:01:15 +00002973StmtResult Sema::ActOnOpenMPSimdDirective(
2974 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2975 SourceLocation EndLoc,
2976 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002977 OMPLoopDirective::HelperExprs B;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002978 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002979 unsigned NestedLoopCount =
2980 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002981 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00002982 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002983 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002984
Alexander Musmana5f070a2014-10-01 06:03:56 +00002985 assert((CurContext->isDependentContext() || B.builtAll()) &&
2986 "omp simd loop exprs were not built");
2987
Alexander Musman3276a272015-03-21 10:12:56 +00002988 if (!CurContext->isDependentContext()) {
2989 // Finalize the clauses that need pre-built expressions for CodeGen.
2990 for (auto C : Clauses) {
2991 if (auto LC = dyn_cast<OMPLinearClause>(C))
2992 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
2993 B.NumIterations, *this, CurScope))
2994 return StmtError();
2995 }
2996 }
2997
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002998 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00002999 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3000 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003001}
3002
Alexey Bataev4acb8592014-07-07 13:01:15 +00003003StmtResult Sema::ActOnOpenMPForDirective(
3004 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3005 SourceLocation EndLoc,
3006 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003007 OMPLoopDirective::HelperExprs B;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003008 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003009 unsigned NestedLoopCount =
3010 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003011 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003012 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00003013 return StmtError();
3014
Alexander Musmana5f070a2014-10-01 06:03:56 +00003015 assert((CurContext->isDependentContext() || B.builtAll()) &&
3016 "omp for loop exprs were not built");
3017
Alexey Bataevf29276e2014-06-18 04:14:57 +00003018 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003019 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3020 Clauses, AStmt, B);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003021}
3022
Alexander Musmanf82886e2014-09-18 05:12:34 +00003023StmtResult Sema::ActOnOpenMPForSimdDirective(
3024 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3025 SourceLocation EndLoc,
3026 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003027 OMPLoopDirective::HelperExprs B;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003028 // In presence of clause 'collapse', it will define the nested loops number.
3029 unsigned NestedLoopCount =
3030 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003031 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003032 if (NestedLoopCount == 0)
3033 return StmtError();
3034
Alexander Musmanc6388682014-12-15 07:07:06 +00003035 assert((CurContext->isDependentContext() || B.builtAll()) &&
3036 "omp for simd loop exprs were not built");
3037
Alexander Musmanf82886e2014-09-18 05:12:34 +00003038 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003039 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3040 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003041}
3042
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003043StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3044 Stmt *AStmt,
3045 SourceLocation StartLoc,
3046 SourceLocation EndLoc) {
3047 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3048 auto BaseStmt = AStmt;
3049 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3050 BaseStmt = CS->getCapturedStmt();
3051 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3052 auto S = C->children();
3053 if (!S)
3054 return StmtError();
3055 // All associated statements must be '#pragma omp section' except for
3056 // the first one.
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003057 for (++S; S; ++S) {
3058 auto SectionStmt = *S;
3059 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3060 if (SectionStmt)
3061 Diag(SectionStmt->getLocStart(),
3062 diag::err_omp_sections_substmt_not_section);
3063 return StmtError();
3064 }
3065 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003066 } else {
3067 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3068 return StmtError();
3069 }
3070
3071 getCurFunction()->setHasBranchProtectedScope();
3072
3073 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3074 AStmt);
3075}
3076
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003077StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3078 SourceLocation StartLoc,
3079 SourceLocation EndLoc) {
3080 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3081
3082 getCurFunction()->setHasBranchProtectedScope();
3083
3084 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3085}
3086
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003087StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3088 Stmt *AStmt,
3089 SourceLocation StartLoc,
3090 SourceLocation EndLoc) {
Alexey Bataev74a05c92014-07-15 02:55:09 +00003091 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3092
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003093 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00003094
Alexey Bataev3255bf32015-01-19 05:20:46 +00003095 // OpenMP [2.7.3, single Construct, Restrictions]
3096 // The copyprivate clause must not be used with the nowait clause.
3097 OMPClause *Nowait = nullptr;
3098 OMPClause *Copyprivate = nullptr;
3099 for (auto *Clause : Clauses) {
3100 if (Clause->getClauseKind() == OMPC_nowait)
3101 Nowait = Clause;
3102 else if (Clause->getClauseKind() == OMPC_copyprivate)
3103 Copyprivate = Clause;
3104 if (Copyprivate && Nowait) {
3105 Diag(Copyprivate->getLocStart(),
3106 diag::err_omp_single_copyprivate_with_nowait);
3107 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3108 return StmtError();
3109 }
3110 }
3111
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003112 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3113}
3114
Alexander Musman80c22892014-07-17 08:54:58 +00003115StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3116 SourceLocation StartLoc,
3117 SourceLocation EndLoc) {
3118 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3119
3120 getCurFunction()->setHasBranchProtectedScope();
3121
3122 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3123}
3124
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003125StmtResult
3126Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3127 Stmt *AStmt, SourceLocation StartLoc,
3128 SourceLocation EndLoc) {
3129 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3130
3131 getCurFunction()->setHasBranchProtectedScope();
3132
3133 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3134 AStmt);
3135}
3136
Alexey Bataev4acb8592014-07-07 13:01:15 +00003137StmtResult Sema::ActOnOpenMPParallelForDirective(
3138 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3139 SourceLocation EndLoc,
3140 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3141 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3142 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3143 // 1.2.2 OpenMP Language Terminology
3144 // Structured block - An executable statement with a single entry at the
3145 // top and a single exit at the bottom.
3146 // The point of exit cannot be a branch out of the structured block.
3147 // longjmp() and throw() must not violate the entry/exit criteria.
3148 CS->getCapturedDecl()->setNothrow();
3149
Alexander Musmanc6388682014-12-15 07:07:06 +00003150 OMPLoopDirective::HelperExprs B;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003151 // In presence of clause 'collapse', it will define the nested loops number.
3152 unsigned NestedLoopCount =
3153 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003154 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003155 if (NestedLoopCount == 0)
3156 return StmtError();
3157
Alexander Musmana5f070a2014-10-01 06:03:56 +00003158 assert((CurContext->isDependentContext() || B.builtAll()) &&
3159 "omp parallel for loop exprs were not built");
3160
Alexey Bataev4acb8592014-07-07 13:01:15 +00003161 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003162 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3163 NestedLoopCount, Clauses, AStmt, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003164}
3165
Alexander Musmane4e893b2014-09-23 09:33:00 +00003166StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3167 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3168 SourceLocation EndLoc,
3169 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3170 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3171 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3172 // 1.2.2 OpenMP Language Terminology
3173 // Structured block - An executable statement with a single entry at the
3174 // top and a single exit at the bottom.
3175 // The point of exit cannot be a branch out of the structured block.
3176 // longjmp() and throw() must not violate the entry/exit criteria.
3177 CS->getCapturedDecl()->setNothrow();
3178
Alexander Musmanc6388682014-12-15 07:07:06 +00003179 OMPLoopDirective::HelperExprs B;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003180 // In presence of clause 'collapse', it will define the nested loops number.
3181 unsigned NestedLoopCount =
3182 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003183 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003184 if (NestedLoopCount == 0)
3185 return StmtError();
3186
3187 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003188 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00003189 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003190}
3191
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003192StmtResult
3193Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3194 Stmt *AStmt, SourceLocation StartLoc,
3195 SourceLocation EndLoc) {
3196 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3197 auto BaseStmt = AStmt;
3198 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3199 BaseStmt = CS->getCapturedStmt();
3200 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3201 auto S = C->children();
3202 if (!S)
3203 return StmtError();
3204 // All associated statements must be '#pragma omp section' except for
3205 // the first one.
3206 for (++S; S; ++S) {
3207 auto SectionStmt = *S;
3208 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3209 if (SectionStmt)
3210 Diag(SectionStmt->getLocStart(),
3211 diag::err_omp_parallel_sections_substmt_not_section);
3212 return StmtError();
3213 }
3214 }
3215 } else {
3216 Diag(AStmt->getLocStart(),
3217 diag::err_omp_parallel_sections_not_compound_stmt);
3218 return StmtError();
3219 }
3220
3221 getCurFunction()->setHasBranchProtectedScope();
3222
3223 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3224 Clauses, AStmt);
3225}
3226
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003227StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3228 Stmt *AStmt, SourceLocation StartLoc,
3229 SourceLocation EndLoc) {
3230 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3231 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3232 // 1.2.2 OpenMP Language Terminology
3233 // Structured block - An executable statement with a single entry at the
3234 // top and a single exit at the bottom.
3235 // The point of exit cannot be a branch out of the structured block.
3236 // longjmp() and throw() must not violate the entry/exit criteria.
3237 CS->getCapturedDecl()->setNothrow();
3238
3239 getCurFunction()->setHasBranchProtectedScope();
3240
3241 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3242}
3243
Alexey Bataev68446b72014-07-18 07:47:19 +00003244StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3245 SourceLocation EndLoc) {
3246 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3247}
3248
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003249StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3250 SourceLocation EndLoc) {
3251 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3252}
3253
Alexey Bataev2df347a2014-07-18 10:17:07 +00003254StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3255 SourceLocation EndLoc) {
3256 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3257}
3258
Alexey Bataev6125da92014-07-21 11:26:11 +00003259StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3260 SourceLocation StartLoc,
3261 SourceLocation EndLoc) {
3262 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3263 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3264}
3265
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003266StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3267 SourceLocation StartLoc,
3268 SourceLocation EndLoc) {
3269 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3270
3271 getCurFunction()->setHasBranchProtectedScope();
3272
3273 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3274}
3275
Alexey Bataev1d160b12015-03-13 12:27:31 +00003276namespace {
3277/// \brief Helper class for checking expression in 'omp atomic [update]'
3278/// construct.
3279class OpenMPAtomicUpdateChecker {
3280 /// \brief Error results for atomic update expressions.
3281 enum ExprAnalysisErrorCode {
3282 /// \brief A statement is not an expression statement.
3283 NotAnExpression,
3284 /// \brief Expression is not builtin binary or unary operation.
3285 NotABinaryOrUnaryExpression,
3286 /// \brief Unary operation is not post-/pre- increment/decrement operation.
3287 NotAnUnaryIncDecExpression,
3288 /// \brief An expression is not of scalar type.
3289 NotAScalarType,
3290 /// \brief A binary operation is not an assignment operation.
3291 NotAnAssignmentOp,
3292 /// \brief RHS part of the binary operation is not a binary expression.
3293 NotABinaryExpression,
3294 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
3295 /// expression.
3296 NotABinaryOperator,
3297 /// \brief RHS binary operation does not have reference to the updated LHS
3298 /// part.
3299 NotAnUpdateExpression,
3300 /// \brief No errors is found.
3301 NoError
3302 };
3303 /// \brief Reference to Sema.
3304 Sema &SemaRef;
3305 /// \brief A location for note diagnostics (when error is found).
3306 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003307 /// \brief 'x' lvalue part of the source atomic expression.
3308 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003309 /// \brief 'expr' rvalue part of the source atomic expression.
3310 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003311 /// \brief Helper expression of the form
3312 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3313 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3314 Expr *UpdateExpr;
3315 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
3316 /// important for non-associative operations.
3317 bool IsXLHSInRHSPart;
3318 BinaryOperatorKind Op;
3319 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003320 /// \brief true if the source expression is a postfix unary operation, false
3321 /// if it is a prefix unary operation.
3322 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003323
3324public:
3325 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00003326 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00003327 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00003328 /// \brief Check specified statement that it is suitable for 'atomic update'
3329 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00003330 /// expression. If DiagId and NoteId == 0, then only check is performed
3331 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00003332 /// \param DiagId Diagnostic which should be emitted if error is found.
3333 /// \param NoteId Diagnostic note for the main error message.
3334 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00003335 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003336 /// \brief Return the 'x' lvalue part of the source atomic expression.
3337 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00003338 /// \brief Return the 'expr' rvalue part of the source atomic expression.
3339 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00003340 /// \brief Return the update expression used in calculation of the updated
3341 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3342 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3343 Expr *getUpdateExpr() const { return UpdateExpr; }
3344 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
3345 /// false otherwise.
3346 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
3347
Alexey Bataevb78ca832015-04-01 03:33:17 +00003348 /// \brief true if the source expression is a postfix unary operation, false
3349 /// if it is a prefix unary operation.
3350 bool isPostfixUpdate() const { return IsPostfixUpdate; }
3351
Alexey Bataev1d160b12015-03-13 12:27:31 +00003352private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00003353 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
3354 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003355};
3356} // namespace
3357
3358bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
3359 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
3360 ExprAnalysisErrorCode ErrorFound = NoError;
3361 SourceLocation ErrorLoc, NoteLoc;
3362 SourceRange ErrorRange, NoteRange;
3363 // Allowed constructs are:
3364 // x = x binop expr;
3365 // x = expr binop x;
3366 if (AtomicBinOp->getOpcode() == BO_Assign) {
3367 X = AtomicBinOp->getLHS();
3368 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
3369 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
3370 if (AtomicInnerBinOp->isMultiplicativeOp() ||
3371 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
3372 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003373 Op = AtomicInnerBinOp->getOpcode();
3374 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003375 auto *LHS = AtomicInnerBinOp->getLHS();
3376 auto *RHS = AtomicInnerBinOp->getRHS();
3377 llvm::FoldingSetNodeID XId, LHSId, RHSId;
3378 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
3379 /*Canonical=*/true);
3380 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
3381 /*Canonical=*/true);
3382 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
3383 /*Canonical=*/true);
3384 if (XId == LHSId) {
3385 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003386 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003387 } else if (XId == RHSId) {
3388 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003389 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003390 } else {
3391 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3392 ErrorRange = AtomicInnerBinOp->getSourceRange();
3393 NoteLoc = X->getExprLoc();
3394 NoteRange = X->getSourceRange();
3395 ErrorFound = NotAnUpdateExpression;
3396 }
3397 } else {
3398 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3399 ErrorRange = AtomicInnerBinOp->getSourceRange();
3400 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
3401 NoteRange = SourceRange(NoteLoc, NoteLoc);
3402 ErrorFound = NotABinaryOperator;
3403 }
3404 } else {
3405 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
3406 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
3407 ErrorFound = NotABinaryExpression;
3408 }
3409 } else {
3410 ErrorLoc = AtomicBinOp->getExprLoc();
3411 ErrorRange = AtomicBinOp->getSourceRange();
3412 NoteLoc = AtomicBinOp->getOperatorLoc();
3413 NoteRange = SourceRange(NoteLoc, NoteLoc);
3414 ErrorFound = NotAnAssignmentOp;
3415 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003416 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003417 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3418 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3419 return true;
3420 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003421 E = X = UpdateExpr = nullptr;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003422 return false;
3423}
3424
3425bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
3426 unsigned NoteId) {
3427 ExprAnalysisErrorCode ErrorFound = NoError;
3428 SourceLocation ErrorLoc, NoteLoc;
3429 SourceRange ErrorRange, NoteRange;
3430 // Allowed constructs are:
3431 // x++;
3432 // x--;
3433 // ++x;
3434 // --x;
3435 // x binop= expr;
3436 // x = x binop expr;
3437 // x = expr binop x;
3438 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
3439 AtomicBody = AtomicBody->IgnoreParenImpCasts();
3440 if (AtomicBody->getType()->isScalarType() ||
3441 AtomicBody->isInstantiationDependent()) {
3442 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
3443 AtomicBody->IgnoreParenImpCasts())) {
3444 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003445 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00003446 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003447 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003448 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003449 X = AtomicCompAssignOp->getLHS();
3450 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003451 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
3452 AtomicBody->IgnoreParenImpCasts())) {
3453 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003454 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
3455 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003456 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00003457 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
3458 // Check for Unary Operation
3459 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003460 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003461 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
3462 OpLoc = AtomicUnaryOp->getOperatorLoc();
3463 X = AtomicUnaryOp->getSubExpr();
3464 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
3465 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003466 } else {
3467 ErrorFound = NotAnUnaryIncDecExpression;
3468 ErrorLoc = AtomicUnaryOp->getExprLoc();
3469 ErrorRange = AtomicUnaryOp->getSourceRange();
3470 NoteLoc = AtomicUnaryOp->getOperatorLoc();
3471 NoteRange = SourceRange(NoteLoc, NoteLoc);
3472 }
3473 } else {
3474 ErrorFound = NotABinaryOrUnaryExpression;
3475 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
3476 NoteRange = ErrorRange = AtomicBody->getSourceRange();
3477 }
3478 } else {
3479 ErrorFound = NotAScalarType;
3480 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
3481 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3482 }
3483 } else {
3484 ErrorFound = NotAnExpression;
3485 NoteLoc = ErrorLoc = S->getLocStart();
3486 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3487 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003488 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003489 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3490 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3491 return true;
3492 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003493 E = X = UpdateExpr = nullptr;
3494 if (E && X) {
3495 // Build an update expression of form 'OpaqueValueExpr(x) binop
3496 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
3497 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
3498 auto *OVEX = new (SemaRef.getASTContext())
3499 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
3500 auto *OVEExpr = new (SemaRef.getASTContext())
3501 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
3502 auto Update =
3503 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
3504 IsXLHSInRHSPart ? OVEExpr : OVEX);
3505 if (Update.isInvalid())
3506 return true;
3507 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
3508 Sema::AA_Casting);
3509 if (Update.isInvalid())
3510 return true;
3511 UpdateExpr = Update.get();
3512 }
Alexey Bataev1d160b12015-03-13 12:27:31 +00003513 return false;
3514}
3515
Alexey Bataev0162e452014-07-22 10:10:35 +00003516StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3517 Stmt *AStmt,
3518 SourceLocation StartLoc,
3519 SourceLocation EndLoc) {
3520 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003521 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00003522 // 1.2.2 OpenMP Language Terminology
3523 // Structured block - An executable statement with a single entry at the
3524 // top and a single exit at the bottom.
3525 // The point of exit cannot be a branch out of the structured block.
3526 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00003527 OpenMPClauseKind AtomicKind = OMPC_unknown;
3528 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003529 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00003530 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00003531 C->getClauseKind() == OMPC_update ||
3532 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00003533 if (AtomicKind != OMPC_unknown) {
3534 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3535 << SourceRange(C->getLocStart(), C->getLocEnd());
3536 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3537 << getOpenMPClauseName(AtomicKind);
3538 } else {
3539 AtomicKind = C->getClauseKind();
3540 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003541 }
3542 }
3543 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003544
Alexey Bataev459dec02014-07-24 06:46:57 +00003545 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00003546 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
3547 Body = EWC->getSubExpr();
3548
Alexey Bataev62cec442014-11-18 10:14:22 +00003549 Expr *X = nullptr;
3550 Expr *V = nullptr;
3551 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003552 Expr *UE = nullptr;
3553 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003554 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00003555 // OpenMP [2.12.6, atomic Construct]
3556 // In the next expressions:
3557 // * x and v (as applicable) are both l-value expressions with scalar type.
3558 // * During the execution of an atomic region, multiple syntactic
3559 // occurrences of x must designate the same storage location.
3560 // * Neither of v and expr (as applicable) may access the storage location
3561 // designated by x.
3562 // * Neither of x and expr (as applicable) may access the storage location
3563 // designated by v.
3564 // * expr is an expression with scalar type.
3565 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3566 // * binop, binop=, ++, and -- are not overloaded operators.
3567 // * The expression x binop expr must be numerically equivalent to x binop
3568 // (expr). This requirement is satisfied if the operators in expr have
3569 // precedence greater than binop, or by using parentheses around expr or
3570 // subexpressions of expr.
3571 // * The expression expr binop x must be numerically equivalent to (expr)
3572 // binop x. This requirement is satisfied if the operators in expr have
3573 // precedence equal to or greater than binop, or by using parentheses around
3574 // expr or subexpressions of expr.
3575 // * For forms that allow multiple occurrences of x, the number of times
3576 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00003577 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003578 enum {
3579 NotAnExpression,
3580 NotAnAssignmentOp,
3581 NotAScalarType,
3582 NotAnLValue,
3583 NoError
3584 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00003585 SourceLocation ErrorLoc, NoteLoc;
3586 SourceRange ErrorRange, NoteRange;
3587 // If clause is read:
3588 // v = x;
3589 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3590 auto AtomicBinOp =
3591 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3592 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3593 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3594 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3595 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3596 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3597 if (!X->isLValue() || !V->isLValue()) {
3598 auto NotLValueExpr = X->isLValue() ? V : X;
3599 ErrorFound = NotAnLValue;
3600 ErrorLoc = AtomicBinOp->getExprLoc();
3601 ErrorRange = AtomicBinOp->getSourceRange();
3602 NoteLoc = NotLValueExpr->getExprLoc();
3603 NoteRange = NotLValueExpr->getSourceRange();
3604 }
3605 } else if (!X->isInstantiationDependent() ||
3606 !V->isInstantiationDependent()) {
3607 auto NotScalarExpr =
3608 (X->isInstantiationDependent() || X->getType()->isScalarType())
3609 ? V
3610 : X;
3611 ErrorFound = NotAScalarType;
3612 ErrorLoc = AtomicBinOp->getExprLoc();
3613 ErrorRange = AtomicBinOp->getSourceRange();
3614 NoteLoc = NotScalarExpr->getExprLoc();
3615 NoteRange = NotScalarExpr->getSourceRange();
3616 }
3617 } else {
3618 ErrorFound = NotAnAssignmentOp;
3619 ErrorLoc = AtomicBody->getExprLoc();
3620 ErrorRange = AtomicBody->getSourceRange();
3621 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3622 : AtomicBody->getExprLoc();
3623 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3624 : AtomicBody->getSourceRange();
3625 }
3626 } else {
3627 ErrorFound = NotAnExpression;
3628 NoteLoc = ErrorLoc = Body->getLocStart();
3629 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003630 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003631 if (ErrorFound != NoError) {
3632 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3633 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003634 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3635 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00003636 return StmtError();
3637 } else if (CurContext->isDependentContext())
3638 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00003639 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003640 enum {
3641 NotAnExpression,
3642 NotAnAssignmentOp,
3643 NotAScalarType,
3644 NotAnLValue,
3645 NoError
3646 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003647 SourceLocation ErrorLoc, NoteLoc;
3648 SourceRange ErrorRange, NoteRange;
3649 // If clause is write:
3650 // x = expr;
3651 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3652 auto AtomicBinOp =
3653 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3654 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00003655 X = AtomicBinOp->getLHS();
3656 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00003657 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3658 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
3659 if (!X->isLValue()) {
3660 ErrorFound = NotAnLValue;
3661 ErrorLoc = AtomicBinOp->getExprLoc();
3662 ErrorRange = AtomicBinOp->getSourceRange();
3663 NoteLoc = X->getExprLoc();
3664 NoteRange = X->getSourceRange();
3665 }
3666 } else if (!X->isInstantiationDependent() ||
3667 !E->isInstantiationDependent()) {
3668 auto NotScalarExpr =
3669 (X->isInstantiationDependent() || X->getType()->isScalarType())
3670 ? E
3671 : X;
3672 ErrorFound = NotAScalarType;
3673 ErrorLoc = AtomicBinOp->getExprLoc();
3674 ErrorRange = AtomicBinOp->getSourceRange();
3675 NoteLoc = NotScalarExpr->getExprLoc();
3676 NoteRange = NotScalarExpr->getSourceRange();
3677 }
3678 } else {
3679 ErrorFound = NotAnAssignmentOp;
3680 ErrorLoc = AtomicBody->getExprLoc();
3681 ErrorRange = AtomicBody->getSourceRange();
3682 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3683 : AtomicBody->getExprLoc();
3684 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3685 : AtomicBody->getSourceRange();
3686 }
3687 } else {
3688 ErrorFound = NotAnExpression;
3689 NoteLoc = ErrorLoc = Body->getLocStart();
3690 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003691 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00003692 if (ErrorFound != NoError) {
3693 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
3694 << ErrorRange;
3695 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3696 << NoteRange;
3697 return StmtError();
3698 } else if (CurContext->isDependentContext())
3699 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00003700 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003701 // If clause is update:
3702 // x++;
3703 // x--;
3704 // ++x;
3705 // --x;
3706 // x binop= expr;
3707 // x = x binop expr;
3708 // x = expr binop x;
3709 OpenMPAtomicUpdateChecker Checker(*this);
3710 if (Checker.checkStatement(
3711 Body, (AtomicKind == OMPC_update)
3712 ? diag::err_omp_atomic_update_not_expression_statement
3713 : diag::err_omp_atomic_not_expression_statement,
3714 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00003715 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003716 if (!CurContext->isDependentContext()) {
3717 E = Checker.getExpr();
3718 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003719 UE = Checker.getUpdateExpr();
3720 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00003721 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003722 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003723 enum {
3724 NotAnAssignmentOp,
3725 NotACompoundStatement,
3726 NotTwoSubstatements,
3727 NotASpecificExpression,
3728 NoError
3729 } ErrorFound = NoError;
3730 SourceLocation ErrorLoc, NoteLoc;
3731 SourceRange ErrorRange, NoteRange;
3732 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
3733 // If clause is a capture:
3734 // v = x++;
3735 // v = x--;
3736 // v = ++x;
3737 // v = --x;
3738 // v = x binop= expr;
3739 // v = x = x binop expr;
3740 // v = x = expr binop x;
3741 auto *AtomicBinOp =
3742 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3743 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3744 V = AtomicBinOp->getLHS();
3745 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3746 OpenMPAtomicUpdateChecker Checker(*this);
3747 if (Checker.checkStatement(
3748 Body, diag::err_omp_atomic_capture_not_expression_statement,
3749 diag::note_omp_atomic_update))
3750 return StmtError();
3751 E = Checker.getExpr();
3752 X = Checker.getX();
3753 UE = Checker.getUpdateExpr();
3754 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3755 IsPostfixUpdate = Checker.isPostfixUpdate();
3756 } else {
3757 ErrorLoc = AtomicBody->getExprLoc();
3758 ErrorRange = AtomicBody->getSourceRange();
3759 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3760 : AtomicBody->getExprLoc();
3761 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3762 : AtomicBody->getSourceRange();
3763 ErrorFound = NotAnAssignmentOp;
3764 }
3765 if (ErrorFound != NoError) {
3766 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
3767 << ErrorRange;
3768 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3769 return StmtError();
3770 } else if (CurContext->isDependentContext()) {
3771 UE = V = E = X = nullptr;
3772 }
3773 } else {
3774 // If clause is a capture:
3775 // { v = x; x = expr; }
3776 // { v = x; x++; }
3777 // { v = x; x--; }
3778 // { v = x; ++x; }
3779 // { v = x; --x; }
3780 // { v = x; x binop= expr; }
3781 // { v = x; x = x binop expr; }
3782 // { v = x; x = expr binop x; }
3783 // { x++; v = x; }
3784 // { x--; v = x; }
3785 // { ++x; v = x; }
3786 // { --x; v = x; }
3787 // { x binop= expr; v = x; }
3788 // { x = x binop expr; v = x; }
3789 // { x = expr binop x; v = x; }
3790 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
3791 // Check that this is { expr1; expr2; }
3792 if (CS->size() == 2) {
3793 auto *First = CS->body_front();
3794 auto *Second = CS->body_back();
3795 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
3796 First = EWC->getSubExpr()->IgnoreParenImpCasts();
3797 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
3798 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
3799 // Need to find what subexpression is 'v' and what is 'x'.
3800 OpenMPAtomicUpdateChecker Checker(*this);
3801 bool IsUpdateExprFound = !Checker.checkStatement(Second);
3802 BinaryOperator *BinOp = nullptr;
3803 if (IsUpdateExprFound) {
3804 BinOp = dyn_cast<BinaryOperator>(First);
3805 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3806 }
3807 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3808 // { v = x; x++; }
3809 // { v = x; x--; }
3810 // { v = x; ++x; }
3811 // { v = x; --x; }
3812 // { v = x; x binop= expr; }
3813 // { v = x; x = x binop expr; }
3814 // { v = x; x = expr binop x; }
3815 // Check that the first expression has form v = x.
3816 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3817 llvm::FoldingSetNodeID XId, PossibleXId;
3818 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3819 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3820 IsUpdateExprFound = XId == PossibleXId;
3821 if (IsUpdateExprFound) {
3822 V = BinOp->getLHS();
3823 X = Checker.getX();
3824 E = Checker.getExpr();
3825 UE = Checker.getUpdateExpr();
3826 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3827 IsPostfixUpdate = Checker.isPostfixUpdate();
3828 }
3829 }
3830 if (!IsUpdateExprFound) {
3831 IsUpdateExprFound = !Checker.checkStatement(First);
3832 BinOp = nullptr;
3833 if (IsUpdateExprFound) {
3834 BinOp = dyn_cast<BinaryOperator>(Second);
3835 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3836 }
3837 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3838 // { x++; v = x; }
3839 // { x--; v = x; }
3840 // { ++x; v = x; }
3841 // { --x; v = x; }
3842 // { x binop= expr; v = x; }
3843 // { x = x binop expr; v = x; }
3844 // { x = expr binop x; v = x; }
3845 // Check that the second expression has form v = x.
3846 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3847 llvm::FoldingSetNodeID XId, PossibleXId;
3848 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3849 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3850 IsUpdateExprFound = XId == PossibleXId;
3851 if (IsUpdateExprFound) {
3852 V = BinOp->getLHS();
3853 X = Checker.getX();
3854 E = Checker.getExpr();
3855 UE = Checker.getUpdateExpr();
3856 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3857 IsPostfixUpdate = Checker.isPostfixUpdate();
3858 }
3859 }
3860 }
3861 if (!IsUpdateExprFound) {
3862 // { v = x; x = expr; }
3863 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
3864 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
3865 ErrorFound = NotAnAssignmentOp;
3866 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
3867 : First->getLocStart();
3868 NoteRange = ErrorRange = FirstBinOp
3869 ? FirstBinOp->getSourceRange()
3870 : SourceRange(ErrorLoc, ErrorLoc);
3871 } else {
3872 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
3873 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
3874 ErrorFound = NotAnAssignmentOp;
3875 NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
3876 : Second->getLocStart();
3877 NoteRange = ErrorRange = SecondBinOp
3878 ? SecondBinOp->getSourceRange()
3879 : SourceRange(ErrorLoc, ErrorLoc);
3880 } else {
3881 auto *PossibleXRHSInFirst =
3882 FirstBinOp->getRHS()->IgnoreParenImpCasts();
3883 auto *PossibleXLHSInSecond =
3884 SecondBinOp->getLHS()->IgnoreParenImpCasts();
3885 llvm::FoldingSetNodeID X1Id, X2Id;
3886 PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
3887 PossibleXLHSInSecond->Profile(X2Id, Context,
3888 /*Canonical=*/true);
3889 IsUpdateExprFound = X1Id == X2Id;
3890 if (IsUpdateExprFound) {
3891 V = FirstBinOp->getLHS();
3892 X = SecondBinOp->getLHS();
3893 E = SecondBinOp->getRHS();
3894 UE = nullptr;
3895 IsXLHSInRHSPart = false;
3896 IsPostfixUpdate = true;
3897 } else {
3898 ErrorFound = NotASpecificExpression;
3899 ErrorLoc = FirstBinOp->getExprLoc();
3900 ErrorRange = FirstBinOp->getSourceRange();
3901 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
3902 NoteRange = SecondBinOp->getRHS()->getSourceRange();
3903 }
3904 }
3905 }
3906 }
3907 } else {
3908 NoteLoc = ErrorLoc = Body->getLocStart();
3909 NoteRange = ErrorRange =
3910 SourceRange(Body->getLocStart(), Body->getLocStart());
3911 ErrorFound = NotTwoSubstatements;
3912 }
3913 } else {
3914 NoteLoc = ErrorLoc = Body->getLocStart();
3915 NoteRange = ErrorRange =
3916 SourceRange(Body->getLocStart(), Body->getLocStart());
3917 ErrorFound = NotACompoundStatement;
3918 }
3919 if (ErrorFound != NoError) {
3920 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
3921 << ErrorRange;
3922 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3923 return StmtError();
3924 } else if (CurContext->isDependentContext()) {
3925 UE = V = E = X = nullptr;
3926 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003927 }
Alexey Bataevdea47612014-07-23 07:46:59 +00003928 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003929
3930 getCurFunction()->setHasBranchProtectedScope();
3931
Alexey Bataev62cec442014-11-18 10:14:22 +00003932 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00003933 X, V, E, UE, IsXLHSInRHSPart,
3934 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00003935}
3936
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003937StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
3938 Stmt *AStmt,
3939 SourceLocation StartLoc,
3940 SourceLocation EndLoc) {
3941 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3942
Alexey Bataev13314bf2014-10-09 04:18:56 +00003943 // OpenMP [2.16, Nesting of Regions]
3944 // If specified, a teams construct must be contained within a target
3945 // construct. That target construct must contain no statements or directives
3946 // outside of the teams construct.
3947 if (DSAStack->hasInnerTeamsRegion()) {
3948 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
3949 bool OMPTeamsFound = true;
3950 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
3951 auto I = CS->body_begin();
3952 while (I != CS->body_end()) {
3953 auto OED = dyn_cast<OMPExecutableDirective>(*I);
3954 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
3955 OMPTeamsFound = false;
3956 break;
3957 }
3958 ++I;
3959 }
3960 assert(I != CS->body_end() && "Not found statement");
3961 S = *I;
3962 }
3963 if (!OMPTeamsFound) {
3964 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
3965 Diag(DSAStack->getInnerTeamsRegionLoc(),
3966 diag::note_omp_nested_teams_construct_here);
3967 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
3968 << isa<OMPExecutableDirective>(S);
3969 return StmtError();
3970 }
3971 }
3972
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003973 getCurFunction()->setHasBranchProtectedScope();
3974
3975 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3976}
3977
Alexey Bataev13314bf2014-10-09 04:18:56 +00003978StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
3979 Stmt *AStmt, SourceLocation StartLoc,
3980 SourceLocation EndLoc) {
3981 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3982 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3983 // 1.2.2 OpenMP Language Terminology
3984 // Structured block - An executable statement with a single entry at the
3985 // top and a single exit at the bottom.
3986 // The point of exit cannot be a branch out of the structured block.
3987 // longjmp() and throw() must not violate the entry/exit criteria.
3988 CS->getCapturedDecl()->setNothrow();
3989
3990 getCurFunction()->setHasBranchProtectedScope();
3991
3992 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3993}
3994
Alexey Bataeved09d242014-05-28 05:53:51 +00003995OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003996 SourceLocation StartLoc,
3997 SourceLocation LParenLoc,
3998 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00003999 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004000 switch (Kind) {
4001 case OMPC_if:
4002 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
4003 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00004004 case OMPC_final:
4005 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
4006 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00004007 case OMPC_num_threads:
4008 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
4009 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004010 case OMPC_safelen:
4011 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
4012 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00004013 case OMPC_collapse:
4014 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
4015 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004016 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004017 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004018 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004019 case OMPC_private:
4020 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004021 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004022 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004023 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004024 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004025 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004026 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004027 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004028 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004029 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004030 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004031 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004032 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004033 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004034 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004035 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004036 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004037 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004038 case OMPC_seq_cst:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004039 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004040 llvm_unreachable("Clause is not allowed.");
4041 }
4042 return Res;
4043}
4044
Alexey Bataeved09d242014-05-28 05:53:51 +00004045OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004046 SourceLocation LParenLoc,
4047 SourceLocation EndLoc) {
4048 Expr *ValExpr = Condition;
4049 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4050 !Condition->isInstantiationDependent() &&
4051 !Condition->containsUnexpandedParameterPack()) {
4052 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00004053 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004054 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004055 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004056
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004057 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004058 }
4059
4060 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4061}
4062
Alexey Bataev3778b602014-07-17 07:32:53 +00004063OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
4064 SourceLocation StartLoc,
4065 SourceLocation LParenLoc,
4066 SourceLocation EndLoc) {
4067 Expr *ValExpr = Condition;
4068 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4069 !Condition->isInstantiationDependent() &&
4070 !Condition->containsUnexpandedParameterPack()) {
4071 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4072 Condition->getExprLoc(), Condition);
4073 if (Val.isInvalid())
4074 return nullptr;
4075
4076 ValExpr = Val.get();
4077 }
4078
4079 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4080}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004081ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
4082 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004083 if (!Op)
4084 return ExprError();
4085
4086 class IntConvertDiagnoser : public ICEConvertDiagnoser {
4087 public:
4088 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00004089 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00004090 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
4091 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004092 return S.Diag(Loc, diag::err_omp_not_integral) << T;
4093 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004094 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4095 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004096 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
4097 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004098 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4099 QualType T,
4100 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004101 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
4102 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004103 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4104 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004105 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004106 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004107 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004108 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4109 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004110 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
4111 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004112 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4113 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004114 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004115 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004116 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004117 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
4118 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004119 llvm_unreachable("conversion functions are permitted");
4120 }
4121 } ConvertDiagnoser;
4122 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
4123}
4124
4125OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
4126 SourceLocation StartLoc,
4127 SourceLocation LParenLoc,
4128 SourceLocation EndLoc) {
4129 Expr *ValExpr = NumThreads;
4130 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
Alexey Bataev568a8332014-03-06 06:15:19 +00004131 !NumThreads->containsUnexpandedParameterPack()) {
4132 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
4133 ExprResult Val =
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004134 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
Alexey Bataev568a8332014-03-06 06:15:19 +00004135 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004136 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004137
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004138 ValExpr = Val.get();
Alexey Bataev568a8332014-03-06 06:15:19 +00004139
4140 // OpenMP [2.5, Restrictions]
4141 // The num_threads expression must evaluate to a positive integer value.
4142 llvm::APSInt Result;
Alexey Bataeved09d242014-05-28 05:53:51 +00004143 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
4144 !Result.isStrictlyPositive()) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004145 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
4146 << "num_threads" << NumThreads->getSourceRange();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004147 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004148 }
4149 }
4150
Alexey Bataeved09d242014-05-28 05:53:51 +00004151 return new (Context)
4152 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00004153}
4154
Alexey Bataev62c87d22014-03-21 04:51:18 +00004155ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
4156 OpenMPClauseKind CKind) {
4157 if (!E)
4158 return ExprError();
4159 if (E->isValueDependent() || E->isTypeDependent() ||
4160 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004161 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004162 llvm::APSInt Result;
4163 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
4164 if (ICE.isInvalid())
4165 return ExprError();
4166 if (!Result.isStrictlyPositive()) {
4167 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
4168 << getOpenMPClauseName(CKind) << E->getSourceRange();
4169 return ExprError();
4170 }
Alexander Musman09184fe2014-09-30 05:29:28 +00004171 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
4172 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
4173 << E->getSourceRange();
4174 return ExprError();
4175 }
Alexey Bataev62c87d22014-03-21 04:51:18 +00004176 return ICE;
4177}
4178
4179OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
4180 SourceLocation LParenLoc,
4181 SourceLocation EndLoc) {
4182 // OpenMP [2.8.1, simd construct, Description]
4183 // The parameter of the safelen clause must be a constant
4184 // positive integer expression.
4185 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
4186 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004187 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004188 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004189 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00004190}
4191
Alexander Musman64d33f12014-06-04 07:53:32 +00004192OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
4193 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00004194 SourceLocation LParenLoc,
4195 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00004196 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004197 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00004198 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004199 // The parameter of the collapse clause must be a constant
4200 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00004201 ExprResult NumForLoopsResult =
4202 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
4203 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00004204 return nullptr;
4205 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00004206 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00004207}
4208
Alexey Bataeved09d242014-05-28 05:53:51 +00004209OMPClause *Sema::ActOnOpenMPSimpleClause(
4210 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
4211 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004212 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004213 switch (Kind) {
4214 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004215 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00004216 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
4217 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004218 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004219 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00004220 Res = ActOnOpenMPProcBindClause(
4221 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
4222 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004223 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004224 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004225 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004226 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004227 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004228 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004229 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004230 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004231 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004232 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004233 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004234 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004235 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004236 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004237 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004238 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004239 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004240 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004241 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004242 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004243 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004244 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004245 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004246 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004247 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004248 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004249 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004250 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004251 llvm_unreachable("Clause is not allowed.");
4252 }
4253 return Res;
4254}
4255
4256OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
4257 SourceLocation KindKwLoc,
4258 SourceLocation StartLoc,
4259 SourceLocation LParenLoc,
4260 SourceLocation EndLoc) {
4261 if (Kind == OMPC_DEFAULT_unknown) {
4262 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004263 static_assert(OMPC_DEFAULT_unknown > 0,
4264 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00004265 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004266 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004267 Values += "'";
4268 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
4269 Values += "'";
4270 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004271 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004272 Values += " or ";
4273 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004274 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004275 break;
4276 default:
4277 Values += Sep;
4278 break;
4279 }
4280 }
4281 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004282 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004283 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004284 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004285 switch (Kind) {
4286 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004287 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004288 break;
4289 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004290 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004291 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004292 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004293 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00004294 break;
4295 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004296 return new (Context)
4297 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004298}
4299
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004300OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
4301 SourceLocation KindKwLoc,
4302 SourceLocation StartLoc,
4303 SourceLocation LParenLoc,
4304 SourceLocation EndLoc) {
4305 if (Kind == OMPC_PROC_BIND_unknown) {
4306 std::string Values;
4307 std::string Sep(", ");
4308 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
4309 Values += "'";
4310 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
4311 Values += "'";
4312 switch (i) {
4313 case OMPC_PROC_BIND_unknown - 2:
4314 Values += " or ";
4315 break;
4316 case OMPC_PROC_BIND_unknown - 1:
4317 break;
4318 default:
4319 Values += Sep;
4320 break;
4321 }
4322 }
4323 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004324 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004325 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004326 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004327 return new (Context)
4328 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004329}
4330
Alexey Bataev56dafe82014-06-20 07:16:17 +00004331OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
4332 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
4333 SourceLocation StartLoc, SourceLocation LParenLoc,
4334 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
4335 SourceLocation EndLoc) {
4336 OMPClause *Res = nullptr;
4337 switch (Kind) {
4338 case OMPC_schedule:
4339 Res = ActOnOpenMPScheduleClause(
4340 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
4341 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
4342 break;
4343 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004344 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004345 case OMPC_num_threads:
4346 case OMPC_safelen:
4347 case OMPC_collapse:
4348 case OMPC_default:
4349 case OMPC_proc_bind:
4350 case OMPC_private:
4351 case OMPC_firstprivate:
4352 case OMPC_lastprivate:
4353 case OMPC_shared:
4354 case OMPC_reduction:
4355 case OMPC_linear:
4356 case OMPC_aligned:
4357 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004358 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004359 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004360 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004361 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004362 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004363 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004364 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004365 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004366 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004367 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004368 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004369 case OMPC_seq_cst:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004370 case OMPC_unknown:
4371 llvm_unreachable("Clause is not allowed.");
4372 }
4373 return Res;
4374}
4375
4376OMPClause *Sema::ActOnOpenMPScheduleClause(
4377 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
4378 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
4379 SourceLocation EndLoc) {
4380 if (Kind == OMPC_SCHEDULE_unknown) {
4381 std::string Values;
4382 std::string Sep(", ");
4383 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
4384 Values += "'";
4385 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
4386 Values += "'";
4387 switch (i) {
4388 case OMPC_SCHEDULE_unknown - 2:
4389 Values += " or ";
4390 break;
4391 case OMPC_SCHEDULE_unknown - 1:
4392 break;
4393 default:
4394 Values += Sep;
4395 break;
4396 }
4397 }
4398 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
4399 << Values << getOpenMPClauseName(OMPC_schedule);
4400 return nullptr;
4401 }
4402 Expr *ValExpr = ChunkSize;
4403 if (ChunkSize) {
4404 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
4405 !ChunkSize->isInstantiationDependent() &&
4406 !ChunkSize->containsUnexpandedParameterPack()) {
4407 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
4408 ExprResult Val =
4409 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
4410 if (Val.isInvalid())
4411 return nullptr;
4412
4413 ValExpr = Val.get();
4414
4415 // OpenMP [2.7.1, Restrictions]
4416 // chunk_size must be a loop invariant integer expression with a positive
4417 // value.
4418 llvm::APSInt Result;
4419 if (ValExpr->isIntegerConstantExpr(Result, Context) &&
4420 Result.isSigned() && !Result.isStrictlyPositive()) {
4421 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
4422 << "schedule" << ChunkSize->getSourceRange();
4423 return nullptr;
4424 }
4425 }
4426 }
4427
4428 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
4429 EndLoc, Kind, ValExpr);
4430}
4431
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004432OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
4433 SourceLocation StartLoc,
4434 SourceLocation EndLoc) {
4435 OMPClause *Res = nullptr;
4436 switch (Kind) {
4437 case OMPC_ordered:
4438 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
4439 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00004440 case OMPC_nowait:
4441 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
4442 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004443 case OMPC_untied:
4444 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
4445 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004446 case OMPC_mergeable:
4447 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
4448 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004449 case OMPC_read:
4450 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
4451 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00004452 case OMPC_write:
4453 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
4454 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004455 case OMPC_update:
4456 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
4457 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00004458 case OMPC_capture:
4459 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
4460 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004461 case OMPC_seq_cst:
4462 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
4463 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004464 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004465 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004466 case OMPC_num_threads:
4467 case OMPC_safelen:
4468 case OMPC_collapse:
4469 case OMPC_schedule:
4470 case OMPC_private:
4471 case OMPC_firstprivate:
4472 case OMPC_lastprivate:
4473 case OMPC_shared:
4474 case OMPC_reduction:
4475 case OMPC_linear:
4476 case OMPC_aligned:
4477 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004478 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004479 case OMPC_default:
4480 case OMPC_proc_bind:
4481 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004482 case OMPC_flush:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004483 case OMPC_unknown:
4484 llvm_unreachable("Clause is not allowed.");
4485 }
4486 return Res;
4487}
4488
4489OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
4490 SourceLocation EndLoc) {
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004491 DSAStack->setOrderedRegion();
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004492 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
4493}
4494
Alexey Bataev236070f2014-06-20 11:19:47 +00004495OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
4496 SourceLocation EndLoc) {
4497 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
4498}
4499
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004500OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
4501 SourceLocation EndLoc) {
4502 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
4503}
4504
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004505OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
4506 SourceLocation EndLoc) {
4507 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
4508}
4509
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004510OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
4511 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004512 return new (Context) OMPReadClause(StartLoc, EndLoc);
4513}
4514
Alexey Bataevdea47612014-07-23 07:46:59 +00004515OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
4516 SourceLocation EndLoc) {
4517 return new (Context) OMPWriteClause(StartLoc, EndLoc);
4518}
4519
Alexey Bataev67a4f222014-07-23 10:25:33 +00004520OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
4521 SourceLocation EndLoc) {
4522 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
4523}
4524
Alexey Bataev459dec02014-07-24 06:46:57 +00004525OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
4526 SourceLocation EndLoc) {
4527 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
4528}
4529
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004530OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
4531 SourceLocation EndLoc) {
4532 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
4533}
4534
Alexey Bataevc5e02582014-06-16 07:08:35 +00004535OMPClause *Sema::ActOnOpenMPVarListClause(
4536 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
4537 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
4538 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
4539 const DeclarationNameInfo &ReductionId) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004540 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004541 switch (Kind) {
4542 case OMPC_private:
4543 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4544 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004545 case OMPC_firstprivate:
4546 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4547 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00004548 case OMPC_lastprivate:
4549 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4550 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00004551 case OMPC_shared:
4552 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
4553 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00004554 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00004555 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
4556 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00004557 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00004558 case OMPC_linear:
4559 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
4560 ColonLoc, EndLoc);
4561 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004562 case OMPC_aligned:
4563 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
4564 ColonLoc, EndLoc);
4565 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004566 case OMPC_copyin:
4567 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
4568 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00004569 case OMPC_copyprivate:
4570 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4571 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004572 case OMPC_flush:
4573 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4574 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004575 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004576 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004577 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004578 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004579 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004580 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004581 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004582 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004583 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004584 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004585 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004586 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004587 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004588 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004589 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004590 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004591 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004592 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004593 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004594 llvm_unreachable("Clause is not allowed.");
4595 }
4596 return Res;
4597}
4598
4599OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
4600 SourceLocation StartLoc,
4601 SourceLocation LParenLoc,
4602 SourceLocation EndLoc) {
4603 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00004604 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00004605 for (auto &RefExpr : VarList) {
4606 assert(RefExpr && "NULL expr in OpenMP private clause.");
4607 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004608 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004609 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004610 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004611 continue;
4612 }
4613
Alexey Bataeved09d242014-05-28 05:53:51 +00004614 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004615 // OpenMP [2.1, C/C++]
4616 // A list item is a variable name.
4617 // OpenMP [2.9.3.3, Restrictions, p.1]
4618 // A variable that is part of another variable (as an array or
4619 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004620 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004621 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004622 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004623 continue;
4624 }
4625 Decl *D = DE->getDecl();
4626 VarDecl *VD = cast<VarDecl>(D);
4627
4628 QualType Type = VD->getType();
4629 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4630 // It will be analyzed later.
4631 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004632 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004633 continue;
4634 }
4635
4636 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4637 // A variable that appears in a private clause must not have an incomplete
4638 // type or a reference type.
4639 if (RequireCompleteType(ELoc, Type,
4640 diag::err_omp_private_incomplete_type)) {
4641 continue;
4642 }
4643 if (Type->isReferenceType()) {
4644 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00004645 << getOpenMPClauseName(OMPC_private) << Type;
4646 bool IsDecl =
4647 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4648 Diag(VD->getLocation(),
4649 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4650 << VD;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004651 continue;
4652 }
4653
4654 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
4655 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004656 // clause requires an accessible, unambiguous default constructor for the
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004657 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00004658 while (Type->isArrayType()) {
4659 Type = cast<ArrayType>(Type.getTypePtr())->getElementType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004660 }
4661
Alexey Bataev758e55e2013-09-06 18:03:48 +00004662 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4663 // in a Construct]
4664 // Variables with the predetermined data-sharing attributes may not be
4665 // listed in data-sharing attributes clauses, except for the cases
4666 // listed below. For these exceptions only, listing a predetermined
4667 // variable in a data-sharing attribute clause is allowed and overrides
4668 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004669 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004670 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004671 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4672 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004673 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004674 continue;
4675 }
4676
Alexey Bataev03b340a2014-10-21 03:16:40 +00004677 // Generate helper private variable and initialize it with the default
4678 // value. The address of the original variable is replaced by the address of
4679 // the new private variable in CodeGen. This new variable is not added to
4680 // IdResolver, so the code in the OpenMP region uses original variable for
4681 // proper diagnostics.
4682 auto VDPrivate =
4683 VarDecl::Create(Context, CurContext, DE->getLocStart(),
4684 DE->getExprLoc(), VD->getIdentifier(), VD->getType(),
4685 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4686 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto*/ false);
4687 if (VDPrivate->isInvalidDecl())
4688 continue;
4689 CurContext->addDecl(VDPrivate);
Alexey Bataev07649fb2014-12-16 08:01:48 +00004690 auto VDPrivateRefExpr =
4691 DeclRefExpr::Create(Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4692 /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004693 /*RefersToEnclosingVariableOrCapture*/ false,
Alexey Bataev07649fb2014-12-16 08:01:48 +00004694 /*NameLoc*/ SourceLocation(), DE->getType(),
4695 /*VK*/ VK_LValue);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004696
Alexey Bataev758e55e2013-09-06 18:03:48 +00004697 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004698 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004699 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004700 }
4701
Alexey Bataeved09d242014-05-28 05:53:51 +00004702 if (Vars.empty())
4703 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004704
Alexey Bataev03b340a2014-10-21 03:16:40 +00004705 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
4706 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004707}
4708
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004709namespace {
4710class DiagsUninitializedSeveretyRAII {
4711private:
4712 DiagnosticsEngine &Diags;
4713 SourceLocation SavedLoc;
4714 bool IsIgnored;
4715
4716public:
4717 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
4718 bool IsIgnored)
4719 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
4720 if (!IsIgnored) {
4721 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
4722 /*Map*/ diag::Severity::Ignored, Loc);
4723 }
4724 }
4725 ~DiagsUninitializedSeveretyRAII() {
4726 if (!IsIgnored)
4727 Diags.popMappings(SavedLoc);
4728 }
4729};
4730}
4731
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004732OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
4733 SourceLocation StartLoc,
4734 SourceLocation LParenLoc,
4735 SourceLocation EndLoc) {
4736 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004737 SmallVector<Expr *, 8> PrivateCopies;
4738 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004739 bool IsImplicitClause =
4740 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
4741 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
4742
Alexey Bataeved09d242014-05-28 05:53:51 +00004743 for (auto &RefExpr : VarList) {
4744 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
4745 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004746 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004747 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004748 PrivateCopies.push_back(nullptr);
4749 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004750 continue;
4751 }
4752
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004753 SourceLocation ELoc =
4754 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004755 // OpenMP [2.1, C/C++]
4756 // A list item is a variable name.
4757 // OpenMP [2.9.3.3, Restrictions, p.1]
4758 // A variable that is part of another variable (as an array or
4759 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004760 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004761 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004762 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004763 continue;
4764 }
4765 Decl *D = DE->getDecl();
4766 VarDecl *VD = cast<VarDecl>(D);
4767
4768 QualType Type = VD->getType();
4769 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4770 // It will be analyzed later.
4771 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004772 PrivateCopies.push_back(nullptr);
4773 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004774 continue;
4775 }
4776
4777 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4778 // A variable that appears in a private clause must not have an incomplete
4779 // type or a reference type.
4780 if (RequireCompleteType(ELoc, Type,
4781 diag::err_omp_firstprivate_incomplete_type)) {
4782 continue;
4783 }
4784 if (Type->isReferenceType()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004785 if (IsImplicitClause) {
4786 Diag(ImplicitClauseLoc,
4787 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
4788 << Type;
4789 Diag(RefExpr->getExprLoc(), diag::note_used_here);
4790 } else {
4791 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4792 << getOpenMPClauseName(OMPC_firstprivate) << Type;
4793 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004794 bool IsDecl =
4795 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4796 Diag(VD->getLocation(),
4797 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4798 << VD;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004799 continue;
4800 }
4801
4802 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
4803 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004804 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004805 // class type.
Alexey Bataev69c62a92015-04-15 04:52:20 +00004806 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004807
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004808 // If an implicit firstprivate variable found it was checked already.
4809 if (!IsImplicitClause) {
4810 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004811 Type = Type.getNonReferenceType().getCanonicalType();
4812 bool IsConstant = Type.isConstant(Context);
4813 Type = Context.getBaseElementType(Type);
4814 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
4815 // A list item that specifies a given variable may not appear in more
4816 // than one clause on the same directive, except that a variable may be
4817 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004818 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00004819 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004820 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004821 << getOpenMPClauseName(DVar.CKind)
4822 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004823 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004824 continue;
4825 }
4826
4827 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4828 // in a Construct]
4829 // Variables with the predetermined data-sharing attributes may not be
4830 // listed in data-sharing attributes clauses, except for the cases
4831 // listed below. For these exceptions only, listing a predetermined
4832 // variable in a data-sharing attribute clause is allowed and overrides
4833 // the variable's predetermined data-sharing attributes.
4834 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4835 // in a Construct, C/C++, p.2]
4836 // Variables with const-qualified type having no mutable member may be
4837 // listed in a firstprivate clause, even if they are static data members.
4838 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
4839 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
4840 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004841 << getOpenMPClauseName(DVar.CKind)
4842 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004843 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004844 continue;
4845 }
4846
Alexey Bataevf29276e2014-06-18 04:14:57 +00004847 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004848 // OpenMP [2.9.3.4, Restrictions, p.2]
4849 // A list item that is private within a parallel region must not appear
4850 // in a firstprivate clause on a worksharing construct if any of the
4851 // worksharing regions arising from the worksharing construct ever bind
4852 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00004853 if (isOpenMPWorksharingDirective(CurrDir) &&
4854 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004855 DVar = DSAStack->getImplicitDSA(VD, true);
4856 if (DVar.CKind != OMPC_shared &&
4857 (isOpenMPParallelDirective(DVar.DKind) ||
4858 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00004859 Diag(ELoc, diag::err_omp_required_access)
4860 << getOpenMPClauseName(OMPC_firstprivate)
4861 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004862 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004863 continue;
4864 }
4865 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004866 // OpenMP [2.9.3.4, Restrictions, p.3]
4867 // A list item that appears in a reduction clause of a parallel construct
4868 // must not appear in a firstprivate clause on a worksharing or task
4869 // construct if any of the worksharing or task regions arising from the
4870 // worksharing or task construct ever bind to any of the parallel regions
4871 // arising from the parallel construct.
4872 // OpenMP [2.9.3.4, Restrictions, p.4]
4873 // A list item that appears in a reduction clause in worksharing
4874 // construct must not appear in a firstprivate clause in a task construct
4875 // encountered during execution of any of the worksharing regions arising
4876 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004877 if (CurrDir == OMPD_task) {
4878 DVar =
4879 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
4880 [](OpenMPDirectiveKind K) -> bool {
4881 return isOpenMPParallelDirective(K) ||
4882 isOpenMPWorksharingDirective(K);
4883 },
4884 false);
4885 if (DVar.CKind == OMPC_reduction &&
4886 (isOpenMPParallelDirective(DVar.DKind) ||
4887 isOpenMPWorksharingDirective(DVar.DKind))) {
4888 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
4889 << getOpenMPDirectiveName(DVar.DKind);
4890 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4891 continue;
4892 }
4893 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004894 }
4895
Alexey Bataev69c62a92015-04-15 04:52:20 +00004896 auto VDPrivate =
4897 VarDecl::Create(Context, CurContext, DE->getLocStart(), ELoc,
4898 VD->getIdentifier(), VD->getType().getUnqualifiedType(),
4899 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004900 // Generate helper private variable and initialize it with the value of the
4901 // original variable. The address of the original variable is replaced by
4902 // the address of the new private variable in the CodeGen. This new variable
4903 // is not added to IdResolver, so the code in the OpenMP region uses
4904 // original variable for proper diagnostics and variable capturing.
4905 Expr *VDInitRefExpr = nullptr;
4906 // For arrays generate initializer for single element and replace it by the
4907 // original array element in CodeGen.
4908 if (DE->getType()->isArrayType()) {
4909 auto VDInit = VarDecl::Create(Context, CurContext, DE->getLocStart(),
4910 ELoc, VD->getIdentifier(), Type,
4911 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4912 CurContext->addHiddenDecl(VDInit);
4913 VDInitRefExpr = DeclRefExpr::Create(
4914 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4915 /*TemplateKWLoc*/ SourceLocation(), VDInit,
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004916 /*RefersToEnclosingVariableOrCapture*/ true, ELoc, Type,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004917 /*VK*/ VK_LValue);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004918 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataev69c62a92015-04-15 04:52:20 +00004919 auto *VDInitTemp =
4920 BuildVarDecl(*this, DE->getLocStart(), Type.getUnqualifiedType(),
4921 ".firstprivate.temp");
4922 InitializedEntity Entity =
4923 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004924 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
4925
4926 InitializationSequence InitSeq(*this, Entity, Kind, Init);
4927 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
4928 if (Result.isInvalid())
4929 VDPrivate->setInvalidDecl();
4930 else
4931 VDPrivate->setInit(Result.getAs<Expr>());
4932 } else {
Alexey Bataev69c62a92015-04-15 04:52:20 +00004933 auto *VDInit =
4934 BuildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
4935 VDInitRefExpr =
4936 BuildDeclRefExpr(VDInit, Type, VK_LValue, DE->getExprLoc()).get();
4937 AddInitializerToDecl(VDPrivate,
4938 DefaultLvalueConversion(VDInitRefExpr).get(),
4939 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004940 }
4941 if (VDPrivate->isInvalidDecl()) {
4942 if (IsImplicitClause) {
4943 Diag(DE->getExprLoc(),
4944 diag::note_omp_task_predetermined_firstprivate_here);
4945 }
4946 continue;
4947 }
4948 CurContext->addDecl(VDPrivate);
Alexey Bataev69c62a92015-04-15 04:52:20 +00004949 auto VDPrivateRefExpr = DeclRefExpr::Create(
4950 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4951 /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
4952 /*RefersToEnclosingVariableOrCapture*/ false, DE->getLocStart(),
4953 DE->getType().getUnqualifiedType(), /*VK*/ VK_LValue);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004954 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
4955 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004956 PrivateCopies.push_back(VDPrivateRefExpr);
4957 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004958 }
4959
Alexey Bataeved09d242014-05-28 05:53:51 +00004960 if (Vars.empty())
4961 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004962
4963 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004964 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004965}
4966
Alexander Musman1bb328c2014-06-04 13:06:39 +00004967OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
4968 SourceLocation StartLoc,
4969 SourceLocation LParenLoc,
4970 SourceLocation EndLoc) {
4971 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00004972 SmallVector<Expr *, 8> SrcExprs;
4973 SmallVector<Expr *, 8> DstExprs;
4974 SmallVector<Expr *, 8> AssignmentOps;
Alexander Musman1bb328c2014-06-04 13:06:39 +00004975 for (auto &RefExpr : VarList) {
4976 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
4977 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4978 // It will be analyzed later.
4979 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00004980 SrcExprs.push_back(nullptr);
4981 DstExprs.push_back(nullptr);
4982 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00004983 continue;
4984 }
4985
4986 SourceLocation ELoc = RefExpr->getExprLoc();
4987 // OpenMP [2.1, C/C++]
4988 // A list item is a variable name.
4989 // OpenMP [2.14.3.5, Restrictions, p.1]
4990 // A variable that is part of another variable (as an array or structure
4991 // element) cannot appear in a lastprivate clause.
4992 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4993 if (!DE || !isa<VarDecl>(DE->getDecl())) {
4994 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4995 continue;
4996 }
4997 Decl *D = DE->getDecl();
4998 VarDecl *VD = cast<VarDecl>(D);
4999
5000 QualType Type = VD->getType();
5001 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5002 // It will be analyzed later.
5003 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005004 SrcExprs.push_back(nullptr);
5005 DstExprs.push_back(nullptr);
5006 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005007 continue;
5008 }
5009
5010 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
5011 // A variable that appears in a lastprivate clause must not have an
5012 // incomplete type or a reference type.
5013 if (RequireCompleteType(ELoc, Type,
5014 diag::err_omp_lastprivate_incomplete_type)) {
5015 continue;
5016 }
5017 if (Type->isReferenceType()) {
5018 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5019 << getOpenMPClauseName(OMPC_lastprivate) << Type;
5020 bool IsDecl =
5021 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5022 Diag(VD->getLocation(),
5023 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5024 << VD;
5025 continue;
5026 }
5027
5028 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5029 // in a Construct]
5030 // Variables with the predetermined data-sharing attributes may not be
5031 // listed in data-sharing attributes clauses, except for the cases
5032 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005033 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005034 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
5035 DVar.CKind != OMPC_firstprivate &&
5036 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5037 Diag(ELoc, diag::err_omp_wrong_dsa)
5038 << getOpenMPClauseName(DVar.CKind)
5039 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005040 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005041 continue;
5042 }
5043
Alexey Bataevf29276e2014-06-18 04:14:57 +00005044 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5045 // OpenMP [2.14.3.5, Restrictions, p.2]
5046 // A list item that is private within a parallel region, or that appears in
5047 // the reduction clause of a parallel construct, must not appear in a
5048 // lastprivate clause on a worksharing construct if any of the corresponding
5049 // worksharing regions ever binds to any of the corresponding parallel
5050 // regions.
Alexey Bataev549210e2014-06-24 04:39:47 +00005051 if (isOpenMPWorksharingDirective(CurrDir) &&
5052 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005053 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005054 if (DVar.CKind != OMPC_shared) {
5055 Diag(ELoc, diag::err_omp_required_access)
5056 << getOpenMPClauseName(OMPC_lastprivate)
5057 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005058 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005059 continue;
5060 }
5061 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00005062 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00005063 // A variable of class type (or array thereof) that appears in a
5064 // lastprivate clause requires an accessible, unambiguous default
5065 // constructor for the class type, unless the list item is also specified
5066 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00005067 // A variable of class type (or array thereof) that appears in a
5068 // lastprivate clause requires an accessible, unambiguous copy assignment
5069 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00005070 Type = Context.getBaseElementType(Type).getNonReferenceType();
5071 auto *SrcVD = BuildVarDecl(*this, DE->getLocStart(),
5072 Type.getUnqualifiedType(), ".lastprivate.src");
5073 auto *PseudoSrcExpr = BuildDeclRefExpr(SrcVD, Type.getUnqualifiedType(),
5074 VK_LValue, DE->getExprLoc()).get();
5075 auto *DstVD =
5076 BuildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst");
5077 auto *PseudoDstExpr =
5078 BuildDeclRefExpr(DstVD, Type, VK_LValue, DE->getExprLoc()).get();
5079 // For arrays generate assignment operation for single element and replace
5080 // it by the original array element in CodeGen.
5081 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
5082 PseudoDstExpr, PseudoSrcExpr);
5083 if (AssignmentOp.isInvalid())
5084 continue;
5085 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
5086 /*DiscardedValue=*/true);
5087 if (AssignmentOp.isInvalid())
5088 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005089
Alexey Bataevf29276e2014-06-18 04:14:57 +00005090 if (DVar.CKind != OMPC_firstprivate)
5091 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005092 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005093 SrcExprs.push_back(PseudoSrcExpr);
5094 DstExprs.push_back(PseudoDstExpr);
5095 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00005096 }
5097
5098 if (Vars.empty())
5099 return nullptr;
5100
5101 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00005102 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005103}
5104
Alexey Bataev758e55e2013-09-06 18:03:48 +00005105OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
5106 SourceLocation StartLoc,
5107 SourceLocation LParenLoc,
5108 SourceLocation EndLoc) {
5109 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00005110 for (auto &RefExpr : VarList) {
5111 assert(RefExpr && "NULL expr in OpenMP shared clause.");
5112 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00005113 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005114 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005115 continue;
5116 }
5117
Alexey Bataeved09d242014-05-28 05:53:51 +00005118 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005119 // OpenMP [2.1, C/C++]
5120 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00005121 // OpenMP [2.14.3.2, Restrictions, p.1]
5122 // A variable that is part of another variable (as an array or structure
5123 // element) cannot appear in a shared unless it is a static data member
5124 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00005125 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005126 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005127 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005128 continue;
5129 }
5130 Decl *D = DE->getDecl();
5131 VarDecl *VD = cast<VarDecl>(D);
5132
5133 QualType Type = VD->getType();
5134 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5135 // It will be analyzed later.
5136 Vars.push_back(DE);
5137 continue;
5138 }
5139
5140 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5141 // in a Construct]
5142 // Variables with the predetermined data-sharing attributes may not be
5143 // listed in data-sharing attributes clauses, except for the cases
5144 // listed below. For these exceptions only, listing a predetermined
5145 // variable in a data-sharing attribute clause is allowed and overrides
5146 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005147 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00005148 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
5149 DVar.RefExpr) {
5150 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5151 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005152 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005153 continue;
5154 }
5155
5156 DSAStack->addDSA(VD, DE, OMPC_shared);
5157 Vars.push_back(DE);
5158 }
5159
Alexey Bataeved09d242014-05-28 05:53:51 +00005160 if (Vars.empty())
5161 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00005162
5163 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5164}
5165
Alexey Bataevc5e02582014-06-16 07:08:35 +00005166namespace {
5167class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
5168 DSAStackTy *Stack;
5169
5170public:
5171 bool VisitDeclRefExpr(DeclRefExpr *E) {
5172 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005173 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005174 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
5175 return false;
5176 if (DVar.CKind != OMPC_unknown)
5177 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00005178 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005179 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005180 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00005181 return true;
5182 return false;
5183 }
5184 return false;
5185 }
5186 bool VisitStmt(Stmt *S) {
5187 for (auto Child : S->children()) {
5188 if (Child && Visit(Child))
5189 return true;
5190 }
5191 return false;
5192 }
Alexey Bataev23b69422014-06-18 07:08:49 +00005193 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00005194};
Alexey Bataev23b69422014-06-18 07:08:49 +00005195} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00005196
5197OMPClause *Sema::ActOnOpenMPReductionClause(
5198 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
5199 SourceLocation ColonLoc, SourceLocation EndLoc,
5200 CXXScopeSpec &ReductionIdScopeSpec,
5201 const DeclarationNameInfo &ReductionId) {
5202 // TODO: Allow scope specification search when 'declare reduction' is
5203 // supported.
5204 assert(ReductionIdScopeSpec.isEmpty() &&
5205 "No support for scoped reduction identifiers yet.");
5206
5207 auto DN = ReductionId.getName();
5208 auto OOK = DN.getCXXOverloadedOperator();
5209 BinaryOperatorKind BOK = BO_Comma;
5210
5211 // OpenMP [2.14.3.6, reduction clause]
5212 // C
5213 // reduction-identifier is either an identifier or one of the following
5214 // operators: +, -, *, &, |, ^, && and ||
5215 // C++
5216 // reduction-identifier is either an id-expression or one of the following
5217 // operators: +, -, *, &, |, ^, && and ||
5218 // FIXME: Only 'min' and 'max' identifiers are supported for now.
5219 switch (OOK) {
5220 case OO_Plus:
5221 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005222 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005223 break;
5224 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005225 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005226 break;
5227 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005228 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005229 break;
5230 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005231 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005232 break;
5233 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005234 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005235 break;
5236 case OO_AmpAmp:
5237 BOK = BO_LAnd;
5238 break;
5239 case OO_PipePipe:
5240 BOK = BO_LOr;
5241 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005242 case OO_New:
5243 case OO_Delete:
5244 case OO_Array_New:
5245 case OO_Array_Delete:
5246 case OO_Slash:
5247 case OO_Percent:
5248 case OO_Tilde:
5249 case OO_Exclaim:
5250 case OO_Equal:
5251 case OO_Less:
5252 case OO_Greater:
5253 case OO_LessEqual:
5254 case OO_GreaterEqual:
5255 case OO_PlusEqual:
5256 case OO_MinusEqual:
5257 case OO_StarEqual:
5258 case OO_SlashEqual:
5259 case OO_PercentEqual:
5260 case OO_CaretEqual:
5261 case OO_AmpEqual:
5262 case OO_PipeEqual:
5263 case OO_LessLess:
5264 case OO_GreaterGreater:
5265 case OO_LessLessEqual:
5266 case OO_GreaterGreaterEqual:
5267 case OO_EqualEqual:
5268 case OO_ExclaimEqual:
5269 case OO_PlusPlus:
5270 case OO_MinusMinus:
5271 case OO_Comma:
5272 case OO_ArrowStar:
5273 case OO_Arrow:
5274 case OO_Call:
5275 case OO_Subscript:
5276 case OO_Conditional:
5277 case NUM_OVERLOADED_OPERATORS:
5278 llvm_unreachable("Unexpected reduction identifier");
5279 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005280 if (auto II = DN.getAsIdentifierInfo()) {
5281 if (II->isStr("max"))
5282 BOK = BO_GT;
5283 else if (II->isStr("min"))
5284 BOK = BO_LT;
5285 }
5286 break;
5287 }
5288 SourceRange ReductionIdRange;
5289 if (ReductionIdScopeSpec.isValid()) {
5290 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
5291 }
5292 ReductionIdRange.setEnd(ReductionId.getEndLoc());
5293 if (BOK == BO_Comma) {
5294 // Not allowed reduction identifier is found.
5295 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
5296 << ReductionIdRange;
5297 return nullptr;
5298 }
5299
5300 SmallVector<Expr *, 8> Vars;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005301 SmallVector<Expr *, 8> LHSs;
5302 SmallVector<Expr *, 8> RHSs;
5303 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005304 for (auto RefExpr : VarList) {
5305 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
5306 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5307 // It will be analyzed later.
5308 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005309 LHSs.push_back(nullptr);
5310 RHSs.push_back(nullptr);
5311 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005312 continue;
5313 }
5314
5315 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5316 RefExpr->isInstantiationDependent() ||
5317 RefExpr->containsUnexpandedParameterPack()) {
5318 // It will be analyzed later.
5319 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005320 LHSs.push_back(nullptr);
5321 RHSs.push_back(nullptr);
5322 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005323 continue;
5324 }
5325
5326 auto ELoc = RefExpr->getExprLoc();
5327 auto ERange = RefExpr->getSourceRange();
5328 // OpenMP [2.1, C/C++]
5329 // A list item is a variable or array section, subject to the restrictions
5330 // specified in Section 2.4 on page 42 and in each of the sections
5331 // describing clauses and directives for which a list appears.
5332 // OpenMP [2.14.3.3, Restrictions, p.1]
5333 // A variable that is part of another variable (as an array or
5334 // structure element) cannot appear in a private clause.
5335 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
5336 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5337 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
5338 continue;
5339 }
5340 auto D = DE->getDecl();
5341 auto VD = cast<VarDecl>(D);
5342 auto Type = VD->getType();
5343 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5344 // A variable that appears in a private clause must not have an incomplete
5345 // type or a reference type.
5346 if (RequireCompleteType(ELoc, Type,
5347 diag::err_omp_reduction_incomplete_type))
5348 continue;
5349 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5350 // Arrays may not appear in a reduction clause.
5351 if (Type.getNonReferenceType()->isArrayType()) {
5352 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
5353 bool IsDecl =
5354 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5355 Diag(VD->getLocation(),
5356 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5357 << VD;
5358 continue;
5359 }
5360 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5361 // A list item that appears in a reduction clause must not be
5362 // const-qualified.
5363 if (Type.getNonReferenceType().isConstant(Context)) {
5364 Diag(ELoc, diag::err_omp_const_variable)
5365 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
5366 bool IsDecl =
5367 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5368 Diag(VD->getLocation(),
5369 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5370 << VD;
5371 continue;
5372 }
5373 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
5374 // If a list-item is a reference type then it must bind to the same object
5375 // for all threads of the team.
5376 VarDecl *VDDef = VD->getDefinition();
5377 if (Type->isReferenceType() && VDDef) {
5378 DSARefChecker Check(DSAStack);
5379 if (Check.Visit(VDDef->getInit())) {
5380 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
5381 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
5382 continue;
5383 }
5384 }
5385 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5386 // The type of a list item that appears in a reduction clause must be valid
5387 // for the reduction-identifier. For a max or min reduction in C, the type
5388 // of the list item must be an allowed arithmetic data type: char, int,
5389 // float, double, or _Bool, possibly modified with long, short, signed, or
5390 // unsigned. For a max or min reduction in C++, the type of the list item
5391 // must be an allowed arithmetic data type: char, wchar_t, int, float,
5392 // double, or bool, possibly modified with long, short, signed, or unsigned.
5393 if ((BOK == BO_GT || BOK == BO_LT) &&
5394 !(Type->isScalarType() ||
5395 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
5396 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
5397 << getLangOpts().CPlusPlus;
5398 bool IsDecl =
5399 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5400 Diag(VD->getLocation(),
5401 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5402 << VD;
5403 continue;
5404 }
5405 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
5406 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
5407 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
5408 bool IsDecl =
5409 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5410 Diag(VD->getLocation(),
5411 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5412 << VD;
5413 continue;
5414 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00005415 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5416 // in a Construct]
5417 // Variables with the predetermined data-sharing attributes may not be
5418 // listed in data-sharing attributes clauses, except for the cases
5419 // listed below. For these exceptions only, listing a predetermined
5420 // variable in a data-sharing attribute clause is allowed and overrides
5421 // the variable's predetermined data-sharing attributes.
5422 // OpenMP [2.14.3.6, Restrictions, p.3]
5423 // Any number of reduction clauses can be specified on the directive,
5424 // but a list item can appear only once in the reduction clauses for that
5425 // directive.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005426 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005427 if (DVar.CKind == OMPC_reduction) {
5428 Diag(ELoc, diag::err_omp_once_referenced)
5429 << getOpenMPClauseName(OMPC_reduction);
5430 if (DVar.RefExpr) {
5431 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
5432 }
5433 } else if (DVar.CKind != OMPC_unknown) {
5434 Diag(ELoc, diag::err_omp_wrong_dsa)
5435 << getOpenMPClauseName(DVar.CKind)
5436 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005437 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005438 continue;
5439 }
5440
5441 // OpenMP [2.14.3.6, Restrictions, p.1]
5442 // A list item that appears in a reduction clause of a worksharing
5443 // construct must be shared in the parallel regions to which any of the
5444 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf29276e2014-06-18 04:14:57 +00005445 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataev549210e2014-06-24 04:39:47 +00005446 if (isOpenMPWorksharingDirective(CurrDir) &&
5447 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005448 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005449 if (DVar.CKind != OMPC_shared) {
5450 Diag(ELoc, diag::err_omp_required_access)
5451 << getOpenMPClauseName(OMPC_reduction)
5452 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005453 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005454 continue;
5455 }
5456 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005457 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
5458 auto *LHSVD = BuildVarDecl(*this, ELoc, Type, ".reduction.lhs");
5459 auto *RHSVD = BuildVarDecl(*this, ELoc, Type, VD->getName());
5460 // Add initializer for private variable.
5461 Expr *Init = nullptr;
5462 switch (BOK) {
5463 case BO_Add:
5464 case BO_Xor:
5465 case BO_Or:
5466 case BO_LOr:
5467 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
5468 if (Type->isScalarType() || Type->isAnyComplexType()) {
5469 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005470 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005471 break;
5472 case BO_Mul:
5473 case BO_LAnd:
5474 if (Type->isScalarType() || Type->isAnyComplexType()) {
5475 // '*' and '&&' reduction ops - initializer is '1'.
5476 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
5477 }
5478 break;
5479 case BO_And: {
5480 // '&' reduction op - initializer is '~0'.
5481 QualType OrigType = Type;
5482 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
5483 Type = ComplexTy->getElementType();
5484 }
5485 if (Type->isRealFloatingType()) {
5486 llvm::APFloat InitValue =
5487 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
5488 /*isIEEE=*/true);
5489 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5490 Type, ELoc);
5491 } else if (Type->isScalarType()) {
5492 auto Size = Context.getTypeSize(Type);
5493 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
5494 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
5495 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5496 }
5497 if (Init && OrigType->isAnyComplexType()) {
5498 // Init = 0xFFFF + 0xFFFFi;
5499 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
5500 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
5501 }
5502 Type = OrigType;
5503 break;
5504 }
5505 case BO_LT:
5506 case BO_GT: {
5507 // 'min' reduction op - initializer is 'Largest representable number in
5508 // the reduction list item type'.
5509 // 'max' reduction op - initializer is 'Least representable number in
5510 // the reduction list item type'.
5511 if (Type->isIntegerType() || Type->isPointerType()) {
5512 bool IsSigned = Type->hasSignedIntegerRepresentation();
5513 auto Size = Context.getTypeSize(Type);
5514 QualType IntTy =
5515 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
5516 llvm::APInt InitValue =
5517 (BOK != BO_LT)
5518 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
5519 : llvm::APInt::getMinValue(Size)
5520 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
5521 : llvm::APInt::getMaxValue(Size);
5522 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5523 if (Type->isPointerType()) {
5524 // Cast to pointer type.
5525 auto CastExpr = BuildCStyleCastExpr(
5526 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
5527 SourceLocation(), Init);
5528 if (CastExpr.isInvalid())
5529 continue;
5530 Init = CastExpr.get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005531 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005532 } else if (Type->isRealFloatingType()) {
5533 llvm::APFloat InitValue = llvm::APFloat::getLargest(
5534 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
5535 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5536 Type, ELoc);
5537 }
5538 break;
5539 }
5540 case BO_PtrMemD:
5541 case BO_PtrMemI:
5542 case BO_MulAssign:
5543 case BO_Div:
5544 case BO_Rem:
5545 case BO_Sub:
5546 case BO_Shl:
5547 case BO_Shr:
5548 case BO_LE:
5549 case BO_GE:
5550 case BO_EQ:
5551 case BO_NE:
5552 case BO_AndAssign:
5553 case BO_XorAssign:
5554 case BO_OrAssign:
5555 case BO_Assign:
5556 case BO_AddAssign:
5557 case BO_SubAssign:
5558 case BO_DivAssign:
5559 case BO_RemAssign:
5560 case BO_ShlAssign:
5561 case BO_ShrAssign:
5562 case BO_Comma:
5563 llvm_unreachable("Unexpected reduction operation");
5564 }
5565 if (Init) {
5566 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
5567 /*TypeMayContainAuto=*/false);
5568 } else {
5569 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
5570 }
5571 if (!RHSVD->hasInit()) {
5572 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
5573 << ReductionIdRange;
5574 bool IsDecl =
5575 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5576 Diag(VD->getLocation(),
5577 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5578 << VD;
5579 continue;
5580 }
5581 auto *LHSDRE = BuildDeclRefExpr(LHSVD, Type, VK_LValue, ELoc).get();
5582 auto *RHSDRE = BuildDeclRefExpr(RHSVD, Type, VK_LValue, ELoc).get();
5583 ExprResult ReductionOp =
5584 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
5585 LHSDRE, RHSDRE);
5586 if (ReductionOp.isUsable()) {
5587 if (BOK != BO_LOr && BOK != BO_LAnd) {
5588 ReductionOp =
5589 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5590 BO_Assign, LHSDRE, ReductionOp.get());
5591 } else {
5592 auto *ConditionalOp = new (Context) ConditionalOperator(
5593 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
5594 RHSDRE, Type, VK_LValue, OK_Ordinary);
5595 ReductionOp =
5596 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5597 BO_Assign, LHSDRE, ConditionalOp);
5598 }
5599 if (ReductionOp.isUsable()) {
5600 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005601 }
5602 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005603 if (ReductionOp.isInvalid())
5604 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005605
5606 DSAStack->addDSA(VD, DE, OMPC_reduction);
5607 Vars.push_back(DE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005608 LHSs.push_back(LHSDRE);
5609 RHSs.push_back(RHSDRE);
5610 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005611 }
5612
5613 if (Vars.empty())
5614 return nullptr;
5615
5616 return OMPReductionClause::Create(
5617 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005618 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
5619 RHSs, ReductionOps);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005620}
5621
Alexander Musman8dba6642014-04-22 13:09:42 +00005622OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
5623 SourceLocation StartLoc,
5624 SourceLocation LParenLoc,
5625 SourceLocation ColonLoc,
5626 SourceLocation EndLoc) {
5627 SmallVector<Expr *, 8> Vars;
Alexander Musman3276a272015-03-21 10:12:56 +00005628 SmallVector<Expr *, 8> Inits;
Alexey Bataeved09d242014-05-28 05:53:51 +00005629 for (auto &RefExpr : VarList) {
5630 assert(RefExpr && "NULL expr in OpenMP linear clause.");
5631 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00005632 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005633 Vars.push_back(RefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00005634 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005635 continue;
5636 }
5637
5638 // OpenMP [2.14.3.7, linear clause]
5639 // A list item that appears in a linear clause is subject to the private
5640 // clause semantics described in Section 2.14.3.3 on page 159 except as
5641 // noted. In addition, the value of the new list item on each iteration
5642 // of the associated loop(s) corresponds to the value of the original
5643 // list item before entering the construct plus the logical number of
5644 // the iteration times linear-step.
5645
Alexey Bataeved09d242014-05-28 05:53:51 +00005646 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00005647 // OpenMP [2.1, C/C++]
5648 // A list item is a variable name.
5649 // OpenMP [2.14.3.3, Restrictions, p.1]
5650 // A variable that is part of another variable (as an array or
5651 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005652 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005653 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005654 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00005655 continue;
5656 }
5657
5658 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5659
5660 // OpenMP [2.14.3.7, linear clause]
5661 // A list-item cannot appear in more than one linear clause.
5662 // A list-item that appears in a linear clause cannot appear in any
5663 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005664 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00005665 if (DVar.RefExpr) {
5666 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5667 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005668 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00005669 continue;
5670 }
5671
5672 QualType QType = VD->getType();
5673 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
5674 // It will be analyzed later.
5675 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005676 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005677 continue;
5678 }
5679
5680 // A variable must not have an incomplete type or a reference type.
5681 if (RequireCompleteType(ELoc, QType,
5682 diag::err_omp_linear_incomplete_type)) {
5683 continue;
5684 }
5685 if (QType->isReferenceType()) {
5686 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5687 << getOpenMPClauseName(OMPC_linear) << QType;
5688 bool IsDecl =
5689 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5690 Diag(VD->getLocation(),
5691 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5692 << VD;
5693 continue;
5694 }
5695
5696 // A list item must not be const-qualified.
5697 if (QType.isConstant(Context)) {
5698 Diag(ELoc, diag::err_omp_const_variable)
5699 << getOpenMPClauseName(OMPC_linear);
5700 bool IsDecl =
5701 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5702 Diag(VD->getLocation(),
5703 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5704 << VD;
5705 continue;
5706 }
5707
5708 // A list item must be of integral or pointer type.
5709 QType = QType.getUnqualifiedType().getCanonicalType();
5710 const Type *Ty = QType.getTypePtrOrNull();
5711 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
5712 !Ty->isPointerType())) {
5713 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
5714 bool IsDecl =
5715 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5716 Diag(VD->getLocation(),
5717 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5718 << VD;
5719 continue;
5720 }
5721
Alexander Musman3276a272015-03-21 10:12:56 +00005722 // Build var to save initial value.
5723 VarDecl *Init = BuildVarDecl(*this, ELoc, DE->getType(), ".linear.start");
5724 AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
5725 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
5726 CurContext->addDecl(Init);
5727 Init->setIsUsed();
5728 auto InitRef = DeclRefExpr::Create(
5729 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
5730 /*TemplateKWLoc*/ SourceLocation(), Init,
5731 /*isEnclosingLocal*/ false, DE->getLocStart(), DE->getType(),
5732 /*VK*/ VK_LValue);
Alexander Musman8dba6642014-04-22 13:09:42 +00005733 DSAStack->addDSA(VD, DE, OMPC_linear);
5734 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005735 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00005736 }
5737
5738 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005739 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005740
5741 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00005742 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005743 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5744 !Step->isInstantiationDependent() &&
5745 !Step->containsUnexpandedParameterPack()) {
5746 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005747 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00005748 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005749 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005750 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00005751
Alexander Musman3276a272015-03-21 10:12:56 +00005752 // Build var to save the step value.
5753 VarDecl *SaveVar =
5754 BuildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
5755 CurContext->addDecl(SaveVar);
5756 SaveVar->setIsUsed();
5757 ExprResult SaveRef =
5758 BuildDeclRefExpr(SaveVar, StepExpr->getType(), VK_LValue, StepLoc);
5759 ExprResult CalcStep =
5760 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
5761
Alexander Musman8dba6642014-04-22 13:09:42 +00005762 // Warn about zero linear step (it would be probably better specified as
5763 // making corresponding variables 'const').
5764 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00005765 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
5766 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00005767 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
5768 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00005769 if (!IsConstant && CalcStep.isUsable()) {
5770 // Calculate the step beforehand instead of doing this on each iteration.
5771 // (This is not used if the number of iterations may be kfold-ed).
5772 CalcStepExpr = CalcStep.get();
5773 }
Alexander Musman8dba6642014-04-22 13:09:42 +00005774 }
5775
5776 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
Alexander Musman3276a272015-03-21 10:12:56 +00005777 Vars, Inits, StepExpr, CalcStepExpr);
5778}
5779
5780static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
5781 Expr *NumIterations, Sema &SemaRef,
5782 Scope *S) {
5783 // Walk the vars and build update/final expressions for the CodeGen.
5784 SmallVector<Expr *, 8> Updates;
5785 SmallVector<Expr *, 8> Finals;
5786 Expr *Step = Clause.getStep();
5787 Expr *CalcStep = Clause.getCalcStep();
5788 // OpenMP [2.14.3.7, linear clause]
5789 // If linear-step is not specified it is assumed to be 1.
5790 if (Step == nullptr)
5791 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5792 else if (CalcStep)
5793 Step = cast<BinaryOperator>(CalcStep)->getLHS();
5794 bool HasErrors = false;
5795 auto CurInit = Clause.inits().begin();
5796 for (auto &RefExpr : Clause.varlists()) {
5797 Expr *InitExpr = *CurInit;
5798
5799 // Build privatized reference to the current linear var.
5800 auto DE = cast<DeclRefExpr>(RefExpr);
5801 auto PrivateRef = DeclRefExpr::Create(
5802 SemaRef.Context, /*QualifierLoc*/ DE->getQualifierLoc(),
5803 /*TemplateKWLoc*/ SourceLocation(), DE->getDecl(),
5804 /* RefersToEnclosingVariableOrCapture */ true, DE->getLocStart(),
5805 DE->getType(), /*VK*/ VK_LValue);
5806
5807 // Build update: Var = InitExpr + IV * Step
5808 ExprResult Update =
5809 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
5810 InitExpr, IV, Step, /* Subtract */ false);
5811 Update = SemaRef.ActOnFinishFullExpr(Update.get());
5812
5813 // Build final: Var = InitExpr + NumIterations * Step
5814 ExprResult Final =
5815 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), RefExpr, InitExpr,
5816 NumIterations, Step, /* Subtract */ false);
5817 Final = SemaRef.ActOnFinishFullExpr(Final.get());
5818 if (!Update.isUsable() || !Final.isUsable()) {
5819 Updates.push_back(nullptr);
5820 Finals.push_back(nullptr);
5821 HasErrors = true;
5822 } else {
5823 Updates.push_back(Update.get());
5824 Finals.push_back(Final.get());
5825 }
5826 ++CurInit;
5827 }
5828 Clause.setUpdates(Updates);
5829 Clause.setFinals(Finals);
5830 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00005831}
5832
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005833OMPClause *Sema::ActOnOpenMPAlignedClause(
5834 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
5835 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
5836
5837 SmallVector<Expr *, 8> Vars;
5838 for (auto &RefExpr : VarList) {
5839 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
5840 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5841 // It will be analyzed later.
5842 Vars.push_back(RefExpr);
5843 continue;
5844 }
5845
5846 SourceLocation ELoc = RefExpr->getExprLoc();
5847 // OpenMP [2.1, C/C++]
5848 // A list item is a variable name.
5849 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5850 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5851 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5852 continue;
5853 }
5854
5855 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5856
5857 // OpenMP [2.8.1, simd construct, Restrictions]
5858 // The type of list items appearing in the aligned clause must be
5859 // array, pointer, reference to array, or reference to pointer.
5860 QualType QType = DE->getType()
5861 .getNonReferenceType()
5862 .getUnqualifiedType()
5863 .getCanonicalType();
5864 const Type *Ty = QType.getTypePtrOrNull();
5865 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
5866 !Ty->isPointerType())) {
5867 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
5868 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
5869 bool IsDecl =
5870 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5871 Diag(VD->getLocation(),
5872 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5873 << VD;
5874 continue;
5875 }
5876
5877 // OpenMP [2.8.1, simd construct, Restrictions]
5878 // A list-item cannot appear in more than one aligned clause.
5879 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
5880 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
5881 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
5882 << getOpenMPClauseName(OMPC_aligned);
5883 continue;
5884 }
5885
5886 Vars.push_back(DE);
5887 }
5888
5889 // OpenMP [2.8.1, simd construct, Description]
5890 // The parameter of the aligned clause, alignment, must be a constant
5891 // positive integer expression.
5892 // If no optional parameter is specified, implementation-defined default
5893 // alignments for SIMD instructions on the target platforms are assumed.
5894 if (Alignment != nullptr) {
5895 ExprResult AlignResult =
5896 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
5897 if (AlignResult.isInvalid())
5898 return nullptr;
5899 Alignment = AlignResult.get();
5900 }
5901 if (Vars.empty())
5902 return nullptr;
5903
5904 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
5905 EndLoc, Vars, Alignment);
5906}
5907
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005908OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
5909 SourceLocation StartLoc,
5910 SourceLocation LParenLoc,
5911 SourceLocation EndLoc) {
5912 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00005913 for (auto &RefExpr : VarList) {
5914 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
5915 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005916 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005917 Vars.push_back(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005918 continue;
5919 }
5920
Alexey Bataeved09d242014-05-28 05:53:51 +00005921 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005922 // OpenMP [2.1, C/C++]
5923 // A list item is a variable name.
5924 // OpenMP [2.14.4.1, Restrictions, p.1]
5925 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00005926 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005927 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005928 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005929 continue;
5930 }
5931
5932 Decl *D = DE->getDecl();
5933 VarDecl *VD = cast<VarDecl>(D);
5934
5935 QualType Type = VD->getType();
5936 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5937 // It will be analyzed later.
5938 Vars.push_back(DE);
5939 continue;
5940 }
5941
5942 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
5943 // A list item that appears in a copyin clause must be threadprivate.
5944 if (!DSAStack->isThreadPrivate(VD)) {
5945 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00005946 << getOpenMPClauseName(OMPC_copyin)
5947 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005948 continue;
5949 }
5950
5951 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
5952 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00005953 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005954 // operator for the class type.
5955 Type = Context.getBaseElementType(Type);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005956 CXXRecordDecl *RD =
5957 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev23b69422014-06-18 07:08:49 +00005958 // FIXME This code must be replaced by actual assignment of the
5959 // threadprivate variable.
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005960 if (RD) {
5961 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
5962 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005963 if (MD) {
5964 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
5965 MD->isDeleted()) {
5966 Diag(ELoc, diag::err_omp_required_method)
5967 << getOpenMPClauseName(OMPC_copyin) << 2;
5968 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5969 VarDecl::DeclarationOnly;
5970 Diag(VD->getLocation(),
5971 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5972 << VD;
5973 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5974 continue;
5975 }
5976 MarkFunctionReferenced(ELoc, MD);
5977 DiagnoseUseOfDecl(MD, ELoc);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005978 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005979 }
5980
5981 DSAStack->addDSA(VD, DE, OMPC_copyin);
5982 Vars.push_back(DE);
5983 }
5984
Alexey Bataeved09d242014-05-28 05:53:51 +00005985 if (Vars.empty())
5986 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005987
5988 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5989}
5990
Alexey Bataevbae9a792014-06-27 10:37:06 +00005991OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
5992 SourceLocation StartLoc,
5993 SourceLocation LParenLoc,
5994 SourceLocation EndLoc) {
5995 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00005996 SmallVector<Expr *, 8> SrcExprs;
5997 SmallVector<Expr *, 8> DstExprs;
5998 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00005999 for (auto &RefExpr : VarList) {
6000 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
6001 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6002 // It will be analyzed later.
6003 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006004 SrcExprs.push_back(nullptr);
6005 DstExprs.push_back(nullptr);
6006 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006007 continue;
6008 }
6009
6010 SourceLocation ELoc = RefExpr->getExprLoc();
6011 // OpenMP [2.1, C/C++]
6012 // A list item is a variable name.
6013 // OpenMP [2.14.4.1, Restrictions, p.1]
6014 // A list item that appears in a copyin clause must be threadprivate.
6015 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6016 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6017 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6018 continue;
6019 }
6020
6021 Decl *D = DE->getDecl();
6022 VarDecl *VD = cast<VarDecl>(D);
6023
6024 QualType Type = VD->getType();
6025 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6026 // It will be analyzed later.
6027 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006028 SrcExprs.push_back(nullptr);
6029 DstExprs.push_back(nullptr);
6030 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006031 continue;
6032 }
6033
6034 // OpenMP [2.14.4.2, Restrictions, p.2]
6035 // A list item that appears in a copyprivate clause may not appear in a
6036 // private or firstprivate clause on the single construct.
6037 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006038 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006039 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
6040 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00006041 Diag(ELoc, diag::err_omp_wrong_dsa)
6042 << getOpenMPClauseName(DVar.CKind)
6043 << getOpenMPClauseName(OMPC_copyprivate);
6044 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6045 continue;
6046 }
6047
6048 // OpenMP [2.11.4.2, Restrictions, p.1]
6049 // All list items that appear in a copyprivate clause must be either
6050 // threadprivate or private in the enclosing context.
6051 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006052 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006053 if (DVar.CKind == OMPC_shared) {
6054 Diag(ELoc, diag::err_omp_required_access)
6055 << getOpenMPClauseName(OMPC_copyprivate)
6056 << "threadprivate or private in the enclosing context";
6057 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6058 continue;
6059 }
6060 }
6061 }
6062
6063 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6064 // A variable of class type (or array thereof) that appears in a
6065 // copyin clause requires an accessible, unambiguous copy assignment
6066 // operator for the class type.
Alexey Bataev420d45b2015-04-14 05:11:24 +00006067 Type = Context.getBaseElementType(Type).getUnqualifiedType();
6068 auto *SrcVD =
6069 BuildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src");
6070 auto *PseudoSrcExpr =
6071 BuildDeclRefExpr(SrcVD, Type, VK_LValue, DE->getExprLoc()).get();
6072 auto *DstVD =
6073 BuildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst");
6074 auto *PseudoDstExpr =
6075 BuildDeclRefExpr(DstVD, Type, VK_LValue, DE->getExprLoc()).get();
Alexey Bataeva63048e2015-03-23 06:18:07 +00006076 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6077 PseudoDstExpr, PseudoSrcExpr);
6078 if (AssignmentOp.isInvalid())
6079 continue;
6080 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6081 /*DiscardedValue=*/true);
6082 if (AssignmentOp.isInvalid())
6083 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006084
6085 // No need to mark vars as copyprivate, they are already threadprivate or
6086 // implicitly private.
6087 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006088 SrcExprs.push_back(PseudoSrcExpr);
6089 DstExprs.push_back(PseudoDstExpr);
6090 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00006091 }
6092
6093 if (Vars.empty())
6094 return nullptr;
6095
Alexey Bataeva63048e2015-03-23 06:18:07 +00006096 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6097 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006098}
6099
Alexey Bataev6125da92014-07-21 11:26:11 +00006100OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
6101 SourceLocation StartLoc,
6102 SourceLocation LParenLoc,
6103 SourceLocation EndLoc) {
6104 if (VarList.empty())
6105 return nullptr;
6106
6107 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
6108}
Alexey Bataevdea47612014-07-23 07:46:59 +00006109