blob: 06b9d56cdc76f870fcd7771f5a3955adbf6f0cec [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) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000241 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000242 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000243 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000244 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
245 // in a region but not in construct]
246 // File-scope or namespace-scope variables referenced in called routines
247 // in the region are shared unless they appear in a threadprivate
248 // directive.
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000249 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000250 DVar.CKind = OMPC_shared;
251
252 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
253 // in a region but not in construct]
254 // Variables with static storage duration that are declared in called
255 // routines in the region are shared.
256 if (D->hasGlobalStorage())
257 DVar.CKind = OMPC_shared;
258
Alexey Bataev758e55e2013-09-06 18:03:48 +0000259 return DVar;
260 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000261
Alexey Bataev758e55e2013-09-06 18:03:48 +0000262 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000263 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
264 // in a Construct, C/C++, predetermined, p.1]
265 // Variables with automatic storage duration that are declared in a scope
266 // inside the construct are private.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000267 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
268 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
269 DVar.CKind = OMPC_private;
270 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000271 }
272
Alexey Bataev758e55e2013-09-06 18:03:48 +0000273 // Explicitly specified attributes and local variables with predetermined
274 // attributes.
275 if (Iter->SharingMap.count(D)) {
276 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
277 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000278 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000279 return DVar;
280 }
281
282 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
283 // in a Construct, C/C++, implicitly determined, p.1]
284 // In a parallel or task construct, the data-sharing attributes of these
285 // variables are determined by the default clause, if present.
286 switch (Iter->DefaultAttr) {
287 case DSA_shared:
288 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000289 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000290 return DVar;
291 case DSA_none:
292 return DVar;
293 case DSA_unspecified:
294 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
295 // in a Construct, implicitly determined, p.2]
296 // In a parallel construct, if no default clause is present, these
297 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000298 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000299 if (isOpenMPParallelDirective(DVar.DKind) ||
300 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000301 DVar.CKind = OMPC_shared;
302 return DVar;
303 }
304
305 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
306 // in a Construct, implicitly determined, p.4]
307 // In a task construct, if no default clause is present, a variable that in
308 // the enclosing context is determined to be shared by all implicit tasks
309 // bound to the current team is shared.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000310 if (DVar.DKind == OMPD_task) {
311 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000312 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000313 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000314 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
315 // Referenced
Alexey Bataev758e55e2013-09-06 18:03:48 +0000316 // in a Construct, implicitly determined, p.6]
317 // In a task construct, if no default clause is present, a variable
318 // whose data-sharing attribute is not determined by the rules above is
319 // firstprivate.
320 DVarTemp = getDSA(I, D);
321 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000322 DVar.RefExpr = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000323 DVar.DKind = OMPD_task;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000324 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000325 return DVar;
326 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000327 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000328 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000329 }
330 DVar.DKind = OMPD_task;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000331 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000332 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000333 return DVar;
334 }
335 }
336 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
337 // in a Construct, implicitly determined, p.3]
338 // For constructs other than task, if no default clause is present, these
339 // variables inherit their data-sharing attributes from the enclosing
340 // context.
Benjamin Kramer167e9992014-03-02 12:20:24 +0000341 return getDSA(std::next(Iter), D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000342}
343
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000344DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
345 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000346 D = D->getCanonicalDecl();
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000347 auto It = Stack.back().AlignedMap.find(D);
348 if (It == Stack.back().AlignedMap.end()) {
349 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
350 Stack.back().AlignedMap[D] = NewDE;
351 return nullptr;
352 } else {
353 assert(It->second && "Unexpected nullptr expr in the aligned map");
354 return It->second;
355 }
356 return nullptr;
357}
358
Alexey Bataev758e55e2013-09-06 18:03:48 +0000359void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000360 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000361 if (A == OMPC_threadprivate) {
362 Stack[0].SharingMap[D].Attributes = A;
363 Stack[0].SharingMap[D].RefExpr = E;
364 } else {
365 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
366 Stack.back().SharingMap[D].Attributes = A;
367 Stack.back().SharingMap[D].RefExpr = E;
368 }
369}
370
Alexey Bataeved09d242014-05-28 05:53:51 +0000371bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000372 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000373 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000374 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000375 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000376 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000377 ++I;
378 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000379 if (I == E)
380 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000381 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000382 Scope *CurScope = getCurScope();
383 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000384 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000385 }
386 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000387 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000388 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000389}
390
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000391DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000392 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000393 DSAVarData DVar;
394
395 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
396 // in a Construct, C/C++, predetermined, p.1]
397 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev26a39242015-01-13 03:35:30 +0000398 if (D->getTLSKind() != VarDecl::TLS_None ||
399 D->getStorageClass() == SC_Register) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000400 DVar.CKind = OMPC_threadprivate;
401 return DVar;
402 }
403 if (Stack[0].SharingMap.count(D)) {
404 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
405 DVar.CKind = OMPC_threadprivate;
406 return DVar;
407 }
408
409 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
410 // in a Construct, C/C++, predetermined, p.1]
411 // Variables with automatic storage duration that are declared in a scope
412 // inside the construct are private.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000413 OpenMPDirectiveKind Kind =
414 FromParent ? getParentDirective() : getCurrentDirective();
415 auto StartI = std::next(Stack.rbegin());
416 auto EndI = std::prev(Stack.rend());
417 if (FromParent && StartI != EndI) {
418 StartI = std::next(StartI);
419 }
420 if (!isParallelOrTaskRegion(Kind)) {
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000421 if (isOpenMPLocal(D, StartI) &&
422 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
423 D->getStorageClass() == SC_None)) ||
424 isa<ParmVarDecl>(D))) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000425 DVar.CKind = OMPC_private;
426 return DVar;
Alexander Musman8dba6642014-04-22 13:09:42 +0000427 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000428
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000429 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
430 // in a Construct, C/C++, predetermined, p.4]
431 // Static data members are shared.
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000432 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
433 // in a Construct, C/C++, predetermined, p.7]
434 // Variables with static storage duration that are declared in a scope
435 // inside the construct are shared.
Alexey Bataev42971a32015-01-20 07:03:46 +0000436 if (D->isStaticDataMember() || D->isStaticLocal()) {
437 DSAVarData DVarTemp =
438 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
439 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
440 return DVar;
441
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000442 DVar.CKind = OMPC_shared;
443 return DVar;
444 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000445 }
446
447 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataev7ff55242014-06-19 09:13:45 +0000448 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
Alexey Bataev758e55e2013-09-06 18:03:48 +0000449 while (Type->isArrayType()) {
450 QualType ElemType = cast<ArrayType>(Type.getTypePtr())->getElementType();
451 Type = ElemType.getNonReferenceType().getCanonicalType();
452 }
453 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
454 // in a Construct, C/C++, predetermined, p.6]
455 // Variables with const qualified type having no mutable member are
456 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000457 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000458 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000459 if (IsConstant &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000460 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000461 // Variables with const-qualified type having no mutable member may be
462 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000463 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
464 MatchesAlways(), FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000465 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
466 return DVar;
467
Alexey Bataev758e55e2013-09-06 18:03:48 +0000468 DVar.CKind = OMPC_shared;
469 return DVar;
470 }
471
Alexey Bataev758e55e2013-09-06 18:03:48 +0000472 // Explicitly specified attributes and local variables with predetermined
473 // attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000474 auto I = std::prev(StartI);
475 if (I->SharingMap.count(D)) {
476 DVar.RefExpr = I->SharingMap[D].RefExpr;
477 DVar.CKind = I->SharingMap[D].Attributes;
478 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000479 }
480
481 return DVar;
482}
483
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000484DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000485 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000486 auto StartI = Stack.rbegin();
487 auto EndI = std::prev(Stack.rend());
488 if (FromParent && StartI != EndI) {
489 StartI = std::next(StartI);
490 }
491 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000492}
493
Alexey Bataevf29276e2014-06-18 04:14:57 +0000494template <class ClausesPredicate, class DirectivesPredicate>
495DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000496 DirectivesPredicate DPred,
497 bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000498 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000499 auto StartI = std::next(Stack.rbegin());
500 auto EndI = std::prev(Stack.rend());
501 if (FromParent && StartI != EndI) {
502 StartI = std::next(StartI);
503 }
504 for (auto I = StartI, EE = EndI; I != EE; ++I) {
505 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000506 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000507 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000508 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000509 return DVar;
510 }
511 return DSAVarData();
512}
513
Alexey Bataevf29276e2014-06-18 04:14:57 +0000514template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000515DSAStackTy::DSAVarData
516DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
517 DirectivesPredicate DPred, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000518 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000519 auto StartI = std::next(Stack.rbegin());
520 auto EndI = std::prev(Stack.rend());
521 if (FromParent && StartI != EndI) {
522 StartI = std::next(StartI);
523 }
524 for (auto I = StartI, EE = EndI; I != EE; ++I) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000525 if (!DPred(I->Directive))
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000526 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +0000527 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000528 if (CPred(DVar.CKind))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000529 return DVar;
530 return DSAVarData();
531 }
532 return DSAVarData();
533}
534
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000535template <class NamedDirectivesPredicate>
536bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
537 auto StartI = std::next(Stack.rbegin());
538 auto EndI = std::prev(Stack.rend());
539 if (FromParent && StartI != EndI) {
540 StartI = std::next(StartI);
541 }
542 for (auto I = StartI, EE = EndI; I != EE; ++I) {
543 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
544 return true;
545 }
546 return false;
547}
548
Alexey Bataev758e55e2013-09-06 18:03:48 +0000549void Sema::InitDataSharingAttributesStack() {
550 VarDataSharingAttributesStack = new DSAStackTy(*this);
551}
552
553#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
554
Alexey Bataevf841bd92014-12-16 07:00:22 +0000555bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
556 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000557 VD = VD->getCanonicalDecl();
Alexey Bataevf841bd92014-12-16 07:00:22 +0000558 if (DSAStack->getCurrentDirective() != OMPD_unknown) {
559 auto DVarPrivate = DSAStack->getTopDSA(VD, /*FromParent=*/false);
560 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
561 return true;
562 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
563 /*FromParent=*/false);
564 return DVarPrivate.CKind != OMPC_unknown;
565 }
566 return false;
567}
568
Alexey Bataeved09d242014-05-28 05:53:51 +0000569void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000570
571void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
572 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000573 Scope *CurScope, SourceLocation Loc) {
574 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000575 PushExpressionEvaluationContext(PotentiallyEvaluated);
576}
577
578void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000579 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
580 // A variable of class type (or array thereof) that appears in a lastprivate
581 // clause requires an accessible, unambiguous default constructor for the
582 // class type, unless the list item is also specified in a firstprivate
583 // clause.
584 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000585 for (auto *C : D->clauses()) {
586 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
587 SmallVector<Expr *, 8> PrivateCopies;
588 for (auto *DE : Clause->varlists()) {
589 if (DE->isValueDependent() || DE->isTypeDependent()) {
590 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000591 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +0000592 }
593 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000594 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000595 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000596 // Generate helper private variable and initialize it with the
597 // default value. The address of the original variable is replaced
598 // by the address of the new private variable in CodeGen. This new
599 // variable is not added to IdResolver, so the code in the OpenMP
600 // region uses original variable for proper diagnostics.
601 auto *VDPrivate = VarDecl::Create(
602 Context, CurContext, DE->getLocStart(), DE->getExprLoc(),
603 VD->getIdentifier(), VD->getType(), VD->getTypeSourceInfo(),
604 SC_Auto);
605 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
606 if (VDPrivate->isInvalidDecl())
607 continue;
608 CurContext->addDecl(VDPrivate);
609 PrivateCopies.push_back(DeclRefExpr::Create(
610 Context, NestedNameSpecifierLoc(), SourceLocation(), VDPrivate,
611 /*RefersToEnclosingVariableOrCapture=*/false, SourceLocation(),
612 DE->getType(), VK_LValue));
613 } else {
614 // The variable is also a firstprivate, so initialization sequence
615 // for private copy is generated already.
616 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000617 }
618 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000619 // Set initializers to private copies if no errors were found.
620 if (PrivateCopies.size() == Clause->varlist_size()) {
621 Clause->setPrivateCopies(PrivateCopies);
622 }
Alexey Bataevf29276e2014-06-18 04:14:57 +0000623 }
624 }
625 }
626
Alexey Bataev758e55e2013-09-06 18:03:48 +0000627 DSAStack->pop();
628 DiscardCleanupsInEvaluationContext();
629 PopExpressionEvaluationContext();
630}
631
Alexander Musman3276a272015-03-21 10:12:56 +0000632static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
633 Expr *NumIterations, Sema &SemaRef,
634 Scope *S);
635
Alexey Bataeva769e072013-03-22 06:34:35 +0000636namespace {
637
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000638class VarDeclFilterCCC : public CorrectionCandidateCallback {
639private:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000640 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +0000641
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000642public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000643 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +0000644 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000645 NamedDecl *ND = Candidate.getCorrectionDecl();
646 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
647 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000648 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
649 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +0000650 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000651 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +0000652 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000653};
Alexey Bataeved09d242014-05-28 05:53:51 +0000654} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000655
656ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
657 CXXScopeSpec &ScopeSpec,
658 const DeclarationNameInfo &Id) {
659 LookupResult Lookup(*this, Id, LookupOrdinaryName);
660 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
661
662 if (Lookup.isAmbiguous())
663 return ExprError();
664
665 VarDecl *VD;
666 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000667 if (TypoCorrection Corrected = CorrectTypo(
668 Id, LookupOrdinaryName, CurScope, nullptr,
669 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000670 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000671 PDiag(Lookup.empty()
672 ? diag::err_undeclared_var_use_suggest
673 : diag::err_omp_expected_var_arg_suggest)
674 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +0000675 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000676 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000677 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
678 : diag::err_omp_expected_var_arg)
679 << Id.getName();
680 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000681 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000682 } else {
683 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000684 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000685 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
686 return ExprError();
687 }
688 }
689 Lookup.suppressDiagnostics();
690
691 // OpenMP [2.9.2, Syntax, C/C++]
692 // Variables must be file-scope, namespace-scope, or static block-scope.
693 if (!VD->hasGlobalStorage()) {
694 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000695 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
696 bool IsDecl =
697 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000698 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +0000699 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
700 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000701 return ExprError();
702 }
703
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000704 VarDecl *CanonicalVD = VD->getCanonicalDecl();
705 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000706 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
707 // A threadprivate directive for file-scope variables must appear outside
708 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000709 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
710 !getCurLexicalContext()->isTranslationUnit()) {
711 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000712 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
713 bool IsDecl =
714 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
715 Diag(VD->getLocation(),
716 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
717 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000718 return ExprError();
719 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000720 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
721 // A threadprivate directive for static class member variables must appear
722 // in the class definition, in the same scope in which the member
723 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000724 if (CanonicalVD->isStaticDataMember() &&
725 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
726 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000727 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
728 bool IsDecl =
729 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
730 Diag(VD->getLocation(),
731 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
732 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000733 return ExprError();
734 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000735 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
736 // A threadprivate directive for namespace-scope variables must appear
737 // outside any definition or declaration other than the namespace
738 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000739 if (CanonicalVD->getDeclContext()->isNamespace() &&
740 (!getCurLexicalContext()->isFileContext() ||
741 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
742 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000743 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
744 bool IsDecl =
745 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
746 Diag(VD->getLocation(),
747 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
748 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000749 return ExprError();
750 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000751 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
752 // A threadprivate directive for static block-scope variables must appear
753 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000754 if (CanonicalVD->isStaticLocal() && CurScope &&
755 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000756 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000757 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
758 bool IsDecl =
759 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
760 Diag(VD->getLocation(),
761 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
762 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000763 return ExprError();
764 }
765
766 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
767 // A threadprivate directive must lexically precede all references to any
768 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000769 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000770 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +0000771 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000772 return ExprError();
773 }
774
775 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataevd178ad42014-03-07 08:03:37 +0000776 ExprResult DE = BuildDeclRefExpr(VD, ExprType, VK_LValue, Id.getLoc());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000777 return DE;
778}
779
Alexey Bataeved09d242014-05-28 05:53:51 +0000780Sema::DeclGroupPtrTy
781Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
782 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000783 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000784 CurContext->addDecl(D);
785 return DeclGroupPtrTy::make(DeclGroupRef(D));
786 }
787 return DeclGroupPtrTy();
788}
789
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000790namespace {
791class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
792 Sema &SemaRef;
793
794public:
795 bool VisitDeclRefExpr(const DeclRefExpr *E) {
796 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
797 if (VD->hasLocalStorage()) {
798 SemaRef.Diag(E->getLocStart(),
799 diag::err_omp_local_var_in_threadprivate_init)
800 << E->getSourceRange();
801 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
802 << VD << VD->getSourceRange();
803 return true;
804 }
805 }
806 return false;
807 }
808 bool VisitStmt(const Stmt *S) {
809 for (auto Child : S->children()) {
810 if (Child && Visit(Child))
811 return true;
812 }
813 return false;
814 }
Alexey Bataev23b69422014-06-18 07:08:49 +0000815 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000816};
817} // namespace
818
Alexey Bataeved09d242014-05-28 05:53:51 +0000819OMPThreadPrivateDecl *
820Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000821 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +0000822 for (auto &RefExpr : VarList) {
823 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000824 VarDecl *VD = cast<VarDecl>(DE->getDecl());
825 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +0000826
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000827 QualType QType = VD->getType();
828 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
829 // It will be analyzed later.
830 Vars.push_back(DE);
831 continue;
832 }
833
Alexey Bataeva769e072013-03-22 06:34:35 +0000834 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
835 // A threadprivate variable must not have an incomplete type.
836 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000837 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000838 continue;
839 }
840
841 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
842 // A threadprivate variable must not have a reference type.
843 if (VD->getType()->isReferenceType()) {
844 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000845 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
846 bool IsDecl =
847 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
848 Diag(VD->getLocation(),
849 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
850 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000851 continue;
852 }
853
Richard Smithfd3834f2013-04-13 02:43:54 +0000854 // Check if this is a TLS variable.
Alexey Bataev26a39242015-01-13 03:35:30 +0000855 if (VD->getTLSKind() != VarDecl::TLS_None ||
856 VD->getStorageClass() == SC_Register) {
857 Diag(ILoc, diag::err_omp_var_thread_local)
858 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +0000859 bool IsDecl =
860 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
861 Diag(VD->getLocation(),
862 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
863 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000864 continue;
865 }
866
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000867 // Check if initial value of threadprivate variable reference variable with
868 // local storage (it is not supported by runtime).
869 if (auto Init = VD->getAnyInitializer()) {
870 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000871 if (Checker.Visit(Init))
872 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000873 }
874
Alexey Bataeved09d242014-05-28 05:53:51 +0000875 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +0000876 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +0000877 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
878 Context, SourceRange(Loc, Loc)));
879 if (auto *ML = Context.getASTMutationListener())
880 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +0000881 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000882 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000883 if (!Vars.empty()) {
884 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
885 Vars);
886 D->setAccess(AS_public);
887 }
888 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +0000889}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000890
Alexey Bataev7ff55242014-06-19 09:13:45 +0000891static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
892 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
893 bool IsLoopIterVar = false) {
894 if (DVar.RefExpr) {
895 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
896 << getOpenMPClauseName(DVar.CKind);
897 return;
898 }
899 enum {
900 PDSA_StaticMemberShared,
901 PDSA_StaticLocalVarShared,
902 PDSA_LoopIterVarPrivate,
903 PDSA_LoopIterVarLinear,
904 PDSA_LoopIterVarLastprivate,
905 PDSA_ConstVarShared,
906 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000907 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000908 PDSA_LocalVarPrivate,
909 PDSA_Implicit
910 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000911 bool ReportHint = false;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000912 auto ReportLoc = VD->getLocation();
Alexey Bataev7ff55242014-06-19 09:13:45 +0000913 if (IsLoopIterVar) {
914 if (DVar.CKind == OMPC_private)
915 Reason = PDSA_LoopIterVarPrivate;
916 else if (DVar.CKind == OMPC_lastprivate)
917 Reason = PDSA_LoopIterVarLastprivate;
918 else
919 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000920 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
921 Reason = PDSA_TaskVarFirstprivate;
922 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000923 } else if (VD->isStaticLocal())
924 Reason = PDSA_StaticLocalVarShared;
925 else if (VD->isStaticDataMember())
926 Reason = PDSA_StaticMemberShared;
927 else if (VD->isFileVarDecl())
928 Reason = PDSA_GlobalVarShared;
929 else if (VD->getType().isConstant(SemaRef.getASTContext()))
930 Reason = PDSA_ConstVarShared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000931 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +0000932 ReportHint = true;
933 Reason = PDSA_LocalVarPrivate;
934 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000935 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000936 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +0000937 << Reason << ReportHint
938 << getOpenMPDirectiveName(Stack->getCurrentDirective());
939 } else if (DVar.ImplicitDSALoc.isValid()) {
940 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
941 << getOpenMPClauseName(DVar.CKind);
942 }
Alexey Bataev7ff55242014-06-19 09:13:45 +0000943}
944
Alexey Bataev758e55e2013-09-06 18:03:48 +0000945namespace {
946class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
947 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000948 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000949 bool ErrorFound;
950 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000951 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev4acb8592014-07-07 13:01:15 +0000952 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +0000953
Alexey Bataev758e55e2013-09-06 18:03:48 +0000954public:
955 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000956 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000957 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +0000958 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
959 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000960
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000961 auto DVar = Stack->getTopDSA(VD, false);
962 // Check if the variable has explicit DSA set and stop analysis if it so.
963 if (DVar.RefExpr) return;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000964
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000965 auto ELoc = E->getExprLoc();
966 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000967 // The default(none) clause requires that each variable that is referenced
968 // in the construct, and does not have a predetermined data-sharing
969 // attribute, must have its data-sharing attribute explicitly determined
970 // by being listed in a data-sharing attribute clause.
971 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000972 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +0000973 VarsWithInheritedDSA.count(VD) == 0) {
974 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000975 return;
976 }
977
978 // OpenMP [2.9.3.6, Restrictions, p.2]
979 // A list item that appears in a reduction clause of the innermost
980 // enclosing worksharing or parallel construct may not be accessed in an
981 // explicit task.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000982 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000983 [](OpenMPDirectiveKind K) -> bool {
984 return isOpenMPParallelDirective(K) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +0000985 isOpenMPWorksharingDirective(K) ||
986 isOpenMPTeamsDirective(K);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000987 },
988 false);
Alexey Bataevc5e02582014-06-16 07:08:35 +0000989 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
990 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000991 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
992 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +0000993 return;
994 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000995
996 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000997 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000998 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000999 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001000 }
1001 }
1002 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001003 for (auto *C : S->clauses()) {
1004 // Skip analysis of arguments of implicitly defined firstprivate clause
1005 // for task directives.
1006 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1007 for (auto *CC : C->children()) {
1008 if (CC)
1009 Visit(CC);
1010 }
1011 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001012 }
1013 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001014 for (auto *C : S->children()) {
1015 if (C && !isa<OMPExecutableDirective>(C))
1016 Visit(C);
1017 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001018 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001019
1020 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001021 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001022 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1023 return VarsWithInheritedDSA;
1024 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001025
Alexey Bataev7ff55242014-06-19 09:13:45 +00001026 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1027 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001028};
Alexey Bataeved09d242014-05-28 05:53:51 +00001029} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001030
Alexey Bataevbae9a792014-06-27 10:37:06 +00001031void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001032 switch (DKind) {
1033 case OMPD_parallel: {
1034 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1035 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001036 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001037 std::make_pair(".global_tid.", KmpInt32PtrTy),
1038 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1039 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 }
1045 case OMPD_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001046 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001047 std::make_pair(StringRef(), QualType()) // __context with shared vars
1048 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001049 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1050 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001051 break;
1052 }
1053 case OMPD_for: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001054 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001055 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001056 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001057 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1058 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001059 break;
1060 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001061 case OMPD_for_simd: {
1062 Sema::CapturedParamNameType Params[] = {
1063 std::make_pair(StringRef(), QualType()) // __context with shared vars
1064 };
1065 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1066 Params);
1067 break;
1068 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001069 case OMPD_sections: {
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 Bataevd3f8dd22014-06-25 11:44:49 +00001075 break;
1076 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001077 case OMPD_section: {
1078 Sema::CapturedParamNameType Params[] = {
1079 std::make_pair(StringRef(), QualType()) // __context with shared vars
1080 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001081 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1082 Params);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001083 break;
1084 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001085 case OMPD_single: {
1086 Sema::CapturedParamNameType Params[] = {
1087 std::make_pair(StringRef(), QualType()) // __context with shared vars
1088 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001089 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1090 Params);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001091 break;
1092 }
Alexander Musman80c22892014-07-17 08:54:58 +00001093 case OMPD_master: {
1094 Sema::CapturedParamNameType Params[] = {
1095 std::make_pair(StringRef(), QualType()) // __context with shared vars
1096 };
1097 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1098 Params);
1099 break;
1100 }
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001101 case OMPD_critical: {
1102 Sema::CapturedParamNameType Params[] = {
1103 std::make_pair(StringRef(), QualType()) // __context with shared vars
1104 };
1105 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1106 Params);
1107 break;
1108 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001109 case OMPD_parallel_for: {
1110 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1111 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1112 Sema::CapturedParamNameType Params[] = {
1113 std::make_pair(".global_tid.", KmpInt32PtrTy),
1114 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1115 std::make_pair(StringRef(), QualType()) // __context with shared vars
1116 };
1117 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1118 Params);
1119 break;
1120 }
Alexander Musmane4e893b2014-09-23 09:33:00 +00001121 case OMPD_parallel_for_simd: {
1122 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1123 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1124 Sema::CapturedParamNameType Params[] = {
1125 std::make_pair(".global_tid.", KmpInt32PtrTy),
1126 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1127 std::make_pair(StringRef(), QualType()) // __context with shared vars
1128 };
1129 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1130 Params);
1131 break;
1132 }
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001133 case OMPD_parallel_sections: {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001134 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1135 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001136 Sema::CapturedParamNameType Params[] = {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001137 std::make_pair(".global_tid.", KmpInt32PtrTy),
1138 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001139 std::make_pair(StringRef(), QualType()) // __context with shared vars
1140 };
1141 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1142 Params);
1143 break;
1144 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001145 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001146 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001147 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001148 std::make_pair(".global_tid.", KmpInt32Ty),
1149 std::make_pair(".part_id.", KmpInt32Ty),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001150 std::make_pair(StringRef(), QualType()) // __context with shared vars
1151 };
1152 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1153 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001154 // Mark this captured region as inlined, because we don't use outlined
1155 // function directly.
1156 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1157 AlwaysInlineAttr::CreateImplicit(
1158 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001159 break;
1160 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001161 case OMPD_ordered: {
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 Bataev0162e452014-07-22 10:10:35 +00001169 case OMPD_atomic: {
1170 Sema::CapturedParamNameType Params[] = {
1171 std::make_pair(StringRef(), QualType()) // __context with shared vars
1172 };
1173 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1174 Params);
1175 break;
1176 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001177 case OMPD_target: {
1178 Sema::CapturedParamNameType Params[] = {
1179 std::make_pair(StringRef(), QualType()) // __context with shared vars
1180 };
1181 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1182 Params);
1183 break;
1184 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001185 case OMPD_teams: {
1186 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1187 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1188 Sema::CapturedParamNameType Params[] = {
1189 std::make_pair(".global_tid.", KmpInt32PtrTy),
1190 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1191 std::make_pair(StringRef(), QualType()) // __context with shared vars
1192 };
1193 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1194 Params);
1195 break;
1196 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001197 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001198 case OMPD_taskyield:
1199 case OMPD_barrier:
1200 case OMPD_taskwait:
1201 case OMPD_flush:
Alexey Bataev9959db52014-05-06 10:08:46 +00001202 llvm_unreachable("OpenMP Directive is not allowed");
1203 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001204 llvm_unreachable("Unknown OpenMP directive");
1205 }
1206}
1207
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001208StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1209 ArrayRef<OMPClause *> Clauses) {
1210 if (!S.isUsable()) {
1211 ActOnCapturedRegionError();
1212 return StmtError();
1213 }
1214 // Mark all variables in private list clauses as used in inner region. This is
1215 // required for proper codegen.
1216 for (auto *Clause : Clauses) {
1217 if (isOpenMPPrivate(Clause->getClauseKind())) {
1218 for (auto *VarRef : Clause->children()) {
1219 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001220 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001221 }
1222 }
1223 }
1224 }
1225 return ActOnCapturedRegionEnd(S.get());
1226}
1227
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001228static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1229 OpenMPDirectiveKind CurrentRegion,
1230 const DeclarationNameInfo &CurrentName,
1231 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001232 // Allowed nesting of constructs
1233 // +------------------+-----------------+------------------------------------+
1234 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1235 // +------------------+-----------------+------------------------------------+
1236 // | parallel | parallel | * |
1237 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001238 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001239 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001240 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001241 // | parallel | simd | * |
1242 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001243 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001244 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001245 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001246 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001247 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001248 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001249 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001250 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001251 // | parallel | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001252 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001253 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001254 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001255 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001256 // | parallel | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001257 // +------------------+-----------------+------------------------------------+
1258 // | for | parallel | * |
1259 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001260 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001261 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001262 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001263 // | for | simd | * |
1264 // | for | sections | + |
1265 // | for | section | + |
1266 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001267 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001268 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001269 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001270 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001271 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001272 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001273 // | for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001274 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001275 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001276 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001277 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001278 // | for | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001279 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001280 // | master | parallel | * |
1281 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001282 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001283 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001284 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001285 // | master | simd | * |
1286 // | master | sections | + |
1287 // | master | section | + |
1288 // | master | single | + |
1289 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001290 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001291 // | master |parallel sections| * |
1292 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001293 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001294 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001295 // | master | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001296 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001297 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001298 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001299 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001300 // | master | teams | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001301 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001302 // | critical | parallel | * |
1303 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001304 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001305 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001306 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001307 // | critical | simd | * |
1308 // | critical | sections | + |
1309 // | critical | section | + |
1310 // | critical | single | + |
1311 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001312 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001313 // | critical |parallel sections| * |
1314 // | critical | task | * |
1315 // | critical | taskyield | * |
1316 // | critical | barrier | + |
1317 // | critical | taskwait | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001318 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001319 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001320 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001321 // | critical | teams | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001322 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001323 // | simd | parallel | |
1324 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001325 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001326 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001327 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001328 // | simd | simd | |
1329 // | simd | sections | |
1330 // | simd | section | |
1331 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001332 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001333 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001334 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001335 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001336 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001337 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001338 // | simd | taskwait | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001339 // | simd | flush | |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001340 // | simd | ordered | |
Alexey Bataev0162e452014-07-22 10:10:35 +00001341 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001342 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001343 // | simd | teams | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001344 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001345 // | for simd | parallel | |
1346 // | for simd | for | |
1347 // | for simd | for simd | |
1348 // | for simd | master | |
1349 // | for simd | critical | |
1350 // | for simd | simd | |
1351 // | for simd | sections | |
1352 // | for simd | section | |
1353 // | for simd | single | |
1354 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001355 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001356 // | for simd |parallel sections| |
1357 // | for simd | task | |
1358 // | for simd | taskyield | |
1359 // | for simd | barrier | |
1360 // | for simd | taskwait | |
1361 // | for simd | flush | |
1362 // | for simd | ordered | |
1363 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001364 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001365 // | for simd | teams | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001366 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001367 // | parallel for simd| parallel | |
1368 // | parallel for simd| for | |
1369 // | parallel for simd| for simd | |
1370 // | parallel for simd| master | |
1371 // | parallel for simd| critical | |
1372 // | parallel for simd| simd | |
1373 // | parallel for simd| sections | |
1374 // | parallel for simd| section | |
1375 // | parallel for simd| single | |
1376 // | parallel for simd| parallel for | |
1377 // | parallel for simd|parallel for simd| |
1378 // | parallel for simd|parallel sections| |
1379 // | parallel for simd| task | |
1380 // | parallel for simd| taskyield | |
1381 // | parallel for simd| barrier | |
1382 // | parallel for simd| taskwait | |
1383 // | parallel for simd| flush | |
1384 // | parallel for simd| ordered | |
1385 // | parallel for simd| atomic | |
1386 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001387 // | parallel for simd| teams | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001388 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001389 // | sections | parallel | * |
1390 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001391 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001392 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001393 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001394 // | sections | simd | * |
1395 // | sections | sections | + |
1396 // | sections | section | * |
1397 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001398 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001399 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001400 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001401 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001402 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001403 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001404 // | sections | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001405 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001406 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001407 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001408 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001409 // | sections | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001410 // +------------------+-----------------+------------------------------------+
1411 // | section | parallel | * |
1412 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001413 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001414 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001415 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001416 // | section | simd | * |
1417 // | section | sections | + |
1418 // | section | section | + |
1419 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001420 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001421 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001422 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001423 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001424 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001425 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001426 // | section | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001427 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001428 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001429 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001430 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001431 // | section | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001432 // +------------------+-----------------+------------------------------------+
1433 // | single | parallel | * |
1434 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001435 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001436 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001437 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001438 // | single | simd | * |
1439 // | single | sections | + |
1440 // | single | section | + |
1441 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001442 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001443 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001444 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001445 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001446 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001447 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001448 // | single | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001449 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001450 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001451 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001452 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001453 // | single | teams | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001454 // +------------------+-----------------+------------------------------------+
1455 // | parallel for | parallel | * |
1456 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001457 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001458 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001459 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001460 // | parallel for | simd | * |
1461 // | parallel for | sections | + |
1462 // | parallel for | section | + |
1463 // | parallel for | single | + |
1464 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001465 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001466 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001467 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001468 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001469 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001470 // | parallel for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001471 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001472 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001473 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001474 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001475 // | parallel for | teams | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001476 // +------------------+-----------------+------------------------------------+
1477 // | parallel sections| parallel | * |
1478 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001479 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001480 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001481 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001482 // | parallel sections| simd | * |
1483 // | parallel sections| sections | + |
1484 // | parallel sections| section | * |
1485 // | parallel sections| single | + |
1486 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001487 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001488 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001489 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001490 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001491 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001492 // | parallel sections| taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001493 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001494 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001495 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001496 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001497 // | parallel sections| teams | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001498 // +------------------+-----------------+------------------------------------+
1499 // | task | parallel | * |
1500 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001501 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001502 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001503 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001504 // | task | simd | * |
1505 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001506 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001507 // | task | single | + |
1508 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001509 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001510 // | task |parallel sections| * |
1511 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001512 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001513 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001514 // | task | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001515 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001516 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001517 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001518 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001519 // | task | teams | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001520 // +------------------+-----------------+------------------------------------+
1521 // | ordered | parallel | * |
1522 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001523 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001524 // | ordered | master | * |
1525 // | ordered | critical | * |
1526 // | ordered | simd | * |
1527 // | ordered | sections | + |
1528 // | ordered | section | + |
1529 // | ordered | single | + |
1530 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001531 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001532 // | ordered |parallel sections| * |
1533 // | ordered | task | * |
1534 // | ordered | taskyield | * |
1535 // | ordered | barrier | + |
1536 // | ordered | taskwait | * |
1537 // | ordered | flush | * |
1538 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001539 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001540 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001541 // | ordered | teams | + |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001542 // +------------------+-----------------+------------------------------------+
1543 // | atomic | parallel | |
1544 // | atomic | for | |
1545 // | atomic | for simd | |
1546 // | atomic | master | |
1547 // | atomic | critical | |
1548 // | atomic | simd | |
1549 // | atomic | sections | |
1550 // | atomic | section | |
1551 // | atomic | single | |
1552 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001553 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001554 // | atomic |parallel sections| |
1555 // | atomic | task | |
1556 // | atomic | taskyield | |
1557 // | atomic | barrier | |
1558 // | atomic | taskwait | |
1559 // | atomic | flush | |
1560 // | atomic | ordered | |
1561 // | atomic | atomic | |
1562 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001563 // | atomic | teams | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001564 // +------------------+-----------------+------------------------------------+
1565 // | target | parallel | * |
1566 // | target | for | * |
1567 // | target | for simd | * |
1568 // | target | master | * |
1569 // | target | critical | * |
1570 // | target | simd | * |
1571 // | target | sections | * |
1572 // | target | section | * |
1573 // | target | single | * |
1574 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001575 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001576 // | target |parallel sections| * |
1577 // | target | task | * |
1578 // | target | taskyield | * |
1579 // | target | barrier | * |
1580 // | target | taskwait | * |
1581 // | target | flush | * |
1582 // | target | ordered | * |
1583 // | target | atomic | * |
1584 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001585 // | target | teams | * |
1586 // +------------------+-----------------+------------------------------------+
1587 // | teams | parallel | * |
1588 // | teams | for | + |
1589 // | teams | for simd | + |
1590 // | teams | master | + |
1591 // | teams | critical | + |
1592 // | teams | simd | + |
1593 // | teams | sections | + |
1594 // | teams | section | + |
1595 // | teams | single | + |
1596 // | teams | parallel for | * |
1597 // | teams |parallel for simd| * |
1598 // | teams |parallel sections| * |
1599 // | teams | task | + |
1600 // | teams | taskyield | + |
1601 // | teams | barrier | + |
1602 // | teams | taskwait | + |
1603 // | teams | flush | + |
1604 // | teams | ordered | + |
1605 // | teams | atomic | + |
1606 // | teams | target | + |
1607 // | teams | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001608 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00001609 if (Stack->getCurScope()) {
1610 auto ParentRegion = Stack->getParentDirective();
1611 bool NestingProhibited = false;
1612 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001613 enum {
1614 NoRecommend,
1615 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001616 ShouldBeInOrderedRegion,
1617 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001618 } Recommend = NoRecommend;
Alexey Bataev549210e2014-06-24 04:39:47 +00001619 if (isOpenMPSimdDirective(ParentRegion)) {
1620 // OpenMP [2.16, Nesting of Regions]
1621 // OpenMP constructs may not be nested inside a simd region.
1622 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1623 return true;
1624 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001625 if (ParentRegion == OMPD_atomic) {
1626 // OpenMP [2.16, Nesting of Regions]
1627 // OpenMP constructs may not be nested inside an atomic region.
1628 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1629 return true;
1630 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001631 if (CurrentRegion == OMPD_section) {
1632 // OpenMP [2.7.2, sections Construct, Restrictions]
1633 // Orphaned section directives are prohibited. That is, the section
1634 // directives must appear within the sections construct and must not be
1635 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001636 if (ParentRegion != OMPD_sections &&
1637 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001638 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1639 << (ParentRegion != OMPD_unknown)
1640 << getOpenMPDirectiveName(ParentRegion);
1641 return true;
1642 }
1643 return false;
1644 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001645 // Allow some constructs to be orphaned (they could be used in functions,
1646 // called from OpenMP regions with the required preconditions).
1647 if (ParentRegion == OMPD_unknown)
1648 return false;
Alexander Musman80c22892014-07-17 08:54:58 +00001649 if (CurrentRegion == OMPD_master) {
1650 // OpenMP [2.16, Nesting of Regions]
1651 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001652 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001653 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1654 ParentRegion == OMPD_task;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001655 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1656 // OpenMP [2.16, Nesting of Regions]
1657 // A critical region may not be nested (closely or otherwise) inside a
1658 // critical region with the same name. Note that this restriction is not
1659 // sufficient to prevent deadlock.
1660 SourceLocation PreviousCriticalLoc;
1661 bool DeadLock =
1662 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1663 OpenMPDirectiveKind K,
1664 const DeclarationNameInfo &DNI,
1665 SourceLocation Loc)
1666 ->bool {
1667 if (K == OMPD_critical &&
1668 DNI.getName() == CurrentName.getName()) {
1669 PreviousCriticalLoc = Loc;
1670 return true;
1671 } else
1672 return false;
1673 },
1674 false /* skip top directive */);
1675 if (DeadLock) {
1676 SemaRef.Diag(StartLoc,
1677 diag::err_omp_prohibited_region_critical_same_name)
1678 << CurrentName.getName();
1679 if (PreviousCriticalLoc.isValid())
1680 SemaRef.Diag(PreviousCriticalLoc,
1681 diag::note_omp_previous_critical_region);
1682 return true;
1683 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001684 } else if (CurrentRegion == OMPD_barrier) {
1685 // OpenMP [2.16, Nesting of Regions]
1686 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001687 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001688 NestingProhibited =
1689 isOpenMPWorksharingDirective(ParentRegion) ||
1690 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1691 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001692 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00001693 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001694 // OpenMP [2.16, Nesting of Regions]
1695 // A worksharing region may not be closely nested inside a worksharing,
1696 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001697 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00001698 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001699 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1700 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1701 Recommend = ShouldBeInParallelRegion;
1702 } else if (CurrentRegion == OMPD_ordered) {
1703 // OpenMP [2.16, Nesting of Regions]
1704 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00001705 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001706 // An ordered region must be closely nested inside a loop region (or
1707 // parallel loop region) with an ordered clause.
1708 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00001709 ParentRegion == OMPD_task ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001710 !Stack->isParentOrderedRegion();
1711 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001712 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1713 // OpenMP [2.16, Nesting of Regions]
1714 // If specified, a teams construct must be contained within a target
1715 // construct.
1716 NestingProhibited = ParentRegion != OMPD_target;
1717 Recommend = ShouldBeInTargetRegion;
1718 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1719 }
1720 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1721 // OpenMP [2.16, Nesting of Regions]
1722 // distribute, parallel, parallel sections, parallel workshare, and the
1723 // parallel loop and parallel loop SIMD constructs are the only OpenMP
1724 // constructs that can be closely nested in the teams region.
1725 // TODO: add distribute directive.
1726 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1727 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001728 }
1729 if (NestingProhibited) {
1730 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001731 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1732 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00001733 return true;
1734 }
1735 }
1736 return false;
1737}
1738
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001739StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001740 const DeclarationNameInfo &DirName,
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001741 ArrayRef<OMPClause *> Clauses,
1742 Stmt *AStmt,
1743 SourceLocation StartLoc,
1744 SourceLocation EndLoc) {
1745 StmtResult Res = StmtError();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001746 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00001747 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001748
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001749 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00001750 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001751 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00001752 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00001753 if (AStmt) {
1754 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1755
1756 // Check default data sharing attributes for referenced variables.
1757 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1758 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1759 if (DSAChecker.isErrorFound())
1760 return StmtError();
1761 // Generate list of implicitly defined firstprivate variables.
1762 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00001763
1764 if (!DSAChecker.getImplicitFirstprivate().empty()) {
1765 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1766 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1767 SourceLocation(), SourceLocation())) {
1768 ClausesWithImplicit.push_back(Implicit);
1769 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1770 DSAChecker.getImplicitFirstprivate().size();
1771 } else
1772 ErrorFound = true;
1773 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001774 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001775
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001776 switch (Kind) {
1777 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00001778 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1779 EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001780 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001781 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001782 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1783 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001784 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00001785 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001786 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1787 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001788 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00001789 case OMPD_for_simd:
1790 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
1791 EndLoc, VarsWithInheritedDSA);
1792 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001793 case OMPD_sections:
1794 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1795 EndLoc);
1796 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001797 case OMPD_section:
1798 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00001799 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001800 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1801 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001802 case OMPD_single:
1803 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1804 EndLoc);
1805 break;
Alexander Musman80c22892014-07-17 08:54:58 +00001806 case OMPD_master:
1807 assert(ClausesWithImplicit.empty() &&
1808 "No clauses are allowed for 'omp master' directive");
1809 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1810 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001811 case OMPD_critical:
1812 assert(ClausesWithImplicit.empty() &&
1813 "No clauses are allowed for 'omp critical' directive");
1814 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1815 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001816 case OMPD_parallel_for:
1817 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1818 EndLoc, VarsWithInheritedDSA);
1819 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00001820 case OMPD_parallel_for_simd:
1821 Res = ActOnOpenMPParallelForSimdDirective(
1822 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
1823 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001824 case OMPD_parallel_sections:
1825 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1826 StartLoc, EndLoc);
1827 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001828 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001829 Res =
1830 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1831 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00001832 case OMPD_taskyield:
1833 assert(ClausesWithImplicit.empty() &&
1834 "No clauses are allowed for 'omp taskyield' directive");
1835 assert(AStmt == nullptr &&
1836 "No associated statement allowed for 'omp taskyield' directive");
1837 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1838 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001839 case OMPD_barrier:
1840 assert(ClausesWithImplicit.empty() &&
1841 "No clauses are allowed for 'omp barrier' directive");
1842 assert(AStmt == nullptr &&
1843 "No associated statement allowed for 'omp barrier' directive");
1844 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1845 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00001846 case OMPD_taskwait:
1847 assert(ClausesWithImplicit.empty() &&
1848 "No clauses are allowed for 'omp taskwait' directive");
1849 assert(AStmt == nullptr &&
1850 "No associated statement allowed for 'omp taskwait' directive");
1851 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1852 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00001853 case OMPD_flush:
1854 assert(AStmt == nullptr &&
1855 "No associated statement allowed for 'omp flush' directive");
1856 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
1857 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001858 case OMPD_ordered:
1859 assert(ClausesWithImplicit.empty() &&
1860 "No clauses are allowed for 'omp ordered' directive");
1861 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
1862 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00001863 case OMPD_atomic:
1864 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
1865 EndLoc);
1866 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001867 case OMPD_teams:
1868 Res =
1869 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1870 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001871 case OMPD_target:
1872 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
1873 EndLoc);
1874 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001875 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001876 llvm_unreachable("OpenMP Directive is not allowed");
1877 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001878 llvm_unreachable("Unknown OpenMP directive");
1879 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001880
Alexey Bataev4acb8592014-07-07 13:01:15 +00001881 for (auto P : VarsWithInheritedDSA) {
1882 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1883 << P.first << P.second->getSourceRange();
1884 }
1885 if (!VarsWithInheritedDSA.empty())
1886 return StmtError();
1887
Alexey Bataeved09d242014-05-28 05:53:51 +00001888 if (ErrorFound)
1889 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001890 return Res;
1891}
1892
1893StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
1894 Stmt *AStmt,
1895 SourceLocation StartLoc,
1896 SourceLocation EndLoc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001897 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
1898 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
1899 // 1.2.2 OpenMP Language Terminology
1900 // Structured block - An executable statement with a single entry at the
1901 // top and a single exit at the bottom.
1902 // The point of exit cannot be a branch out of the structured block.
1903 // longjmp() and throw() must not violate the entry/exit criteria.
1904 CS->getCapturedDecl()->setNothrow();
1905
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001906 getCurFunction()->setHasBranchProtectedScope();
1907
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001908 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
1909 AStmt);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001910}
1911
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001912namespace {
1913/// \brief Helper class for checking canonical form of the OpenMP loops and
1914/// extracting iteration space of each loop in the loop nest, that will be used
1915/// for IR generation.
1916class OpenMPIterationSpaceChecker {
1917 /// \brief Reference to Sema.
1918 Sema &SemaRef;
1919 /// \brief A location for diagnostics (when there is no some better location).
1920 SourceLocation DefaultLoc;
1921 /// \brief A location for diagnostics (when increment is not compatible).
1922 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001923 /// \brief A source location for referring to loop init later.
1924 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001925 /// \brief A source location for referring to condition later.
1926 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001927 /// \brief A source location for referring to increment later.
1928 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001929 /// \brief Loop variable.
1930 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001931 /// \brief Reference to loop variable.
1932 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001933 /// \brief Lower bound (initializer for the var).
1934 Expr *LB;
1935 /// \brief Upper bound.
1936 Expr *UB;
1937 /// \brief Loop step (increment).
1938 Expr *Step;
1939 /// \brief This flag is true when condition is one of:
1940 /// Var < UB
1941 /// Var <= UB
1942 /// UB > Var
1943 /// UB >= Var
1944 bool TestIsLessOp;
1945 /// \brief This flag is true when condition is strict ( < or > ).
1946 bool TestIsStrictOp;
1947 /// \brief This flag is true when step is subtracted on each iteration.
1948 bool SubtractStep;
1949
1950public:
1951 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
1952 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00001953 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
1954 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001955 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
1956 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001957 /// \brief Check init-expr for canonical loop form and save loop counter
1958 /// variable - #Var and its initialization value - #LB.
1959 bool CheckInit(Stmt *S);
1960 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
1961 /// for less/greater and for strict/non-strict comparison.
1962 bool CheckCond(Expr *S);
1963 /// \brief Check incr-expr for canonical loop form and return true if it
1964 /// does not conform, otherwise save loop step (#Step).
1965 bool CheckInc(Expr *S);
1966 /// \brief Return the loop counter variable.
1967 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001968 /// \brief Return the reference expression to loop counter variable.
1969 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001970 /// \brief Source range of the loop init.
1971 SourceRange GetInitSrcRange() const { return InitSrcRange; }
1972 /// \brief Source range of the loop condition.
1973 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
1974 /// \brief Source range of the loop increment.
1975 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
1976 /// \brief True if the step should be subtracted.
1977 bool ShouldSubtractStep() const { return SubtractStep; }
1978 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00001979 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00001980 /// \brief Build the precondition expression for the loops.
1981 Expr *BuildPreCond(Scope *S, Expr *Cond) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001982 /// \brief Build reference expression to the counter be used for codegen.
1983 Expr *BuildCounterVar() const;
1984 /// \brief Build initization of the counter be used for codegen.
1985 Expr *BuildCounterInit() const;
1986 /// \brief Build step of the counter be used for codegen.
1987 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001988 /// \brief Return true if any expression is dependent.
1989 bool Dependent() const;
1990
1991private:
1992 /// \brief Check the right-hand side of an assignment in the increment
1993 /// expression.
1994 bool CheckIncRHS(Expr *RHS);
1995 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001996 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001997 /// \brief Helper to set upper bound.
1998 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
1999 const SourceLocation &SL);
2000 /// \brief Helper to set loop increment.
2001 bool SetStep(Expr *NewStep, bool Subtract);
2002};
2003
2004bool OpenMPIterationSpaceChecker::Dependent() const {
2005 if (!Var) {
2006 assert(!LB && !UB && !Step);
2007 return false;
2008 }
2009 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2010 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2011}
2012
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002013bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2014 DeclRefExpr *NewVarRefExpr,
2015 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002016 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002017 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2018 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002019 if (!NewVar || !NewLB)
2020 return true;
2021 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002022 VarRef = NewVarRefExpr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002023 LB = NewLB;
2024 return false;
2025}
2026
2027bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2028 const SourceRange &SR,
2029 const SourceLocation &SL) {
2030 // State consistency checking to ensure correct usage.
2031 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2032 !TestIsLessOp && !TestIsStrictOp);
2033 if (!NewUB)
2034 return true;
2035 UB = NewUB;
2036 TestIsLessOp = LessOp;
2037 TestIsStrictOp = StrictOp;
2038 ConditionSrcRange = SR;
2039 ConditionLoc = SL;
2040 return false;
2041}
2042
2043bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2044 // State consistency checking to ensure correct usage.
2045 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2046 if (!NewStep)
2047 return true;
2048 if (!NewStep->isValueDependent()) {
2049 // Check that the step is integer expression.
2050 SourceLocation StepLoc = NewStep->getLocStart();
2051 ExprResult Val =
2052 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2053 if (Val.isInvalid())
2054 return true;
2055 NewStep = Val.get();
2056
2057 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2058 // If test-expr is of form var relational-op b and relational-op is < or
2059 // <= then incr-expr must cause var to increase on each iteration of the
2060 // loop. If test-expr is of form var relational-op b and relational-op is
2061 // > or >= then incr-expr must cause var to decrease on each iteration of
2062 // the loop.
2063 // If test-expr is of form b relational-op var and relational-op is < or
2064 // <= then incr-expr must cause var to decrease on each iteration of the
2065 // loop. If test-expr is of form b relational-op var and relational-op is
2066 // > or >= then incr-expr must cause var to increase on each iteration of
2067 // the loop.
2068 llvm::APSInt Result;
2069 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2070 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2071 bool IsConstNeg =
2072 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002073 bool IsConstPos =
2074 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002075 bool IsConstZero = IsConstant && !Result.getBoolValue();
2076 if (UB && (IsConstZero ||
2077 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002078 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002079 SemaRef.Diag(NewStep->getExprLoc(),
2080 diag::err_omp_loop_incr_not_compatible)
2081 << Var << TestIsLessOp << NewStep->getSourceRange();
2082 SemaRef.Diag(ConditionLoc,
2083 diag::note_omp_loop_cond_requres_compatible_incr)
2084 << TestIsLessOp << ConditionSrcRange;
2085 return true;
2086 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002087 if (TestIsLessOp == Subtract) {
2088 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2089 NewStep).get();
2090 Subtract = !Subtract;
2091 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002092 }
2093
2094 Step = NewStep;
2095 SubtractStep = Subtract;
2096 return false;
2097}
2098
2099bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S) {
2100 // Check init-expr for canonical loop form and save loop counter
2101 // variable - #Var and its initialization value - #LB.
2102 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2103 // var = lb
2104 // integer-type var = lb
2105 // random-access-iterator-type var = lb
2106 // pointer-type var = lb
2107 //
2108 if (!S) {
2109 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2110 return true;
2111 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002112 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002113 if (Expr *E = dyn_cast<Expr>(S))
2114 S = E->IgnoreParens();
2115 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2116 if (BO->getOpcode() == BO_Assign)
2117 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002118 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002119 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002120 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2121 if (DS->isSingleDecl()) {
2122 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2123 if (Var->hasInit()) {
2124 // Accept non-canonical init form here but emit ext. warning.
2125 if (Var->getInitStyle() != VarDecl::CInit)
2126 SemaRef.Diag(S->getLocStart(),
2127 diag::ext_omp_loop_not_canonical_init)
2128 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002129 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002130 }
2131 }
2132 }
2133 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2134 if (CE->getOperator() == OO_Equal)
2135 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002136 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2137 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002138
2139 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2140 << S->getSourceRange();
2141 return true;
2142}
2143
Alexey Bataev23b69422014-06-18 07:08:49 +00002144/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002145/// variable (which may be the loop variable) if possible.
2146static const VarDecl *GetInitVarDecl(const Expr *E) {
2147 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002148 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002149 E = E->IgnoreParenImpCasts();
2150 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2151 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2152 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
2153 CE->getArg(0) != nullptr)
2154 E = CE->getArg(0)->IgnoreParenImpCasts();
2155 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2156 if (!DRE)
2157 return nullptr;
2158 return dyn_cast<VarDecl>(DRE->getDecl());
2159}
2160
2161bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2162 // Check test-expr for canonical form, save upper-bound UB, flags for
2163 // less/greater and for strict/non-strict comparison.
2164 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2165 // var relational-op b
2166 // b relational-op var
2167 //
2168 if (!S) {
2169 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2170 return true;
2171 }
2172 S = S->IgnoreParenImpCasts();
2173 SourceLocation CondLoc = S->getLocStart();
2174 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2175 if (BO->isRelationalOp()) {
2176 if (GetInitVarDecl(BO->getLHS()) == Var)
2177 return SetUB(BO->getRHS(),
2178 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2179 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2180 BO->getSourceRange(), BO->getOperatorLoc());
2181 if (GetInitVarDecl(BO->getRHS()) == Var)
2182 return SetUB(BO->getLHS(),
2183 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2184 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2185 BO->getSourceRange(), BO->getOperatorLoc());
2186 }
2187 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2188 if (CE->getNumArgs() == 2) {
2189 auto Op = CE->getOperator();
2190 switch (Op) {
2191 case OO_Greater:
2192 case OO_GreaterEqual:
2193 case OO_Less:
2194 case OO_LessEqual:
2195 if (GetInitVarDecl(CE->getArg(0)) == Var)
2196 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2197 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2198 CE->getOperatorLoc());
2199 if (GetInitVarDecl(CE->getArg(1)) == Var)
2200 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2201 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2202 CE->getOperatorLoc());
2203 break;
2204 default:
2205 break;
2206 }
2207 }
2208 }
2209 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2210 << S->getSourceRange() << Var;
2211 return true;
2212}
2213
2214bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2215 // RHS of canonical loop form increment can be:
2216 // var + incr
2217 // incr + var
2218 // var - incr
2219 //
2220 RHS = RHS->IgnoreParenImpCasts();
2221 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2222 if (BO->isAdditiveOp()) {
2223 bool IsAdd = BO->getOpcode() == BO_Add;
2224 if (GetInitVarDecl(BO->getLHS()) == Var)
2225 return SetStep(BO->getRHS(), !IsAdd);
2226 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2227 return SetStep(BO->getLHS(), false);
2228 }
2229 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2230 bool IsAdd = CE->getOperator() == OO_Plus;
2231 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2232 if (GetInitVarDecl(CE->getArg(0)) == Var)
2233 return SetStep(CE->getArg(1), !IsAdd);
2234 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2235 return SetStep(CE->getArg(0), false);
2236 }
2237 }
2238 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2239 << RHS->getSourceRange() << Var;
2240 return true;
2241}
2242
2243bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2244 // Check incr-expr for canonical loop form and return true if it
2245 // does not conform.
2246 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2247 // ++var
2248 // var++
2249 // --var
2250 // var--
2251 // var += incr
2252 // var -= incr
2253 // var = var + incr
2254 // var = incr + var
2255 // var = var - incr
2256 //
2257 if (!S) {
2258 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2259 return true;
2260 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002261 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002262 S = S->IgnoreParens();
2263 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2264 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2265 return SetStep(
2266 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2267 (UO->isDecrementOp() ? -1 : 1)).get(),
2268 false);
2269 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2270 switch (BO->getOpcode()) {
2271 case BO_AddAssign:
2272 case BO_SubAssign:
2273 if (GetInitVarDecl(BO->getLHS()) == Var)
2274 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2275 break;
2276 case BO_Assign:
2277 if (GetInitVarDecl(BO->getLHS()) == Var)
2278 return CheckIncRHS(BO->getRHS());
2279 break;
2280 default:
2281 break;
2282 }
2283 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2284 switch (CE->getOperator()) {
2285 case OO_PlusPlus:
2286 case OO_MinusMinus:
2287 if (GetInitVarDecl(CE->getArg(0)) == Var)
2288 return SetStep(
2289 SemaRef.ActOnIntegerConstant(
2290 CE->getLocStart(),
2291 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2292 false);
2293 break;
2294 case OO_PlusEqual:
2295 case OO_MinusEqual:
2296 if (GetInitVarDecl(CE->getArg(0)) == Var)
2297 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2298 break;
2299 case OO_Equal:
2300 if (GetInitVarDecl(CE->getArg(0)) == Var)
2301 return CheckIncRHS(CE->getArg(1));
2302 break;
2303 default:
2304 break;
2305 }
2306 }
2307 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2308 << S->getSourceRange() << Var;
2309 return true;
2310}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002311
2312/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002313Expr *
2314OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2315 const bool LimitedType) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002316 ExprResult Diff;
2317 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2318 SemaRef.getLangOpts().CPlusPlus) {
2319 // Upper - Lower
2320 Expr *Upper = TestIsLessOp ? UB : LB;
2321 Expr *Lower = TestIsLessOp ? LB : UB;
2322
2323 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2324
2325 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2326 // BuildBinOp already emitted error, this one is to point user to upper
2327 // and lower bound, and to tell what is passed to 'operator-'.
2328 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2329 << Upper->getSourceRange() << Lower->getSourceRange();
2330 return nullptr;
2331 }
2332 }
2333
2334 if (!Diff.isUsable())
2335 return nullptr;
2336
2337 // Upper - Lower [- 1]
2338 if (TestIsStrictOp)
2339 Diff = SemaRef.BuildBinOp(
2340 S, DefaultLoc, BO_Sub, Diff.get(),
2341 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2342 if (!Diff.isUsable())
2343 return nullptr;
2344
2345 // Upper - Lower [- 1] + Step
2346 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2347 Step->IgnoreImplicit());
2348 if (!Diff.isUsable())
2349 return nullptr;
2350
2351 // Parentheses (for dumping/debugging purposes only).
2352 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2353 if (!Diff.isUsable())
2354 return nullptr;
2355
2356 // (Upper - Lower [- 1] + Step) / Step
2357 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2358 Step->IgnoreImplicit());
2359 if (!Diff.isUsable())
2360 return nullptr;
2361
Alexander Musman174b3ca2014-10-06 11:16:29 +00002362 // OpenMP runtime requires 32-bit or 64-bit loop variables.
2363 if (LimitedType) {
2364 auto &C = SemaRef.Context;
2365 QualType Type = Diff.get()->getType();
2366 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2367 if (NewSize != C.getTypeSize(Type)) {
2368 if (NewSize < C.getTypeSize(Type)) {
2369 assert(NewSize == 64 && "incorrect loop var size");
2370 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2371 << InitSrcRange << ConditionSrcRange;
2372 }
2373 QualType NewType = C.getIntTypeForBitwidth(
2374 NewSize, Type->hasSignedIntegerRepresentation());
2375 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2376 Sema::AA_Converting, true);
2377 if (!Diff.isUsable())
2378 return nullptr;
2379 }
2380 }
2381
Alexander Musmana5f070a2014-10-01 06:03:56 +00002382 return Diff.get();
2383}
2384
Alexey Bataev62dbb972015-04-22 11:59:37 +00002385Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
2386 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
2387 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
2388 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
2389 auto CondExpr = SemaRef.BuildBinOp(
2390 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
2391 : (TestIsStrictOp ? BO_GT : BO_GE),
2392 LB, UB);
2393 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
2394 // Otherwise use original loop conditon and evaluate it in runtime.
2395 return CondExpr.isUsable() ? CondExpr.get() : Cond;
2396}
2397
Alexander Musmana5f070a2014-10-01 06:03:56 +00002398/// \brief Build reference expression to the counter be used for codegen.
2399Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
2400 return DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2401 GetIncrementSrcRange().getBegin(), Var, false,
2402 DefaultLoc, Var->getType(), VK_LValue);
2403}
2404
2405/// \brief Build initization of the counter be used for codegen.
2406Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2407
2408/// \brief Build step of the counter be used for codegen.
2409Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2410
2411/// \brief Iteration space of a single for loop.
2412struct LoopIterationSpace {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002413 /// \brief Condition of the loop.
2414 Expr *PreCond;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002415 /// \brief This expression calculates the number of iterations in the loop.
2416 /// It is always possible to calculate it before starting the loop.
2417 Expr *NumIterations;
2418 /// \brief The loop counter variable.
2419 Expr *CounterVar;
2420 /// \brief This is initializer for the initial value of #CounterVar.
2421 Expr *CounterInit;
2422 /// \brief This is step for the #CounterVar used to generate its update:
2423 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2424 Expr *CounterStep;
2425 /// \brief Should step be subtracted?
2426 bool Subtract;
2427 /// \brief Source range of the loop init.
2428 SourceRange InitSrcRange;
2429 /// \brief Source range of the loop condition.
2430 SourceRange CondSrcRange;
2431 /// \brief Source range of the loop increment.
2432 SourceRange IncSrcRange;
2433};
2434
Alexey Bataev23b69422014-06-18 07:08:49 +00002435} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002436
2437/// \brief Called on a for stmt to check and extract its iteration space
2438/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00002439static bool CheckOpenMPIterationSpace(
2440 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2441 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2442 Expr *NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002443 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2444 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002445 // OpenMP [2.6, Canonical Loop Form]
2446 // for (init-expr; test-expr; incr-expr) structured-block
2447 auto For = dyn_cast_or_null<ForStmt>(S);
2448 if (!For) {
2449 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002450 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2451 << NestedLoopCount << (CurrentNestedLoopCount > 0)
2452 << CurrentNestedLoopCount;
2453 if (NestedLoopCount > 1)
2454 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2455 diag::note_omp_collapse_expr)
2456 << NestedLoopCountExpr->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002457 return true;
2458 }
2459 assert(For->getBody());
2460
2461 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2462
2463 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002464 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002465 if (ISC.CheckInit(Init)) {
2466 return true;
2467 }
2468
2469 bool HasErrors = false;
2470
2471 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002472 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002473
2474 // OpenMP [2.6, Canonical Loop Form]
2475 // Var is one of the following:
2476 // A variable of signed or unsigned integer type.
2477 // For C++, a variable of a random access iterator type.
2478 // For C, a variable of a pointer type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002479 auto VarType = Var->getType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002480 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2481 !VarType->isPointerType() &&
2482 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2483 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2484 << SemaRef.getLangOpts().CPlusPlus;
2485 HasErrors = true;
2486 }
2487
Alexey Bataev4acb8592014-07-07 13:01:15 +00002488 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2489 // Construct
2490 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2491 // parallel for construct is (are) private.
2492 // The loop iteration variable in the associated for-loop of a simd construct
2493 // with just one associated for-loop is linear with a constant-linear-step
2494 // that is the increment of the associated for-loop.
2495 // Exclude loop var from the list of variables with implicitly defined data
2496 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00002497 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002498
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002499 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2500 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00002501 // The loop iteration variable in the associated for-loop of a simd construct
2502 // with just one associated for-loop may be listed in a linear clause with a
2503 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00002504 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2505 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002506 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002507 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2508 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2509 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002510 auto PredeterminedCKind =
2511 isOpenMPSimdDirective(DKind)
2512 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2513 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002514 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002515 DVar.CKind != PredeterminedCKind) ||
Alexander Musmanf82886e2014-09-18 05:12:34 +00002516 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2517 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
2518 DVar.CKind != OMPC_lastprivate)) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00002519 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002520 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00002521 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2522 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002523 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002524 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002525 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002526 // Make the loop iteration variable private (for worksharing constructs),
2527 // linear (for simd directives with the only one associated loop) or
2528 // lastprivate (for simd directives with several collapsed loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00002529 // FIXME: the next check and error message must be removed once the
2530 // capturing of global variables in loops is fixed.
2531 if (DVar.CKind == OMPC_unknown)
2532 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2533 /*FromParent=*/false);
2534 if (!Var->hasLocalStorage() && DVar.CKind == OMPC_unknown) {
2535 SemaRef.Diag(Init->getLocStart(), diag::err_omp_global_loop_var_dsa)
2536 << getOpenMPClauseName(PredeterminedCKind)
2537 << getOpenMPDirectiveName(DKind);
2538 HasErrors = true;
2539 } else
2540 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002541 }
2542
Alexey Bataev7ff55242014-06-19 09:13:45 +00002543 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00002544
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002545 // Check test-expr.
2546 HasErrors |= ISC.CheckCond(For->getCond());
2547
2548 // Check incr-expr.
2549 HasErrors |= ISC.CheckInc(For->getInc());
2550
Alexander Musmana5f070a2014-10-01 06:03:56 +00002551 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002552 return HasErrors;
2553
Alexander Musmana5f070a2014-10-01 06:03:56 +00002554 // Build the loop's iteration space representation.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002555 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
Alexander Musman174b3ca2014-10-06 11:16:29 +00002556 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2557 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
Alexander Musmana5f070a2014-10-01 06:03:56 +00002558 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2559 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2560 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2561 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2562 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2563 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2564 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2565
Alexey Bataev62dbb972015-04-22 11:59:37 +00002566 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
2567 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00002568 ResultIterSpace.CounterVar == nullptr ||
2569 ResultIterSpace.CounterInit == nullptr ||
2570 ResultIterSpace.CounterStep == nullptr);
2571
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002572 return HasErrors;
2573}
2574
Alexander Musmana5f070a2014-10-01 06:03:56 +00002575/// \brief Build a variable declaration for OpenMP loop iteration variable.
2576static VarDecl *BuildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
2577 StringRef Name) {
2578 DeclContext *DC = SemaRef.CurContext;
2579 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2580 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2581 VarDecl *Decl =
2582 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
2583 Decl->setImplicit();
2584 return Decl;
2585}
2586
2587/// \brief Build 'VarRef = Start + Iter * Step'.
2588static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2589 SourceLocation Loc, ExprResult VarRef,
2590 ExprResult Start, ExprResult Iter,
2591 ExprResult Step, bool Subtract) {
2592 // Add parentheses (for debugging purposes only).
2593 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2594 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2595 !Step.isUsable())
2596 return ExprError();
2597
2598 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2599 Step.get()->IgnoreImplicit());
2600 if (!Update.isUsable())
2601 return ExprError();
2602
2603 // Build 'VarRef = Start + Iter * Step'.
2604 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2605 Start.get()->IgnoreImplicit(), Update.get());
2606 if (!Update.isUsable())
2607 return ExprError();
2608
2609 Update = SemaRef.PerformImplicitConversion(
2610 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2611 if (!Update.isUsable())
2612 return ExprError();
2613
2614 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2615 return Update;
2616}
2617
2618/// \brief Convert integer expression \a E to make it have at least \a Bits
2619/// bits.
2620static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2621 Sema &SemaRef) {
2622 if (E == nullptr)
2623 return ExprError();
2624 auto &C = SemaRef.Context;
2625 QualType OldType = E->getType();
2626 unsigned HasBits = C.getTypeSize(OldType);
2627 if (HasBits >= Bits)
2628 return ExprResult(E);
2629 // OK to convert to signed, because new type has more bits than old.
2630 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2631 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2632 true);
2633}
2634
2635/// \brief Check if the given expression \a E is a constant integer that fits
2636/// into \a Bits bits.
2637static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2638 if (E == nullptr)
2639 return false;
2640 llvm::APSInt Result;
2641 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2642 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2643 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002644}
2645
2646/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00002647/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2648/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002649static unsigned
2650CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2651 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002652 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00002653 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002654 unsigned NestedLoopCount = 1;
2655 if (NestedLoopCountExpr) {
2656 // Found 'collapse' clause - calculate collapse number.
2657 llvm::APSInt Result;
2658 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2659 NestedLoopCount = Result.getLimitedValue();
2660 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002661 // This is helper routine for loop directives (e.g., 'for', 'simd',
2662 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00002663 SmallVector<LoopIterationSpace, 4> IterSpaces;
2664 IterSpaces.resize(NestedLoopCount);
2665 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002666 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002667 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev4acb8592014-07-07 13:01:15 +00002668 NestedLoopCount, NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002669 VarsWithImplicitDSA, IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00002670 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002671 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002672 // OpenMP [2.8.1, simd construct, Restrictions]
2673 // All loops associated with the construct must be perfectly nested; that
2674 // is, there must be no intervening code nor any OpenMP directive between
2675 // any two loops.
2676 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002677 }
2678
Alexander Musmana5f070a2014-10-01 06:03:56 +00002679 Built.clear(/* size */ NestedLoopCount);
2680
2681 if (SemaRef.CurContext->isDependentContext())
2682 return NestedLoopCount;
2683
2684 // An example of what is generated for the following code:
2685 //
2686 // #pragma omp simd collapse(2)
2687 // for (i = 0; i < NI; ++i)
2688 // for (j = J0; j < NJ; j+=2) {
2689 // <loop body>
2690 // }
2691 //
2692 // We generate the code below.
2693 // Note: the loop body may be outlined in CodeGen.
2694 // Note: some counters may be C++ classes, operator- is used to find number of
2695 // iterations and operator+= to calculate counter value.
2696 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2697 // or i64 is currently supported).
2698 //
2699 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2700 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2701 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2702 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2703 // // similar updates for vars in clauses (e.g. 'linear')
2704 // <loop body (using local i and j)>
2705 // }
2706 // i = NI; // assign final values of counters
2707 // j = NJ;
2708 //
2709
2710 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2711 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002712 // Precondition tests if there is at least one iteration (all conditions are
2713 // true).
2714 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002715 auto N0 = IterSpaces[0].NumIterations;
2716 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2717 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2718
2719 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2720 return NestedLoopCount;
2721
2722 auto &C = SemaRef.Context;
2723 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
2724
2725 Scope *CurScope = DSA.getCurScope();
2726 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002727 if (PreCond.isUsable()) {
2728 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
2729 PreCond.get(), IterSpaces[Cnt].PreCond);
2730 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002731 auto N = IterSpaces[Cnt].NumIterations;
2732 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
2733 if (LastIteration32.isUsable())
2734 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2735 LastIteration32.get(), N);
2736 if (LastIteration64.isUsable())
2737 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2738 LastIteration64.get(), N);
2739 }
2740
2741 // Choose either the 32-bit or 64-bit version.
2742 ExprResult LastIteration = LastIteration64;
2743 if (LastIteration32.isUsable() &&
2744 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
2745 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
2746 FitsInto(
2747 32 /* Bits */,
2748 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
2749 LastIteration64.get(), SemaRef)))
2750 LastIteration = LastIteration32;
2751
2752 if (!LastIteration.isUsable())
2753 return 0;
2754
2755 // Save the number of iterations.
2756 ExprResult NumIterations = LastIteration;
2757 {
2758 LastIteration = SemaRef.BuildBinOp(
2759 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
2760 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2761 if (!LastIteration.isUsable())
2762 return 0;
2763 }
2764
2765 // Calculate the last iteration number beforehand instead of doing this on
2766 // each iteration. Do not do this if the number of iterations may be kfold-ed.
2767 llvm::APSInt Result;
2768 bool IsConstant =
2769 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
2770 ExprResult CalcLastIteration;
2771 if (!IsConstant) {
2772 SourceLocation SaveLoc;
2773 VarDecl *SaveVar =
2774 BuildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
2775 ".omp.last.iteration");
2776 ExprResult SaveRef = SemaRef.BuildDeclRefExpr(
2777 SaveVar, LastIteration.get()->getType(), VK_LValue, SaveLoc);
2778 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
2779 SaveRef.get(), LastIteration.get());
2780 LastIteration = SaveRef;
2781
2782 // Prepare SaveRef + 1.
2783 NumIterations = SemaRef.BuildBinOp(
2784 CurScope, SaveLoc, BO_Add, SaveRef.get(),
2785 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2786 if (!NumIterations.isUsable())
2787 return 0;
2788 }
2789
2790 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
2791
Alexander Musmanc6388682014-12-15 07:07:06 +00002792 QualType VType = LastIteration.get()->getType();
2793 // Build variables passed into runtime, nesessary for worksharing directives.
2794 ExprResult LB, UB, IL, ST, EUB;
2795 if (isOpenMPWorksharingDirective(DKind)) {
2796 // Lower bound variable, initialized with zero.
2797 VarDecl *LBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
2798 LB = SemaRef.BuildDeclRefExpr(LBDecl, VType, VK_LValue, InitLoc);
2799 SemaRef.AddInitializerToDecl(
2800 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2801 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2802
2803 // Upper bound variable, initialized with last iteration number.
2804 VarDecl *UBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
2805 UB = SemaRef.BuildDeclRefExpr(UBDecl, VType, VK_LValue, InitLoc);
2806 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
2807 /*DirectInit*/ false,
2808 /*TypeMayContainAuto*/ false);
2809
2810 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
2811 // This will be used to implement clause 'lastprivate'.
2812 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
2813 VarDecl *ILDecl = BuildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
2814 IL = SemaRef.BuildDeclRefExpr(ILDecl, Int32Ty, VK_LValue, InitLoc);
2815 SemaRef.AddInitializerToDecl(
2816 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2817 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2818
2819 // Stride variable returned by runtime (we initialize it to 1 by default).
2820 VarDecl *STDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
2821 ST = SemaRef.BuildDeclRefExpr(STDecl, VType, VK_LValue, InitLoc);
2822 SemaRef.AddInitializerToDecl(
2823 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
2824 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2825
2826 // Build expression: UB = min(UB, LastIteration)
2827 // It is nesessary for CodeGen of directives with static scheduling.
2828 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
2829 UB.get(), LastIteration.get());
2830 ExprResult CondOp = SemaRef.ActOnConditionalOp(
2831 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
2832 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
2833 CondOp.get());
2834 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
2835 }
2836
2837 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002838 ExprResult IV;
2839 ExprResult Init;
2840 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002841 VarDecl *IVDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
2842 IV = SemaRef.BuildDeclRefExpr(IVDecl, VType, VK_LValue, InitLoc);
2843 Expr *RHS = isOpenMPWorksharingDirective(DKind)
2844 ? LB.get()
2845 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
2846 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
2847 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002848 }
2849
Alexander Musmanc6388682014-12-15 07:07:06 +00002850 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002851 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00002852 ExprResult Cond =
2853 isOpenMPWorksharingDirective(DKind)
2854 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
2855 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
2856 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002857 // Loop condition with 1 iteration separated (IV < LastIteration)
2858 ExprResult SeparatedCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT,
2859 IV.get(), LastIteration.get());
2860
2861 // Loop increment (IV = IV + 1)
2862 SourceLocation IncLoc;
2863 ExprResult Inc =
2864 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
2865 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
2866 if (!Inc.isUsable())
2867 return 0;
2868 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00002869 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
2870 if (!Inc.isUsable())
2871 return 0;
2872
2873 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
2874 // Used for directives with static scheduling.
2875 ExprResult NextLB, NextUB;
2876 if (isOpenMPWorksharingDirective(DKind)) {
2877 // LB + ST
2878 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
2879 if (!NextLB.isUsable())
2880 return 0;
2881 // LB = LB + ST
2882 NextLB =
2883 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
2884 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
2885 if (!NextLB.isUsable())
2886 return 0;
2887 // UB + ST
2888 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
2889 if (!NextUB.isUsable())
2890 return 0;
2891 // UB = UB + ST
2892 NextUB =
2893 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
2894 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
2895 if (!NextUB.isUsable())
2896 return 0;
2897 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002898
2899 // Build updates and final values of the loop counters.
2900 bool HasErrors = false;
2901 Built.Counters.resize(NestedLoopCount);
2902 Built.Updates.resize(NestedLoopCount);
2903 Built.Finals.resize(NestedLoopCount);
2904 {
2905 ExprResult Div;
2906 // Go from inner nested loop to outer.
2907 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
2908 LoopIterationSpace &IS = IterSpaces[Cnt];
2909 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
2910 // Build: Iter = (IV / Div) % IS.NumIters
2911 // where Div is product of previous iterations' IS.NumIters.
2912 ExprResult Iter;
2913 if (Div.isUsable()) {
2914 Iter =
2915 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
2916 } else {
2917 Iter = IV;
2918 assert((Cnt == (int)NestedLoopCount - 1) &&
2919 "unusable div expected on first iteration only");
2920 }
2921
2922 if (Cnt != 0 && Iter.isUsable())
2923 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
2924 IS.NumIterations);
2925 if (!Iter.isUsable()) {
2926 HasErrors = true;
2927 break;
2928 }
2929
2930 // Build update: IS.CounterVar = IS.Start + Iter * IS.Step
2931 ExprResult Update =
2932 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, IS.CounterVar,
2933 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
2934 if (!Update.isUsable()) {
2935 HasErrors = true;
2936 break;
2937 }
2938
2939 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
2940 ExprResult Final = BuildCounterUpdate(
2941 SemaRef, CurScope, UpdLoc, IS.CounterVar, IS.CounterInit,
2942 IS.NumIterations, IS.CounterStep, IS.Subtract);
2943 if (!Final.isUsable()) {
2944 HasErrors = true;
2945 break;
2946 }
2947
2948 // Build Div for the next iteration: Div <- Div * IS.NumIters
2949 if (Cnt != 0) {
2950 if (Div.isUnset())
2951 Div = IS.NumIterations;
2952 else
2953 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
2954 IS.NumIterations);
2955
2956 // Add parentheses (for debugging purposes only).
2957 if (Div.isUsable())
2958 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
2959 if (!Div.isUsable()) {
2960 HasErrors = true;
2961 break;
2962 }
2963 }
2964 if (!Update.isUsable() || !Final.isUsable()) {
2965 HasErrors = true;
2966 break;
2967 }
2968 // Save results
2969 Built.Counters[Cnt] = IS.CounterVar;
2970 Built.Updates[Cnt] = Update.get();
2971 Built.Finals[Cnt] = Final.get();
2972 }
2973 }
2974
2975 if (HasErrors)
2976 return 0;
2977
2978 // Save results
2979 Built.IterationVarRef = IV.get();
2980 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00002981 Built.NumIterations = NumIterations.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002982 Built.CalcLastIteration = CalcLastIteration.get();
2983 Built.PreCond = PreCond.get();
2984 Built.Cond = Cond.get();
2985 Built.SeparatedCond = SeparatedCond.get();
2986 Built.Init = Init.get();
2987 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00002988 Built.LB = LB.get();
2989 Built.UB = UB.get();
2990 Built.IL = IL.get();
2991 Built.ST = ST.get();
2992 Built.EUB = EUB.get();
2993 Built.NLB = NextLB.get();
2994 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002995
Alexey Bataevabfc0692014-06-25 06:52:00 +00002996 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002997}
2998
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002999static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Alexey Bataevc925aa32015-04-27 08:00:32 +00003000 auto &&CollapseFilter = [](const OMPClause *C) -> bool {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003001 return C->getClauseKind() == OMPC_collapse;
3002 };
3003 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
Alexey Bataevc925aa32015-04-27 08:00:32 +00003004 Clauses, std::move(CollapseFilter));
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003005 if (I)
3006 return cast<OMPCollapseClause>(*I)->getNumForLoops();
3007 return nullptr;
3008}
3009
Alexey Bataev4acb8592014-07-07 13:01:15 +00003010StmtResult Sema::ActOnOpenMPSimdDirective(
3011 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3012 SourceLocation EndLoc,
3013 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003014 OMPLoopDirective::HelperExprs B;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003015 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003016 unsigned NestedLoopCount =
3017 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003018 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003019 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003020 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003021
Alexander Musmana5f070a2014-10-01 06:03:56 +00003022 assert((CurContext->isDependentContext() || B.builtAll()) &&
3023 "omp simd loop exprs were not built");
3024
Alexander Musman3276a272015-03-21 10:12:56 +00003025 if (!CurContext->isDependentContext()) {
3026 // Finalize the clauses that need pre-built expressions for CodeGen.
3027 for (auto C : Clauses) {
3028 if (auto LC = dyn_cast<OMPLinearClause>(C))
3029 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3030 B.NumIterations, *this, CurScope))
3031 return StmtError();
3032 }
3033 }
3034
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003035 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003036 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3037 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003038}
3039
Alexey Bataev4acb8592014-07-07 13:01:15 +00003040StmtResult Sema::ActOnOpenMPForDirective(
3041 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3042 SourceLocation EndLoc,
3043 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003044 OMPLoopDirective::HelperExprs B;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003045 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003046 unsigned NestedLoopCount =
3047 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003048 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003049 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00003050 return StmtError();
3051
Alexander Musmana5f070a2014-10-01 06:03:56 +00003052 assert((CurContext->isDependentContext() || B.builtAll()) &&
3053 "omp for loop exprs were not built");
3054
Alexey Bataevf29276e2014-06-18 04:14:57 +00003055 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003056 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3057 Clauses, AStmt, B);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003058}
3059
Alexander Musmanf82886e2014-09-18 05:12:34 +00003060StmtResult Sema::ActOnOpenMPForSimdDirective(
3061 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3062 SourceLocation EndLoc,
3063 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003064 OMPLoopDirective::HelperExprs B;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003065 // In presence of clause 'collapse', it will define the nested loops number.
3066 unsigned NestedLoopCount =
3067 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003068 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003069 if (NestedLoopCount == 0)
3070 return StmtError();
3071
Alexander Musmanc6388682014-12-15 07:07:06 +00003072 assert((CurContext->isDependentContext() || B.builtAll()) &&
3073 "omp for simd loop exprs were not built");
3074
Alexander Musmanf82886e2014-09-18 05:12:34 +00003075 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003076 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3077 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003078}
3079
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003080StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3081 Stmt *AStmt,
3082 SourceLocation StartLoc,
3083 SourceLocation EndLoc) {
3084 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3085 auto BaseStmt = AStmt;
3086 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3087 BaseStmt = CS->getCapturedStmt();
3088 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3089 auto S = C->children();
3090 if (!S)
3091 return StmtError();
3092 // All associated statements must be '#pragma omp section' except for
3093 // the first one.
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003094 for (++S; S; ++S) {
3095 auto SectionStmt = *S;
3096 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3097 if (SectionStmt)
3098 Diag(SectionStmt->getLocStart(),
3099 diag::err_omp_sections_substmt_not_section);
3100 return StmtError();
3101 }
3102 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003103 } else {
3104 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3105 return StmtError();
3106 }
3107
3108 getCurFunction()->setHasBranchProtectedScope();
3109
3110 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3111 AStmt);
3112}
3113
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003114StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3115 SourceLocation StartLoc,
3116 SourceLocation EndLoc) {
3117 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3118
3119 getCurFunction()->setHasBranchProtectedScope();
3120
3121 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3122}
3123
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003124StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3125 Stmt *AStmt,
3126 SourceLocation StartLoc,
3127 SourceLocation EndLoc) {
Alexey Bataev74a05c92014-07-15 02:55:09 +00003128 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3129
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003130 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00003131
Alexey Bataev3255bf32015-01-19 05:20:46 +00003132 // OpenMP [2.7.3, single Construct, Restrictions]
3133 // The copyprivate clause must not be used with the nowait clause.
3134 OMPClause *Nowait = nullptr;
3135 OMPClause *Copyprivate = nullptr;
3136 for (auto *Clause : Clauses) {
3137 if (Clause->getClauseKind() == OMPC_nowait)
3138 Nowait = Clause;
3139 else if (Clause->getClauseKind() == OMPC_copyprivate)
3140 Copyprivate = Clause;
3141 if (Copyprivate && Nowait) {
3142 Diag(Copyprivate->getLocStart(),
3143 diag::err_omp_single_copyprivate_with_nowait);
3144 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3145 return StmtError();
3146 }
3147 }
3148
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003149 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3150}
3151
Alexander Musman80c22892014-07-17 08:54:58 +00003152StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3153 SourceLocation StartLoc,
3154 SourceLocation EndLoc) {
3155 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3156
3157 getCurFunction()->setHasBranchProtectedScope();
3158
3159 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3160}
3161
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003162StmtResult
3163Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3164 Stmt *AStmt, SourceLocation StartLoc,
3165 SourceLocation EndLoc) {
3166 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3167
3168 getCurFunction()->setHasBranchProtectedScope();
3169
3170 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3171 AStmt);
3172}
3173
Alexey Bataev4acb8592014-07-07 13:01:15 +00003174StmtResult Sema::ActOnOpenMPParallelForDirective(
3175 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3176 SourceLocation EndLoc,
3177 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3178 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3179 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3180 // 1.2.2 OpenMP Language Terminology
3181 // Structured block - An executable statement with a single entry at the
3182 // top and a single exit at the bottom.
3183 // The point of exit cannot be a branch out of the structured block.
3184 // longjmp() and throw() must not violate the entry/exit criteria.
3185 CS->getCapturedDecl()->setNothrow();
3186
Alexander Musmanc6388682014-12-15 07:07:06 +00003187 OMPLoopDirective::HelperExprs B;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003188 // In presence of clause 'collapse', it will define the nested loops number.
3189 unsigned NestedLoopCount =
3190 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003191 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003192 if (NestedLoopCount == 0)
3193 return StmtError();
3194
Alexander Musmana5f070a2014-10-01 06:03:56 +00003195 assert((CurContext->isDependentContext() || B.builtAll()) &&
3196 "omp parallel for loop exprs were not built");
3197
Alexey Bataev4acb8592014-07-07 13:01:15 +00003198 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003199 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3200 NestedLoopCount, Clauses, AStmt, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003201}
3202
Alexander Musmane4e893b2014-09-23 09:33:00 +00003203StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3204 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3205 SourceLocation EndLoc,
3206 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3207 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3208 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3209 // 1.2.2 OpenMP Language Terminology
3210 // Structured block - An executable statement with a single entry at the
3211 // top and a single exit at the bottom.
3212 // The point of exit cannot be a branch out of the structured block.
3213 // longjmp() and throw() must not violate the entry/exit criteria.
3214 CS->getCapturedDecl()->setNothrow();
3215
Alexander Musmanc6388682014-12-15 07:07:06 +00003216 OMPLoopDirective::HelperExprs B;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003217 // In presence of clause 'collapse', it will define the nested loops number.
3218 unsigned NestedLoopCount =
3219 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003220 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003221 if (NestedLoopCount == 0)
3222 return StmtError();
3223
3224 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003225 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00003226 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003227}
3228
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003229StmtResult
3230Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3231 Stmt *AStmt, SourceLocation StartLoc,
3232 SourceLocation EndLoc) {
3233 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3234 auto BaseStmt = AStmt;
3235 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3236 BaseStmt = CS->getCapturedStmt();
3237 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3238 auto S = C->children();
3239 if (!S)
3240 return StmtError();
3241 // All associated statements must be '#pragma omp section' except for
3242 // the first one.
3243 for (++S; S; ++S) {
3244 auto SectionStmt = *S;
3245 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3246 if (SectionStmt)
3247 Diag(SectionStmt->getLocStart(),
3248 diag::err_omp_parallel_sections_substmt_not_section);
3249 return StmtError();
3250 }
3251 }
3252 } else {
3253 Diag(AStmt->getLocStart(),
3254 diag::err_omp_parallel_sections_not_compound_stmt);
3255 return StmtError();
3256 }
3257
3258 getCurFunction()->setHasBranchProtectedScope();
3259
3260 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3261 Clauses, AStmt);
3262}
3263
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003264StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3265 Stmt *AStmt, SourceLocation StartLoc,
3266 SourceLocation EndLoc) {
3267 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3268 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3269 // 1.2.2 OpenMP Language Terminology
3270 // Structured block - An executable statement with a single entry at the
3271 // top and a single exit at the bottom.
3272 // The point of exit cannot be a branch out of the structured block.
3273 // longjmp() and throw() must not violate the entry/exit criteria.
3274 CS->getCapturedDecl()->setNothrow();
3275
3276 getCurFunction()->setHasBranchProtectedScope();
3277
3278 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3279}
3280
Alexey Bataev68446b72014-07-18 07:47:19 +00003281StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3282 SourceLocation EndLoc) {
3283 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3284}
3285
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003286StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3287 SourceLocation EndLoc) {
3288 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3289}
3290
Alexey Bataev2df347a2014-07-18 10:17:07 +00003291StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3292 SourceLocation EndLoc) {
3293 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3294}
3295
Alexey Bataev6125da92014-07-21 11:26:11 +00003296StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3297 SourceLocation StartLoc,
3298 SourceLocation EndLoc) {
3299 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3300 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3301}
3302
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003303StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3304 SourceLocation StartLoc,
3305 SourceLocation EndLoc) {
3306 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3307
3308 getCurFunction()->setHasBranchProtectedScope();
3309
3310 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3311}
3312
Alexey Bataev1d160b12015-03-13 12:27:31 +00003313namespace {
3314/// \brief Helper class for checking expression in 'omp atomic [update]'
3315/// construct.
3316class OpenMPAtomicUpdateChecker {
3317 /// \brief Error results for atomic update expressions.
3318 enum ExprAnalysisErrorCode {
3319 /// \brief A statement is not an expression statement.
3320 NotAnExpression,
3321 /// \brief Expression is not builtin binary or unary operation.
3322 NotABinaryOrUnaryExpression,
3323 /// \brief Unary operation is not post-/pre- increment/decrement operation.
3324 NotAnUnaryIncDecExpression,
3325 /// \brief An expression is not of scalar type.
3326 NotAScalarType,
3327 /// \brief A binary operation is not an assignment operation.
3328 NotAnAssignmentOp,
3329 /// \brief RHS part of the binary operation is not a binary expression.
3330 NotABinaryExpression,
3331 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
3332 /// expression.
3333 NotABinaryOperator,
3334 /// \brief RHS binary operation does not have reference to the updated LHS
3335 /// part.
3336 NotAnUpdateExpression,
3337 /// \brief No errors is found.
3338 NoError
3339 };
3340 /// \brief Reference to Sema.
3341 Sema &SemaRef;
3342 /// \brief A location for note diagnostics (when error is found).
3343 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003344 /// \brief 'x' lvalue part of the source atomic expression.
3345 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003346 /// \brief 'expr' rvalue part of the source atomic expression.
3347 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003348 /// \brief Helper expression of the form
3349 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3350 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3351 Expr *UpdateExpr;
3352 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
3353 /// important for non-associative operations.
3354 bool IsXLHSInRHSPart;
3355 BinaryOperatorKind Op;
3356 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003357 /// \brief true if the source expression is a postfix unary operation, false
3358 /// if it is a prefix unary operation.
3359 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003360
3361public:
3362 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00003363 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00003364 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00003365 /// \brief Check specified statement that it is suitable for 'atomic update'
3366 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00003367 /// expression. If DiagId and NoteId == 0, then only check is performed
3368 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00003369 /// \param DiagId Diagnostic which should be emitted if error is found.
3370 /// \param NoteId Diagnostic note for the main error message.
3371 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00003372 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003373 /// \brief Return the 'x' lvalue part of the source atomic expression.
3374 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00003375 /// \brief Return the 'expr' rvalue part of the source atomic expression.
3376 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00003377 /// \brief Return the update expression used in calculation of the updated
3378 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3379 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3380 Expr *getUpdateExpr() const { return UpdateExpr; }
3381 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
3382 /// false otherwise.
3383 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
3384
Alexey Bataevb78ca832015-04-01 03:33:17 +00003385 /// \brief true if the source expression is a postfix unary operation, false
3386 /// if it is a prefix unary operation.
3387 bool isPostfixUpdate() const { return IsPostfixUpdate; }
3388
Alexey Bataev1d160b12015-03-13 12:27:31 +00003389private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00003390 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
3391 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003392};
3393} // namespace
3394
3395bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
3396 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
3397 ExprAnalysisErrorCode ErrorFound = NoError;
3398 SourceLocation ErrorLoc, NoteLoc;
3399 SourceRange ErrorRange, NoteRange;
3400 // Allowed constructs are:
3401 // x = x binop expr;
3402 // x = expr binop x;
3403 if (AtomicBinOp->getOpcode() == BO_Assign) {
3404 X = AtomicBinOp->getLHS();
3405 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
3406 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
3407 if (AtomicInnerBinOp->isMultiplicativeOp() ||
3408 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
3409 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003410 Op = AtomicInnerBinOp->getOpcode();
3411 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003412 auto *LHS = AtomicInnerBinOp->getLHS();
3413 auto *RHS = AtomicInnerBinOp->getRHS();
3414 llvm::FoldingSetNodeID XId, LHSId, RHSId;
3415 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
3416 /*Canonical=*/true);
3417 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
3418 /*Canonical=*/true);
3419 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
3420 /*Canonical=*/true);
3421 if (XId == LHSId) {
3422 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003423 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003424 } else if (XId == RHSId) {
3425 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003426 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003427 } else {
3428 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3429 ErrorRange = AtomicInnerBinOp->getSourceRange();
3430 NoteLoc = X->getExprLoc();
3431 NoteRange = X->getSourceRange();
3432 ErrorFound = NotAnUpdateExpression;
3433 }
3434 } else {
3435 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3436 ErrorRange = AtomicInnerBinOp->getSourceRange();
3437 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
3438 NoteRange = SourceRange(NoteLoc, NoteLoc);
3439 ErrorFound = NotABinaryOperator;
3440 }
3441 } else {
3442 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
3443 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
3444 ErrorFound = NotABinaryExpression;
3445 }
3446 } else {
3447 ErrorLoc = AtomicBinOp->getExprLoc();
3448 ErrorRange = AtomicBinOp->getSourceRange();
3449 NoteLoc = AtomicBinOp->getOperatorLoc();
3450 NoteRange = SourceRange(NoteLoc, NoteLoc);
3451 ErrorFound = NotAnAssignmentOp;
3452 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003453 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003454 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3455 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3456 return true;
3457 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003458 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003459 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003460}
3461
3462bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
3463 unsigned NoteId) {
3464 ExprAnalysisErrorCode ErrorFound = NoError;
3465 SourceLocation ErrorLoc, NoteLoc;
3466 SourceRange ErrorRange, NoteRange;
3467 // Allowed constructs are:
3468 // x++;
3469 // x--;
3470 // ++x;
3471 // --x;
3472 // x binop= expr;
3473 // x = x binop expr;
3474 // x = expr binop x;
3475 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
3476 AtomicBody = AtomicBody->IgnoreParenImpCasts();
3477 if (AtomicBody->getType()->isScalarType() ||
3478 AtomicBody->isInstantiationDependent()) {
3479 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
3480 AtomicBody->IgnoreParenImpCasts())) {
3481 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003482 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00003483 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003484 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003485 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003486 X = AtomicCompAssignOp->getLHS();
3487 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003488 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
3489 AtomicBody->IgnoreParenImpCasts())) {
3490 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003491 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
3492 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003493 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00003494 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
3495 // Check for Unary Operation
3496 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003497 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003498 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
3499 OpLoc = AtomicUnaryOp->getOperatorLoc();
3500 X = AtomicUnaryOp->getSubExpr();
3501 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
3502 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003503 } else {
3504 ErrorFound = NotAnUnaryIncDecExpression;
3505 ErrorLoc = AtomicUnaryOp->getExprLoc();
3506 ErrorRange = AtomicUnaryOp->getSourceRange();
3507 NoteLoc = AtomicUnaryOp->getOperatorLoc();
3508 NoteRange = SourceRange(NoteLoc, NoteLoc);
3509 }
3510 } else {
3511 ErrorFound = NotABinaryOrUnaryExpression;
3512 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
3513 NoteRange = ErrorRange = AtomicBody->getSourceRange();
3514 }
3515 } else {
3516 ErrorFound = NotAScalarType;
3517 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
3518 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3519 }
3520 } else {
3521 ErrorFound = NotAnExpression;
3522 NoteLoc = ErrorLoc = S->getLocStart();
3523 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3524 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003525 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003526 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3527 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3528 return true;
3529 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003530 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003531 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003532 // Build an update expression of form 'OpaqueValueExpr(x) binop
3533 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
3534 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
3535 auto *OVEX = new (SemaRef.getASTContext())
3536 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
3537 auto *OVEExpr = new (SemaRef.getASTContext())
3538 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
3539 auto Update =
3540 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
3541 IsXLHSInRHSPart ? OVEExpr : OVEX);
3542 if (Update.isInvalid())
3543 return true;
3544 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
3545 Sema::AA_Casting);
3546 if (Update.isInvalid())
3547 return true;
3548 UpdateExpr = Update.get();
3549 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003550 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003551}
3552
Alexey Bataev0162e452014-07-22 10:10:35 +00003553StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3554 Stmt *AStmt,
3555 SourceLocation StartLoc,
3556 SourceLocation EndLoc) {
3557 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003558 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00003559 // 1.2.2 OpenMP Language Terminology
3560 // Structured block - An executable statement with a single entry at the
3561 // top and a single exit at the bottom.
3562 // The point of exit cannot be a branch out of the structured block.
3563 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00003564 OpenMPClauseKind AtomicKind = OMPC_unknown;
3565 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003566 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00003567 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00003568 C->getClauseKind() == OMPC_update ||
3569 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00003570 if (AtomicKind != OMPC_unknown) {
3571 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3572 << SourceRange(C->getLocStart(), C->getLocEnd());
3573 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3574 << getOpenMPClauseName(AtomicKind);
3575 } else {
3576 AtomicKind = C->getClauseKind();
3577 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003578 }
3579 }
3580 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003581
Alexey Bataev459dec02014-07-24 06:46:57 +00003582 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00003583 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
3584 Body = EWC->getSubExpr();
3585
Alexey Bataev62cec442014-11-18 10:14:22 +00003586 Expr *X = nullptr;
3587 Expr *V = nullptr;
3588 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003589 Expr *UE = nullptr;
3590 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003591 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00003592 // OpenMP [2.12.6, atomic Construct]
3593 // In the next expressions:
3594 // * x and v (as applicable) are both l-value expressions with scalar type.
3595 // * During the execution of an atomic region, multiple syntactic
3596 // occurrences of x must designate the same storage location.
3597 // * Neither of v and expr (as applicable) may access the storage location
3598 // designated by x.
3599 // * Neither of x and expr (as applicable) may access the storage location
3600 // designated by v.
3601 // * expr is an expression with scalar type.
3602 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3603 // * binop, binop=, ++, and -- are not overloaded operators.
3604 // * The expression x binop expr must be numerically equivalent to x binop
3605 // (expr). This requirement is satisfied if the operators in expr have
3606 // precedence greater than binop, or by using parentheses around expr or
3607 // subexpressions of expr.
3608 // * The expression expr binop x must be numerically equivalent to (expr)
3609 // binop x. This requirement is satisfied if the operators in expr have
3610 // precedence equal to or greater than binop, or by using parentheses around
3611 // expr or subexpressions of expr.
3612 // * For forms that allow multiple occurrences of x, the number of times
3613 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00003614 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003615 enum {
3616 NotAnExpression,
3617 NotAnAssignmentOp,
3618 NotAScalarType,
3619 NotAnLValue,
3620 NoError
3621 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00003622 SourceLocation ErrorLoc, NoteLoc;
3623 SourceRange ErrorRange, NoteRange;
3624 // If clause is read:
3625 // v = x;
3626 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3627 auto AtomicBinOp =
3628 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3629 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3630 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3631 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3632 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3633 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3634 if (!X->isLValue() || !V->isLValue()) {
3635 auto NotLValueExpr = X->isLValue() ? V : X;
3636 ErrorFound = NotAnLValue;
3637 ErrorLoc = AtomicBinOp->getExprLoc();
3638 ErrorRange = AtomicBinOp->getSourceRange();
3639 NoteLoc = NotLValueExpr->getExprLoc();
3640 NoteRange = NotLValueExpr->getSourceRange();
3641 }
3642 } else if (!X->isInstantiationDependent() ||
3643 !V->isInstantiationDependent()) {
3644 auto NotScalarExpr =
3645 (X->isInstantiationDependent() || X->getType()->isScalarType())
3646 ? V
3647 : X;
3648 ErrorFound = NotAScalarType;
3649 ErrorLoc = AtomicBinOp->getExprLoc();
3650 ErrorRange = AtomicBinOp->getSourceRange();
3651 NoteLoc = NotScalarExpr->getExprLoc();
3652 NoteRange = NotScalarExpr->getSourceRange();
3653 }
3654 } else {
3655 ErrorFound = NotAnAssignmentOp;
3656 ErrorLoc = AtomicBody->getExprLoc();
3657 ErrorRange = AtomicBody->getSourceRange();
3658 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3659 : AtomicBody->getExprLoc();
3660 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3661 : AtomicBody->getSourceRange();
3662 }
3663 } else {
3664 ErrorFound = NotAnExpression;
3665 NoteLoc = ErrorLoc = Body->getLocStart();
3666 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003667 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003668 if (ErrorFound != NoError) {
3669 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3670 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003671 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3672 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00003673 return StmtError();
3674 } else if (CurContext->isDependentContext())
3675 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00003676 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003677 enum {
3678 NotAnExpression,
3679 NotAnAssignmentOp,
3680 NotAScalarType,
3681 NotAnLValue,
3682 NoError
3683 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003684 SourceLocation ErrorLoc, NoteLoc;
3685 SourceRange ErrorRange, NoteRange;
3686 // If clause is write:
3687 // x = expr;
3688 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3689 auto AtomicBinOp =
3690 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3691 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00003692 X = AtomicBinOp->getLHS();
3693 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00003694 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3695 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
3696 if (!X->isLValue()) {
3697 ErrorFound = NotAnLValue;
3698 ErrorLoc = AtomicBinOp->getExprLoc();
3699 ErrorRange = AtomicBinOp->getSourceRange();
3700 NoteLoc = X->getExprLoc();
3701 NoteRange = X->getSourceRange();
3702 }
3703 } else if (!X->isInstantiationDependent() ||
3704 !E->isInstantiationDependent()) {
3705 auto NotScalarExpr =
3706 (X->isInstantiationDependent() || X->getType()->isScalarType())
3707 ? E
3708 : X;
3709 ErrorFound = NotAScalarType;
3710 ErrorLoc = AtomicBinOp->getExprLoc();
3711 ErrorRange = AtomicBinOp->getSourceRange();
3712 NoteLoc = NotScalarExpr->getExprLoc();
3713 NoteRange = NotScalarExpr->getSourceRange();
3714 }
3715 } else {
3716 ErrorFound = NotAnAssignmentOp;
3717 ErrorLoc = AtomicBody->getExprLoc();
3718 ErrorRange = AtomicBody->getSourceRange();
3719 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3720 : AtomicBody->getExprLoc();
3721 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3722 : AtomicBody->getSourceRange();
3723 }
3724 } else {
3725 ErrorFound = NotAnExpression;
3726 NoteLoc = ErrorLoc = Body->getLocStart();
3727 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003728 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00003729 if (ErrorFound != NoError) {
3730 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
3731 << ErrorRange;
3732 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3733 << NoteRange;
3734 return StmtError();
3735 } else if (CurContext->isDependentContext())
3736 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00003737 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003738 // If clause is update:
3739 // x++;
3740 // x--;
3741 // ++x;
3742 // --x;
3743 // x binop= expr;
3744 // x = x binop expr;
3745 // x = expr binop x;
3746 OpenMPAtomicUpdateChecker Checker(*this);
3747 if (Checker.checkStatement(
3748 Body, (AtomicKind == OMPC_update)
3749 ? diag::err_omp_atomic_update_not_expression_statement
3750 : diag::err_omp_atomic_not_expression_statement,
3751 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00003752 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003753 if (!CurContext->isDependentContext()) {
3754 E = Checker.getExpr();
3755 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003756 UE = Checker.getUpdateExpr();
3757 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00003758 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003759 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003760 enum {
3761 NotAnAssignmentOp,
3762 NotACompoundStatement,
3763 NotTwoSubstatements,
3764 NotASpecificExpression,
3765 NoError
3766 } ErrorFound = NoError;
3767 SourceLocation ErrorLoc, NoteLoc;
3768 SourceRange ErrorRange, NoteRange;
3769 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
3770 // If clause is a capture:
3771 // v = x++;
3772 // v = x--;
3773 // v = ++x;
3774 // v = --x;
3775 // v = x binop= expr;
3776 // v = x = x binop expr;
3777 // v = x = expr binop x;
3778 auto *AtomicBinOp =
3779 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3780 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3781 V = AtomicBinOp->getLHS();
3782 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3783 OpenMPAtomicUpdateChecker Checker(*this);
3784 if (Checker.checkStatement(
3785 Body, diag::err_omp_atomic_capture_not_expression_statement,
3786 diag::note_omp_atomic_update))
3787 return StmtError();
3788 E = Checker.getExpr();
3789 X = Checker.getX();
3790 UE = Checker.getUpdateExpr();
3791 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3792 IsPostfixUpdate = Checker.isPostfixUpdate();
3793 } else {
3794 ErrorLoc = AtomicBody->getExprLoc();
3795 ErrorRange = AtomicBody->getSourceRange();
3796 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3797 : AtomicBody->getExprLoc();
3798 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3799 : AtomicBody->getSourceRange();
3800 ErrorFound = NotAnAssignmentOp;
3801 }
3802 if (ErrorFound != NoError) {
3803 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
3804 << ErrorRange;
3805 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3806 return StmtError();
3807 } else if (CurContext->isDependentContext()) {
3808 UE = V = E = X = nullptr;
3809 }
3810 } else {
3811 // If clause is a capture:
3812 // { v = x; x = expr; }
3813 // { v = x; x++; }
3814 // { v = x; x--; }
3815 // { v = x; ++x; }
3816 // { v = x; --x; }
3817 // { v = x; x binop= expr; }
3818 // { v = x; x = x binop expr; }
3819 // { v = x; x = expr binop x; }
3820 // { x++; v = x; }
3821 // { x--; v = x; }
3822 // { ++x; v = x; }
3823 // { --x; v = x; }
3824 // { x binop= expr; v = x; }
3825 // { x = x binop expr; v = x; }
3826 // { x = expr binop x; v = x; }
3827 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
3828 // Check that this is { expr1; expr2; }
3829 if (CS->size() == 2) {
3830 auto *First = CS->body_front();
3831 auto *Second = CS->body_back();
3832 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
3833 First = EWC->getSubExpr()->IgnoreParenImpCasts();
3834 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
3835 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
3836 // Need to find what subexpression is 'v' and what is 'x'.
3837 OpenMPAtomicUpdateChecker Checker(*this);
3838 bool IsUpdateExprFound = !Checker.checkStatement(Second);
3839 BinaryOperator *BinOp = nullptr;
3840 if (IsUpdateExprFound) {
3841 BinOp = dyn_cast<BinaryOperator>(First);
3842 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3843 }
3844 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3845 // { v = x; x++; }
3846 // { v = x; x--; }
3847 // { v = x; ++x; }
3848 // { v = x; --x; }
3849 // { v = x; x binop= expr; }
3850 // { v = x; x = x binop expr; }
3851 // { v = x; x = expr binop x; }
3852 // Check that the first expression has form v = x.
3853 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3854 llvm::FoldingSetNodeID XId, PossibleXId;
3855 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3856 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3857 IsUpdateExprFound = XId == PossibleXId;
3858 if (IsUpdateExprFound) {
3859 V = BinOp->getLHS();
3860 X = Checker.getX();
3861 E = Checker.getExpr();
3862 UE = Checker.getUpdateExpr();
3863 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003864 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003865 }
3866 }
3867 if (!IsUpdateExprFound) {
3868 IsUpdateExprFound = !Checker.checkStatement(First);
3869 BinOp = nullptr;
3870 if (IsUpdateExprFound) {
3871 BinOp = dyn_cast<BinaryOperator>(Second);
3872 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3873 }
3874 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3875 // { x++; v = x; }
3876 // { x--; v = x; }
3877 // { ++x; v = x; }
3878 // { --x; v = x; }
3879 // { x binop= expr; v = x; }
3880 // { x = x binop expr; v = x; }
3881 // { x = expr binop x; v = x; }
3882 // Check that the second expression has form v = x.
3883 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3884 llvm::FoldingSetNodeID XId, PossibleXId;
3885 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3886 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3887 IsUpdateExprFound = XId == PossibleXId;
3888 if (IsUpdateExprFound) {
3889 V = BinOp->getLHS();
3890 X = Checker.getX();
3891 E = Checker.getExpr();
3892 UE = Checker.getUpdateExpr();
3893 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003894 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003895 }
3896 }
3897 }
3898 if (!IsUpdateExprFound) {
3899 // { v = x; x = expr; }
3900 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
3901 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
3902 ErrorFound = NotAnAssignmentOp;
3903 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
3904 : First->getLocStart();
3905 NoteRange = ErrorRange = FirstBinOp
3906 ? FirstBinOp->getSourceRange()
3907 : SourceRange(ErrorLoc, ErrorLoc);
3908 } else {
3909 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
3910 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
3911 ErrorFound = NotAnAssignmentOp;
3912 NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
3913 : Second->getLocStart();
3914 NoteRange = ErrorRange = SecondBinOp
3915 ? SecondBinOp->getSourceRange()
3916 : SourceRange(ErrorLoc, ErrorLoc);
3917 } else {
3918 auto *PossibleXRHSInFirst =
3919 FirstBinOp->getRHS()->IgnoreParenImpCasts();
3920 auto *PossibleXLHSInSecond =
3921 SecondBinOp->getLHS()->IgnoreParenImpCasts();
3922 llvm::FoldingSetNodeID X1Id, X2Id;
3923 PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
3924 PossibleXLHSInSecond->Profile(X2Id, Context,
3925 /*Canonical=*/true);
3926 IsUpdateExprFound = X1Id == X2Id;
3927 if (IsUpdateExprFound) {
3928 V = FirstBinOp->getLHS();
3929 X = SecondBinOp->getLHS();
3930 E = SecondBinOp->getRHS();
3931 UE = nullptr;
3932 IsXLHSInRHSPart = false;
3933 IsPostfixUpdate = true;
3934 } else {
3935 ErrorFound = NotASpecificExpression;
3936 ErrorLoc = FirstBinOp->getExprLoc();
3937 ErrorRange = FirstBinOp->getSourceRange();
3938 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
3939 NoteRange = SecondBinOp->getRHS()->getSourceRange();
3940 }
3941 }
3942 }
3943 }
3944 } else {
3945 NoteLoc = ErrorLoc = Body->getLocStart();
3946 NoteRange = ErrorRange =
3947 SourceRange(Body->getLocStart(), Body->getLocStart());
3948 ErrorFound = NotTwoSubstatements;
3949 }
3950 } else {
3951 NoteLoc = ErrorLoc = Body->getLocStart();
3952 NoteRange = ErrorRange =
3953 SourceRange(Body->getLocStart(), Body->getLocStart());
3954 ErrorFound = NotACompoundStatement;
3955 }
3956 if (ErrorFound != NoError) {
3957 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
3958 << ErrorRange;
3959 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3960 return StmtError();
3961 } else if (CurContext->isDependentContext()) {
3962 UE = V = E = X = nullptr;
3963 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003964 }
Alexey Bataevdea47612014-07-23 07:46:59 +00003965 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003966
3967 getCurFunction()->setHasBranchProtectedScope();
3968
Alexey Bataev62cec442014-11-18 10:14:22 +00003969 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00003970 X, V, E, UE, IsXLHSInRHSPart,
3971 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00003972}
3973
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003974StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
3975 Stmt *AStmt,
3976 SourceLocation StartLoc,
3977 SourceLocation EndLoc) {
3978 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3979
Alexey Bataev13314bf2014-10-09 04:18:56 +00003980 // OpenMP [2.16, Nesting of Regions]
3981 // If specified, a teams construct must be contained within a target
3982 // construct. That target construct must contain no statements or directives
3983 // outside of the teams construct.
3984 if (DSAStack->hasInnerTeamsRegion()) {
3985 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
3986 bool OMPTeamsFound = true;
3987 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
3988 auto I = CS->body_begin();
3989 while (I != CS->body_end()) {
3990 auto OED = dyn_cast<OMPExecutableDirective>(*I);
3991 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
3992 OMPTeamsFound = false;
3993 break;
3994 }
3995 ++I;
3996 }
3997 assert(I != CS->body_end() && "Not found statement");
3998 S = *I;
3999 }
4000 if (!OMPTeamsFound) {
4001 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
4002 Diag(DSAStack->getInnerTeamsRegionLoc(),
4003 diag::note_omp_nested_teams_construct_here);
4004 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
4005 << isa<OMPExecutableDirective>(S);
4006 return StmtError();
4007 }
4008 }
4009
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004010 getCurFunction()->setHasBranchProtectedScope();
4011
4012 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4013}
4014
Alexey Bataev13314bf2014-10-09 04:18:56 +00004015StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
4016 Stmt *AStmt, SourceLocation StartLoc,
4017 SourceLocation EndLoc) {
4018 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4019 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4020 // 1.2.2 OpenMP Language Terminology
4021 // Structured block - An executable statement with a single entry at the
4022 // top and a single exit at the bottom.
4023 // The point of exit cannot be a branch out of the structured block.
4024 // longjmp() and throw() must not violate the entry/exit criteria.
4025 CS->getCapturedDecl()->setNothrow();
4026
4027 getCurFunction()->setHasBranchProtectedScope();
4028
4029 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4030}
4031
Alexey Bataeved09d242014-05-28 05:53:51 +00004032OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004033 SourceLocation StartLoc,
4034 SourceLocation LParenLoc,
4035 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004036 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004037 switch (Kind) {
4038 case OMPC_if:
4039 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
4040 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00004041 case OMPC_final:
4042 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
4043 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00004044 case OMPC_num_threads:
4045 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
4046 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004047 case OMPC_safelen:
4048 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
4049 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00004050 case OMPC_collapse:
4051 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
4052 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004053 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004054 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004055 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004056 case OMPC_private:
4057 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004058 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004059 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004060 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004061 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004062 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004063 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004064 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004065 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004066 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004067 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004068 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004069 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004070 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004071 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004072 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004073 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004074 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004075 case OMPC_seq_cst:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004076 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004077 llvm_unreachable("Clause is not allowed.");
4078 }
4079 return Res;
4080}
4081
Alexey Bataeved09d242014-05-28 05:53:51 +00004082OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004083 SourceLocation LParenLoc,
4084 SourceLocation EndLoc) {
4085 Expr *ValExpr = Condition;
4086 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4087 !Condition->isInstantiationDependent() &&
4088 !Condition->containsUnexpandedParameterPack()) {
4089 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00004090 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004091 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004092 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004093
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004094 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004095 }
4096
4097 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4098}
4099
Alexey Bataev3778b602014-07-17 07:32:53 +00004100OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
4101 SourceLocation StartLoc,
4102 SourceLocation LParenLoc,
4103 SourceLocation EndLoc) {
4104 Expr *ValExpr = Condition;
4105 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4106 !Condition->isInstantiationDependent() &&
4107 !Condition->containsUnexpandedParameterPack()) {
4108 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4109 Condition->getExprLoc(), Condition);
4110 if (Val.isInvalid())
4111 return nullptr;
4112
4113 ValExpr = Val.get();
4114 }
4115
4116 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4117}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004118ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
4119 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004120 if (!Op)
4121 return ExprError();
4122
4123 class IntConvertDiagnoser : public ICEConvertDiagnoser {
4124 public:
4125 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00004126 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00004127 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
4128 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004129 return S.Diag(Loc, diag::err_omp_not_integral) << T;
4130 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004131 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4132 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004133 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
4134 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004135 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4136 QualType T,
4137 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004138 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
4139 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004140 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4141 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004142 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004143 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004144 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004145 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4146 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004147 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
4148 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004149 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4150 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004151 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004152 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004153 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004154 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
4155 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004156 llvm_unreachable("conversion functions are permitted");
4157 }
4158 } ConvertDiagnoser;
4159 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
4160}
4161
4162OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
4163 SourceLocation StartLoc,
4164 SourceLocation LParenLoc,
4165 SourceLocation EndLoc) {
4166 Expr *ValExpr = NumThreads;
4167 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
Alexey Bataev568a8332014-03-06 06:15:19 +00004168 !NumThreads->containsUnexpandedParameterPack()) {
4169 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
4170 ExprResult Val =
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004171 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
Alexey Bataev568a8332014-03-06 06:15:19 +00004172 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004173 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004174
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004175 ValExpr = Val.get();
Alexey Bataev568a8332014-03-06 06:15:19 +00004176
4177 // OpenMP [2.5, Restrictions]
4178 // The num_threads expression must evaluate to a positive integer value.
4179 llvm::APSInt Result;
Alexey Bataeved09d242014-05-28 05:53:51 +00004180 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
4181 !Result.isStrictlyPositive()) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004182 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
4183 << "num_threads" << NumThreads->getSourceRange();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004184 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004185 }
4186 }
4187
Alexey Bataeved09d242014-05-28 05:53:51 +00004188 return new (Context)
4189 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00004190}
4191
Alexey Bataev62c87d22014-03-21 04:51:18 +00004192ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
4193 OpenMPClauseKind CKind) {
4194 if (!E)
4195 return ExprError();
4196 if (E->isValueDependent() || E->isTypeDependent() ||
4197 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004198 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004199 llvm::APSInt Result;
4200 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
4201 if (ICE.isInvalid())
4202 return ExprError();
4203 if (!Result.isStrictlyPositive()) {
4204 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
4205 << getOpenMPClauseName(CKind) << E->getSourceRange();
4206 return ExprError();
4207 }
Alexander Musman09184fe2014-09-30 05:29:28 +00004208 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
4209 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
4210 << E->getSourceRange();
4211 return ExprError();
4212 }
Alexey Bataev62c87d22014-03-21 04:51:18 +00004213 return ICE;
4214}
4215
4216OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
4217 SourceLocation LParenLoc,
4218 SourceLocation EndLoc) {
4219 // OpenMP [2.8.1, simd construct, Description]
4220 // The parameter of the safelen clause must be a constant
4221 // positive integer expression.
4222 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
4223 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004224 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004225 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004226 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00004227}
4228
Alexander Musman64d33f12014-06-04 07:53:32 +00004229OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
4230 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00004231 SourceLocation LParenLoc,
4232 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00004233 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004234 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00004235 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004236 // The parameter of the collapse clause must be a constant
4237 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00004238 ExprResult NumForLoopsResult =
4239 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
4240 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00004241 return nullptr;
4242 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00004243 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00004244}
4245
Alexey Bataeved09d242014-05-28 05:53:51 +00004246OMPClause *Sema::ActOnOpenMPSimpleClause(
4247 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
4248 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004249 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004250 switch (Kind) {
4251 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004252 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00004253 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
4254 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004255 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004256 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00004257 Res = ActOnOpenMPProcBindClause(
4258 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
4259 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004260 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004261 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004262 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004263 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004264 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004265 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004266 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004267 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004268 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004269 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004270 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004271 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004272 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004273 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004274 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004275 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004276 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004277 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004278 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004279 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004280 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004281 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004282 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004283 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004284 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004285 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004286 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004287 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004288 llvm_unreachable("Clause is not allowed.");
4289 }
4290 return Res;
4291}
4292
4293OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
4294 SourceLocation KindKwLoc,
4295 SourceLocation StartLoc,
4296 SourceLocation LParenLoc,
4297 SourceLocation EndLoc) {
4298 if (Kind == OMPC_DEFAULT_unknown) {
4299 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004300 static_assert(OMPC_DEFAULT_unknown > 0,
4301 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00004302 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004303 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004304 Values += "'";
4305 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
4306 Values += "'";
4307 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004308 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004309 Values += " or ";
4310 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004311 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004312 break;
4313 default:
4314 Values += Sep;
4315 break;
4316 }
4317 }
4318 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004319 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004320 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004321 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004322 switch (Kind) {
4323 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004324 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004325 break;
4326 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004327 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004328 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004329 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004330 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00004331 break;
4332 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004333 return new (Context)
4334 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004335}
4336
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004337OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
4338 SourceLocation KindKwLoc,
4339 SourceLocation StartLoc,
4340 SourceLocation LParenLoc,
4341 SourceLocation EndLoc) {
4342 if (Kind == OMPC_PROC_BIND_unknown) {
4343 std::string Values;
4344 std::string Sep(", ");
4345 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
4346 Values += "'";
4347 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
4348 Values += "'";
4349 switch (i) {
4350 case OMPC_PROC_BIND_unknown - 2:
4351 Values += " or ";
4352 break;
4353 case OMPC_PROC_BIND_unknown - 1:
4354 break;
4355 default:
4356 Values += Sep;
4357 break;
4358 }
4359 }
4360 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004361 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004362 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004363 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004364 return new (Context)
4365 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004366}
4367
Alexey Bataev56dafe82014-06-20 07:16:17 +00004368OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
4369 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
4370 SourceLocation StartLoc, SourceLocation LParenLoc,
4371 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
4372 SourceLocation EndLoc) {
4373 OMPClause *Res = nullptr;
4374 switch (Kind) {
4375 case OMPC_schedule:
4376 Res = ActOnOpenMPScheduleClause(
4377 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
4378 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
4379 break;
4380 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004381 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004382 case OMPC_num_threads:
4383 case OMPC_safelen:
4384 case OMPC_collapse:
4385 case OMPC_default:
4386 case OMPC_proc_bind:
4387 case OMPC_private:
4388 case OMPC_firstprivate:
4389 case OMPC_lastprivate:
4390 case OMPC_shared:
4391 case OMPC_reduction:
4392 case OMPC_linear:
4393 case OMPC_aligned:
4394 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004395 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004396 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004397 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004398 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004399 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004400 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004401 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004402 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004403 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004404 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004405 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004406 case OMPC_seq_cst:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004407 case OMPC_unknown:
4408 llvm_unreachable("Clause is not allowed.");
4409 }
4410 return Res;
4411}
4412
4413OMPClause *Sema::ActOnOpenMPScheduleClause(
4414 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
4415 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
4416 SourceLocation EndLoc) {
4417 if (Kind == OMPC_SCHEDULE_unknown) {
4418 std::string Values;
4419 std::string Sep(", ");
4420 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
4421 Values += "'";
4422 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
4423 Values += "'";
4424 switch (i) {
4425 case OMPC_SCHEDULE_unknown - 2:
4426 Values += " or ";
4427 break;
4428 case OMPC_SCHEDULE_unknown - 1:
4429 break;
4430 default:
4431 Values += Sep;
4432 break;
4433 }
4434 }
4435 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
4436 << Values << getOpenMPClauseName(OMPC_schedule);
4437 return nullptr;
4438 }
4439 Expr *ValExpr = ChunkSize;
4440 if (ChunkSize) {
4441 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
4442 !ChunkSize->isInstantiationDependent() &&
4443 !ChunkSize->containsUnexpandedParameterPack()) {
4444 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
4445 ExprResult Val =
4446 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
4447 if (Val.isInvalid())
4448 return nullptr;
4449
4450 ValExpr = Val.get();
4451
4452 // OpenMP [2.7.1, Restrictions]
4453 // chunk_size must be a loop invariant integer expression with a positive
4454 // value.
4455 llvm::APSInt Result;
4456 if (ValExpr->isIntegerConstantExpr(Result, Context) &&
4457 Result.isSigned() && !Result.isStrictlyPositive()) {
4458 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
4459 << "schedule" << ChunkSize->getSourceRange();
4460 return nullptr;
4461 }
4462 }
4463 }
4464
4465 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
4466 EndLoc, Kind, ValExpr);
4467}
4468
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004469OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
4470 SourceLocation StartLoc,
4471 SourceLocation EndLoc) {
4472 OMPClause *Res = nullptr;
4473 switch (Kind) {
4474 case OMPC_ordered:
4475 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
4476 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00004477 case OMPC_nowait:
4478 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
4479 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004480 case OMPC_untied:
4481 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
4482 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004483 case OMPC_mergeable:
4484 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
4485 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004486 case OMPC_read:
4487 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
4488 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00004489 case OMPC_write:
4490 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
4491 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004492 case OMPC_update:
4493 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
4494 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00004495 case OMPC_capture:
4496 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
4497 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004498 case OMPC_seq_cst:
4499 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
4500 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004501 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004502 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004503 case OMPC_num_threads:
4504 case OMPC_safelen:
4505 case OMPC_collapse:
4506 case OMPC_schedule:
4507 case OMPC_private:
4508 case OMPC_firstprivate:
4509 case OMPC_lastprivate:
4510 case OMPC_shared:
4511 case OMPC_reduction:
4512 case OMPC_linear:
4513 case OMPC_aligned:
4514 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004515 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004516 case OMPC_default:
4517 case OMPC_proc_bind:
4518 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004519 case OMPC_flush:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004520 case OMPC_unknown:
4521 llvm_unreachable("Clause is not allowed.");
4522 }
4523 return Res;
4524}
4525
4526OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
4527 SourceLocation EndLoc) {
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004528 DSAStack->setOrderedRegion();
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004529 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
4530}
4531
Alexey Bataev236070f2014-06-20 11:19:47 +00004532OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
4533 SourceLocation EndLoc) {
4534 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
4535}
4536
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004537OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
4538 SourceLocation EndLoc) {
4539 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
4540}
4541
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004542OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
4543 SourceLocation EndLoc) {
4544 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
4545}
4546
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004547OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
4548 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004549 return new (Context) OMPReadClause(StartLoc, EndLoc);
4550}
4551
Alexey Bataevdea47612014-07-23 07:46:59 +00004552OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
4553 SourceLocation EndLoc) {
4554 return new (Context) OMPWriteClause(StartLoc, EndLoc);
4555}
4556
Alexey Bataev67a4f222014-07-23 10:25:33 +00004557OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
4558 SourceLocation EndLoc) {
4559 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
4560}
4561
Alexey Bataev459dec02014-07-24 06:46:57 +00004562OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
4563 SourceLocation EndLoc) {
4564 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
4565}
4566
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004567OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
4568 SourceLocation EndLoc) {
4569 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
4570}
4571
Alexey Bataevc5e02582014-06-16 07:08:35 +00004572OMPClause *Sema::ActOnOpenMPVarListClause(
4573 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
4574 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
4575 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
4576 const DeclarationNameInfo &ReductionId) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004577 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004578 switch (Kind) {
4579 case OMPC_private:
4580 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4581 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004582 case OMPC_firstprivate:
4583 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4584 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00004585 case OMPC_lastprivate:
4586 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4587 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00004588 case OMPC_shared:
4589 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
4590 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00004591 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00004592 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
4593 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00004594 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00004595 case OMPC_linear:
4596 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
4597 ColonLoc, EndLoc);
4598 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004599 case OMPC_aligned:
4600 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
4601 ColonLoc, EndLoc);
4602 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004603 case OMPC_copyin:
4604 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
4605 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00004606 case OMPC_copyprivate:
4607 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4608 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004609 case OMPC_flush:
4610 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4611 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004612 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004613 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004614 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004615 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004616 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004617 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004618 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004619 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004620 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004621 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004622 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004623 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004624 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004625 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004626 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004627 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004628 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004629 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004630 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004631 llvm_unreachable("Clause is not allowed.");
4632 }
4633 return Res;
4634}
4635
4636OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
4637 SourceLocation StartLoc,
4638 SourceLocation LParenLoc,
4639 SourceLocation EndLoc) {
4640 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00004641 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00004642 for (auto &RefExpr : VarList) {
4643 assert(RefExpr && "NULL expr in OpenMP private clause.");
4644 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004645 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004646 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004647 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004648 continue;
4649 }
4650
Alexey Bataeved09d242014-05-28 05:53:51 +00004651 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004652 // OpenMP [2.1, C/C++]
4653 // A list item is a variable name.
4654 // OpenMP [2.9.3.3, Restrictions, p.1]
4655 // A variable that is part of another variable (as an array or
4656 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004657 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004658 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004659 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004660 continue;
4661 }
4662 Decl *D = DE->getDecl();
4663 VarDecl *VD = cast<VarDecl>(D);
4664
4665 QualType Type = VD->getType();
4666 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4667 // It will be analyzed later.
4668 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004669 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004670 continue;
4671 }
4672
4673 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4674 // A variable that appears in a private clause must not have an incomplete
4675 // type or a reference type.
4676 if (RequireCompleteType(ELoc, Type,
4677 diag::err_omp_private_incomplete_type)) {
4678 continue;
4679 }
4680 if (Type->isReferenceType()) {
4681 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00004682 << getOpenMPClauseName(OMPC_private) << Type;
4683 bool IsDecl =
4684 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4685 Diag(VD->getLocation(),
4686 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4687 << VD;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004688 continue;
4689 }
4690
4691 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
4692 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004693 // clause requires an accessible, unambiguous default constructor for the
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004694 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00004695 while (Type->isArrayType()) {
4696 Type = cast<ArrayType>(Type.getTypePtr())->getElementType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004697 }
4698
Alexey Bataev758e55e2013-09-06 18:03:48 +00004699 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4700 // in a Construct]
4701 // Variables with the predetermined data-sharing attributes may not be
4702 // listed in data-sharing attributes clauses, except for the cases
4703 // listed below. For these exceptions only, listing a predetermined
4704 // variable in a data-sharing attribute clause is allowed and overrides
4705 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004706 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004707 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004708 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4709 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004710 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004711 continue;
4712 }
4713
Alexey Bataev03b340a2014-10-21 03:16:40 +00004714 // Generate helper private variable and initialize it with the default
4715 // value. The address of the original variable is replaced by the address of
4716 // the new private variable in CodeGen. This new variable is not added to
4717 // IdResolver, so the code in the OpenMP region uses original variable for
4718 // proper diagnostics.
Alexey Bataev50a64582015-04-22 12:24:45 +00004719 auto VDPrivate = VarDecl::Create(Context, CurContext, DE->getLocStart(),
4720 DE->getExprLoc(), VD->getIdentifier(),
4721 VD->getType().getUnqualifiedType(),
4722 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004723 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto*/ false);
4724 if (VDPrivate->isInvalidDecl())
4725 continue;
4726 CurContext->addDecl(VDPrivate);
Alexey Bataev07649fb2014-12-16 08:01:48 +00004727 auto VDPrivateRefExpr =
4728 DeclRefExpr::Create(Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4729 /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004730 /*RefersToEnclosingVariableOrCapture*/ false,
Alexey Bataev07649fb2014-12-16 08:01:48 +00004731 /*NameLoc*/ SourceLocation(), DE->getType(),
4732 /*VK*/ VK_LValue);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004733
Alexey Bataev758e55e2013-09-06 18:03:48 +00004734 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004735 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004736 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004737 }
4738
Alexey Bataeved09d242014-05-28 05:53:51 +00004739 if (Vars.empty())
4740 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004741
Alexey Bataev03b340a2014-10-21 03:16:40 +00004742 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
4743 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004744}
4745
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004746namespace {
4747class DiagsUninitializedSeveretyRAII {
4748private:
4749 DiagnosticsEngine &Diags;
4750 SourceLocation SavedLoc;
4751 bool IsIgnored;
4752
4753public:
4754 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
4755 bool IsIgnored)
4756 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
4757 if (!IsIgnored) {
4758 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
4759 /*Map*/ diag::Severity::Ignored, Loc);
4760 }
4761 }
4762 ~DiagsUninitializedSeveretyRAII() {
4763 if (!IsIgnored)
4764 Diags.popMappings(SavedLoc);
4765 }
4766};
4767}
4768
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004769OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
4770 SourceLocation StartLoc,
4771 SourceLocation LParenLoc,
4772 SourceLocation EndLoc) {
4773 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004774 SmallVector<Expr *, 8> PrivateCopies;
4775 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004776 bool IsImplicitClause =
4777 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
4778 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
4779
Alexey Bataeved09d242014-05-28 05:53:51 +00004780 for (auto &RefExpr : VarList) {
4781 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
4782 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004783 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004784 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004785 PrivateCopies.push_back(nullptr);
4786 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004787 continue;
4788 }
4789
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004790 SourceLocation ELoc =
4791 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004792 // OpenMP [2.1, C/C++]
4793 // A list item is a variable name.
4794 // OpenMP [2.9.3.3, Restrictions, p.1]
4795 // A variable that is part of another variable (as an array or
4796 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004797 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004798 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004799 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004800 continue;
4801 }
4802 Decl *D = DE->getDecl();
4803 VarDecl *VD = cast<VarDecl>(D);
4804
4805 QualType Type = VD->getType();
4806 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4807 // It will be analyzed later.
4808 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004809 PrivateCopies.push_back(nullptr);
4810 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004811 continue;
4812 }
4813
4814 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4815 // A variable that appears in a private clause must not have an incomplete
4816 // type or a reference type.
4817 if (RequireCompleteType(ELoc, Type,
4818 diag::err_omp_firstprivate_incomplete_type)) {
4819 continue;
4820 }
4821 if (Type->isReferenceType()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004822 if (IsImplicitClause) {
4823 Diag(ImplicitClauseLoc,
4824 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
4825 << Type;
4826 Diag(RefExpr->getExprLoc(), diag::note_used_here);
4827 } else {
4828 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4829 << getOpenMPClauseName(OMPC_firstprivate) << Type;
4830 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004831 bool IsDecl =
4832 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4833 Diag(VD->getLocation(),
4834 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4835 << VD;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004836 continue;
4837 }
4838
4839 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
4840 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004841 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004842 // class type.
Alexey Bataev69c62a92015-04-15 04:52:20 +00004843 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004844
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004845 // If an implicit firstprivate variable found it was checked already.
4846 if (!IsImplicitClause) {
4847 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004848 Type = Type.getNonReferenceType().getCanonicalType();
4849 bool IsConstant = Type.isConstant(Context);
4850 Type = Context.getBaseElementType(Type);
4851 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
4852 // A list item that specifies a given variable may not appear in more
4853 // than one clause on the same directive, except that a variable may be
4854 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004855 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00004856 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004857 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004858 << getOpenMPClauseName(DVar.CKind)
4859 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004860 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004861 continue;
4862 }
4863
4864 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4865 // in a Construct]
4866 // Variables with the predetermined data-sharing attributes may not be
4867 // listed in data-sharing attributes clauses, except for the cases
4868 // listed below. For these exceptions only, listing a predetermined
4869 // variable in a data-sharing attribute clause is allowed and overrides
4870 // the variable's predetermined data-sharing attributes.
4871 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4872 // in a Construct, C/C++, p.2]
4873 // Variables with const-qualified type having no mutable member may be
4874 // listed in a firstprivate clause, even if they are static data members.
4875 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
4876 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
4877 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004878 << getOpenMPClauseName(DVar.CKind)
4879 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004880 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004881 continue;
4882 }
4883
Alexey Bataevf29276e2014-06-18 04:14:57 +00004884 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004885 // OpenMP [2.9.3.4, Restrictions, p.2]
4886 // A list item that is private within a parallel region must not appear
4887 // in a firstprivate clause on a worksharing construct if any of the
4888 // worksharing regions arising from the worksharing construct ever bind
4889 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00004890 if (isOpenMPWorksharingDirective(CurrDir) &&
4891 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004892 DVar = DSAStack->getImplicitDSA(VD, true);
4893 if (DVar.CKind != OMPC_shared &&
4894 (isOpenMPParallelDirective(DVar.DKind) ||
4895 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00004896 Diag(ELoc, diag::err_omp_required_access)
4897 << getOpenMPClauseName(OMPC_firstprivate)
4898 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004899 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004900 continue;
4901 }
4902 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004903 // OpenMP [2.9.3.4, Restrictions, p.3]
4904 // A list item that appears in a reduction clause of a parallel construct
4905 // must not appear in a firstprivate clause on a worksharing or task
4906 // construct if any of the worksharing or task regions arising from the
4907 // worksharing or task construct ever bind to any of the parallel regions
4908 // arising from the parallel construct.
4909 // OpenMP [2.9.3.4, Restrictions, p.4]
4910 // A list item that appears in a reduction clause in worksharing
4911 // construct must not appear in a firstprivate clause in a task construct
4912 // encountered during execution of any of the worksharing regions arising
4913 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004914 if (CurrDir == OMPD_task) {
4915 DVar =
4916 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
4917 [](OpenMPDirectiveKind K) -> bool {
4918 return isOpenMPParallelDirective(K) ||
4919 isOpenMPWorksharingDirective(K);
4920 },
4921 false);
4922 if (DVar.CKind == OMPC_reduction &&
4923 (isOpenMPParallelDirective(DVar.DKind) ||
4924 isOpenMPWorksharingDirective(DVar.DKind))) {
4925 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
4926 << getOpenMPDirectiveName(DVar.DKind);
4927 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4928 continue;
4929 }
4930 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004931 }
4932
Alexey Bataev69c62a92015-04-15 04:52:20 +00004933 auto VDPrivate =
4934 VarDecl::Create(Context, CurContext, DE->getLocStart(), ELoc,
4935 VD->getIdentifier(), VD->getType().getUnqualifiedType(),
4936 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004937 // Generate helper private variable and initialize it with the value of the
4938 // original variable. The address of the original variable is replaced by
4939 // the address of the new private variable in the CodeGen. This new variable
4940 // is not added to IdResolver, so the code in the OpenMP region uses
4941 // original variable for proper diagnostics and variable capturing.
4942 Expr *VDInitRefExpr = nullptr;
4943 // For arrays generate initializer for single element and replace it by the
4944 // original array element in CodeGen.
4945 if (DE->getType()->isArrayType()) {
4946 auto VDInit = VarDecl::Create(Context, CurContext, DE->getLocStart(),
4947 ELoc, VD->getIdentifier(), Type,
4948 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4949 CurContext->addHiddenDecl(VDInit);
4950 VDInitRefExpr = DeclRefExpr::Create(
4951 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4952 /*TemplateKWLoc*/ SourceLocation(), VDInit,
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004953 /*RefersToEnclosingVariableOrCapture*/ true, ELoc, Type,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004954 /*VK*/ VK_LValue);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004955 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataev69c62a92015-04-15 04:52:20 +00004956 auto *VDInitTemp =
4957 BuildVarDecl(*this, DE->getLocStart(), Type.getUnqualifiedType(),
4958 ".firstprivate.temp");
4959 InitializedEntity Entity =
4960 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004961 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
4962
4963 InitializationSequence InitSeq(*this, Entity, Kind, Init);
4964 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
4965 if (Result.isInvalid())
4966 VDPrivate->setInvalidDecl();
4967 else
4968 VDPrivate->setInit(Result.getAs<Expr>());
4969 } else {
Alexey Bataev69c62a92015-04-15 04:52:20 +00004970 auto *VDInit =
4971 BuildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
4972 VDInitRefExpr =
4973 BuildDeclRefExpr(VDInit, Type, VK_LValue, DE->getExprLoc()).get();
4974 AddInitializerToDecl(VDPrivate,
4975 DefaultLvalueConversion(VDInitRefExpr).get(),
4976 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004977 }
4978 if (VDPrivate->isInvalidDecl()) {
4979 if (IsImplicitClause) {
4980 Diag(DE->getExprLoc(),
4981 diag::note_omp_task_predetermined_firstprivate_here);
4982 }
4983 continue;
4984 }
4985 CurContext->addDecl(VDPrivate);
Alexey Bataev69c62a92015-04-15 04:52:20 +00004986 auto VDPrivateRefExpr = DeclRefExpr::Create(
4987 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4988 /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
4989 /*RefersToEnclosingVariableOrCapture*/ false, DE->getLocStart(),
4990 DE->getType().getUnqualifiedType(), /*VK*/ VK_LValue);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004991 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
4992 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004993 PrivateCopies.push_back(VDPrivateRefExpr);
4994 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004995 }
4996
Alexey Bataeved09d242014-05-28 05:53:51 +00004997 if (Vars.empty())
4998 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004999
5000 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005001 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005002}
5003
Alexander Musman1bb328c2014-06-04 13:06:39 +00005004OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
5005 SourceLocation StartLoc,
5006 SourceLocation LParenLoc,
5007 SourceLocation EndLoc) {
5008 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00005009 SmallVector<Expr *, 8> SrcExprs;
5010 SmallVector<Expr *, 8> DstExprs;
5011 SmallVector<Expr *, 8> AssignmentOps;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005012 for (auto &RefExpr : VarList) {
5013 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
5014 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5015 // It will be analyzed later.
5016 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00005017 SrcExprs.push_back(nullptr);
5018 DstExprs.push_back(nullptr);
5019 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005020 continue;
5021 }
5022
5023 SourceLocation ELoc = RefExpr->getExprLoc();
5024 // OpenMP [2.1, C/C++]
5025 // A list item is a variable name.
5026 // OpenMP [2.14.3.5, Restrictions, p.1]
5027 // A variable that is part of another variable (as an array or structure
5028 // element) cannot appear in a lastprivate clause.
5029 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5030 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5031 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5032 continue;
5033 }
5034 Decl *D = DE->getDecl();
5035 VarDecl *VD = cast<VarDecl>(D);
5036
5037 QualType Type = VD->getType();
5038 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5039 // It will be analyzed later.
5040 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005041 SrcExprs.push_back(nullptr);
5042 DstExprs.push_back(nullptr);
5043 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005044 continue;
5045 }
5046
5047 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
5048 // A variable that appears in a lastprivate clause must not have an
5049 // incomplete type or a reference type.
5050 if (RequireCompleteType(ELoc, Type,
5051 diag::err_omp_lastprivate_incomplete_type)) {
5052 continue;
5053 }
5054 if (Type->isReferenceType()) {
5055 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5056 << getOpenMPClauseName(OMPC_lastprivate) << Type;
5057 bool IsDecl =
5058 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5059 Diag(VD->getLocation(),
5060 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5061 << VD;
5062 continue;
5063 }
5064
5065 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5066 // in a Construct]
5067 // Variables with the predetermined data-sharing attributes may not be
5068 // listed in data-sharing attributes clauses, except for the cases
5069 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005070 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005071 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
5072 DVar.CKind != OMPC_firstprivate &&
5073 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5074 Diag(ELoc, diag::err_omp_wrong_dsa)
5075 << getOpenMPClauseName(DVar.CKind)
5076 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005077 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005078 continue;
5079 }
5080
Alexey Bataevf29276e2014-06-18 04:14:57 +00005081 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5082 // OpenMP [2.14.3.5, Restrictions, p.2]
5083 // A list item that is private within a parallel region, or that appears in
5084 // the reduction clause of a parallel construct, must not appear in a
5085 // lastprivate clause on a worksharing construct if any of the corresponding
5086 // worksharing regions ever binds to any of the corresponding parallel
5087 // regions.
Alexey Bataev549210e2014-06-24 04:39:47 +00005088 if (isOpenMPWorksharingDirective(CurrDir) &&
5089 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005090 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005091 if (DVar.CKind != OMPC_shared) {
5092 Diag(ELoc, diag::err_omp_required_access)
5093 << getOpenMPClauseName(OMPC_lastprivate)
5094 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005095 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005096 continue;
5097 }
5098 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00005099 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00005100 // A variable of class type (or array thereof) that appears in a
5101 // lastprivate clause requires an accessible, unambiguous default
5102 // constructor for the class type, unless the list item is also specified
5103 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00005104 // A variable of class type (or array thereof) that appears in a
5105 // lastprivate clause requires an accessible, unambiguous copy assignment
5106 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00005107 Type = Context.getBaseElementType(Type).getNonReferenceType();
5108 auto *SrcVD = BuildVarDecl(*this, DE->getLocStart(),
5109 Type.getUnqualifiedType(), ".lastprivate.src");
5110 auto *PseudoSrcExpr = BuildDeclRefExpr(SrcVD, Type.getUnqualifiedType(),
5111 VK_LValue, DE->getExprLoc()).get();
5112 auto *DstVD =
5113 BuildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst");
5114 auto *PseudoDstExpr =
5115 BuildDeclRefExpr(DstVD, Type, VK_LValue, DE->getExprLoc()).get();
5116 // For arrays generate assignment operation for single element and replace
5117 // it by the original array element in CodeGen.
5118 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
5119 PseudoDstExpr, PseudoSrcExpr);
5120 if (AssignmentOp.isInvalid())
5121 continue;
5122 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
5123 /*DiscardedValue=*/true);
5124 if (AssignmentOp.isInvalid())
5125 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005126
Alexey Bataevf29276e2014-06-18 04:14:57 +00005127 if (DVar.CKind != OMPC_firstprivate)
5128 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005129 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005130 SrcExprs.push_back(PseudoSrcExpr);
5131 DstExprs.push_back(PseudoDstExpr);
5132 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00005133 }
5134
5135 if (Vars.empty())
5136 return nullptr;
5137
5138 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00005139 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005140}
5141
Alexey Bataev758e55e2013-09-06 18:03:48 +00005142OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
5143 SourceLocation StartLoc,
5144 SourceLocation LParenLoc,
5145 SourceLocation EndLoc) {
5146 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00005147 for (auto &RefExpr : VarList) {
5148 assert(RefExpr && "NULL expr in OpenMP shared clause.");
5149 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00005150 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005151 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005152 continue;
5153 }
5154
Alexey Bataeved09d242014-05-28 05:53:51 +00005155 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005156 // OpenMP [2.1, C/C++]
5157 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00005158 // OpenMP [2.14.3.2, Restrictions, p.1]
5159 // A variable that is part of another variable (as an array or structure
5160 // element) cannot appear in a shared unless it is a static data member
5161 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00005162 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005163 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005164 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005165 continue;
5166 }
5167 Decl *D = DE->getDecl();
5168 VarDecl *VD = cast<VarDecl>(D);
5169
5170 QualType Type = VD->getType();
5171 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5172 // It will be analyzed later.
5173 Vars.push_back(DE);
5174 continue;
5175 }
5176
5177 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5178 // in a Construct]
5179 // Variables with the predetermined data-sharing attributes may not be
5180 // listed in data-sharing attributes clauses, except for the cases
5181 // listed below. For these exceptions only, listing a predetermined
5182 // variable in a data-sharing attribute clause is allowed and overrides
5183 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005184 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00005185 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
5186 DVar.RefExpr) {
5187 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5188 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005189 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005190 continue;
5191 }
5192
5193 DSAStack->addDSA(VD, DE, OMPC_shared);
5194 Vars.push_back(DE);
5195 }
5196
Alexey Bataeved09d242014-05-28 05:53:51 +00005197 if (Vars.empty())
5198 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00005199
5200 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5201}
5202
Alexey Bataevc5e02582014-06-16 07:08:35 +00005203namespace {
5204class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
5205 DSAStackTy *Stack;
5206
5207public:
5208 bool VisitDeclRefExpr(DeclRefExpr *E) {
5209 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005210 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005211 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
5212 return false;
5213 if (DVar.CKind != OMPC_unknown)
5214 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00005215 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005216 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005217 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00005218 return true;
5219 return false;
5220 }
5221 return false;
5222 }
5223 bool VisitStmt(Stmt *S) {
5224 for (auto Child : S->children()) {
5225 if (Child && Visit(Child))
5226 return true;
5227 }
5228 return false;
5229 }
Alexey Bataev23b69422014-06-18 07:08:49 +00005230 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00005231};
Alexey Bataev23b69422014-06-18 07:08:49 +00005232} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00005233
5234OMPClause *Sema::ActOnOpenMPReductionClause(
5235 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
5236 SourceLocation ColonLoc, SourceLocation EndLoc,
5237 CXXScopeSpec &ReductionIdScopeSpec,
5238 const DeclarationNameInfo &ReductionId) {
5239 // TODO: Allow scope specification search when 'declare reduction' is
5240 // supported.
5241 assert(ReductionIdScopeSpec.isEmpty() &&
5242 "No support for scoped reduction identifiers yet.");
5243
5244 auto DN = ReductionId.getName();
5245 auto OOK = DN.getCXXOverloadedOperator();
5246 BinaryOperatorKind BOK = BO_Comma;
5247
5248 // OpenMP [2.14.3.6, reduction clause]
5249 // C
5250 // reduction-identifier is either an identifier or one of the following
5251 // operators: +, -, *, &, |, ^, && and ||
5252 // C++
5253 // reduction-identifier is either an id-expression or one of the following
5254 // operators: +, -, *, &, |, ^, && and ||
5255 // FIXME: Only 'min' and 'max' identifiers are supported for now.
5256 switch (OOK) {
5257 case OO_Plus:
5258 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005259 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005260 break;
5261 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005262 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005263 break;
5264 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005265 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005266 break;
5267 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005268 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005269 break;
5270 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005271 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005272 break;
5273 case OO_AmpAmp:
5274 BOK = BO_LAnd;
5275 break;
5276 case OO_PipePipe:
5277 BOK = BO_LOr;
5278 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005279 case OO_New:
5280 case OO_Delete:
5281 case OO_Array_New:
5282 case OO_Array_Delete:
5283 case OO_Slash:
5284 case OO_Percent:
5285 case OO_Tilde:
5286 case OO_Exclaim:
5287 case OO_Equal:
5288 case OO_Less:
5289 case OO_Greater:
5290 case OO_LessEqual:
5291 case OO_GreaterEqual:
5292 case OO_PlusEqual:
5293 case OO_MinusEqual:
5294 case OO_StarEqual:
5295 case OO_SlashEqual:
5296 case OO_PercentEqual:
5297 case OO_CaretEqual:
5298 case OO_AmpEqual:
5299 case OO_PipeEqual:
5300 case OO_LessLess:
5301 case OO_GreaterGreater:
5302 case OO_LessLessEqual:
5303 case OO_GreaterGreaterEqual:
5304 case OO_EqualEqual:
5305 case OO_ExclaimEqual:
5306 case OO_PlusPlus:
5307 case OO_MinusMinus:
5308 case OO_Comma:
5309 case OO_ArrowStar:
5310 case OO_Arrow:
5311 case OO_Call:
5312 case OO_Subscript:
5313 case OO_Conditional:
5314 case NUM_OVERLOADED_OPERATORS:
5315 llvm_unreachable("Unexpected reduction identifier");
5316 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005317 if (auto II = DN.getAsIdentifierInfo()) {
5318 if (II->isStr("max"))
5319 BOK = BO_GT;
5320 else if (II->isStr("min"))
5321 BOK = BO_LT;
5322 }
5323 break;
5324 }
5325 SourceRange ReductionIdRange;
5326 if (ReductionIdScopeSpec.isValid()) {
5327 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
5328 }
5329 ReductionIdRange.setEnd(ReductionId.getEndLoc());
5330 if (BOK == BO_Comma) {
5331 // Not allowed reduction identifier is found.
5332 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
5333 << ReductionIdRange;
5334 return nullptr;
5335 }
5336
5337 SmallVector<Expr *, 8> Vars;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005338 SmallVector<Expr *, 8> LHSs;
5339 SmallVector<Expr *, 8> RHSs;
5340 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005341 for (auto RefExpr : VarList) {
5342 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
5343 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5344 // It will be analyzed later.
5345 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005346 LHSs.push_back(nullptr);
5347 RHSs.push_back(nullptr);
5348 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005349 continue;
5350 }
5351
5352 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5353 RefExpr->isInstantiationDependent() ||
5354 RefExpr->containsUnexpandedParameterPack()) {
5355 // It will be analyzed later.
5356 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005357 LHSs.push_back(nullptr);
5358 RHSs.push_back(nullptr);
5359 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005360 continue;
5361 }
5362
5363 auto ELoc = RefExpr->getExprLoc();
5364 auto ERange = RefExpr->getSourceRange();
5365 // OpenMP [2.1, C/C++]
5366 // A list item is a variable or array section, subject to the restrictions
5367 // specified in Section 2.4 on page 42 and in each of the sections
5368 // describing clauses and directives for which a list appears.
5369 // OpenMP [2.14.3.3, Restrictions, p.1]
5370 // A variable that is part of another variable (as an array or
5371 // structure element) cannot appear in a private clause.
5372 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
5373 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5374 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
5375 continue;
5376 }
5377 auto D = DE->getDecl();
5378 auto VD = cast<VarDecl>(D);
5379 auto Type = VD->getType();
5380 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5381 // A variable that appears in a private clause must not have an incomplete
5382 // type or a reference type.
5383 if (RequireCompleteType(ELoc, Type,
5384 diag::err_omp_reduction_incomplete_type))
5385 continue;
5386 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5387 // Arrays may not appear in a reduction clause.
5388 if (Type.getNonReferenceType()->isArrayType()) {
5389 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
5390 bool IsDecl =
5391 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5392 Diag(VD->getLocation(),
5393 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5394 << VD;
5395 continue;
5396 }
5397 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5398 // A list item that appears in a reduction clause must not be
5399 // const-qualified.
5400 if (Type.getNonReferenceType().isConstant(Context)) {
5401 Diag(ELoc, diag::err_omp_const_variable)
5402 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
5403 bool IsDecl =
5404 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5405 Diag(VD->getLocation(),
5406 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5407 << VD;
5408 continue;
5409 }
5410 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
5411 // If a list-item is a reference type then it must bind to the same object
5412 // for all threads of the team.
5413 VarDecl *VDDef = VD->getDefinition();
5414 if (Type->isReferenceType() && VDDef) {
5415 DSARefChecker Check(DSAStack);
5416 if (Check.Visit(VDDef->getInit())) {
5417 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
5418 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
5419 continue;
5420 }
5421 }
5422 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5423 // The type of a list item that appears in a reduction clause must be valid
5424 // for the reduction-identifier. For a max or min reduction in C, the type
5425 // of the list item must be an allowed arithmetic data type: char, int,
5426 // float, double, or _Bool, possibly modified with long, short, signed, or
5427 // unsigned. For a max or min reduction in C++, the type of the list item
5428 // must be an allowed arithmetic data type: char, wchar_t, int, float,
5429 // double, or bool, possibly modified with long, short, signed, or unsigned.
5430 if ((BOK == BO_GT || BOK == BO_LT) &&
5431 !(Type->isScalarType() ||
5432 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
5433 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
5434 << getLangOpts().CPlusPlus;
5435 bool IsDecl =
5436 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5437 Diag(VD->getLocation(),
5438 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5439 << VD;
5440 continue;
5441 }
5442 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
5443 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
5444 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
5445 bool IsDecl =
5446 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5447 Diag(VD->getLocation(),
5448 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5449 << VD;
5450 continue;
5451 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00005452 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5453 // in a Construct]
5454 // Variables with the predetermined data-sharing attributes may not be
5455 // listed in data-sharing attributes clauses, except for the cases
5456 // listed below. For these exceptions only, listing a predetermined
5457 // variable in a data-sharing attribute clause is allowed and overrides
5458 // the variable's predetermined data-sharing attributes.
5459 // OpenMP [2.14.3.6, Restrictions, p.3]
5460 // Any number of reduction clauses can be specified on the directive,
5461 // but a list item can appear only once in the reduction clauses for that
5462 // directive.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005463 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005464 if (DVar.CKind == OMPC_reduction) {
5465 Diag(ELoc, diag::err_omp_once_referenced)
5466 << getOpenMPClauseName(OMPC_reduction);
5467 if (DVar.RefExpr) {
5468 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
5469 }
5470 } else if (DVar.CKind != OMPC_unknown) {
5471 Diag(ELoc, diag::err_omp_wrong_dsa)
5472 << getOpenMPClauseName(DVar.CKind)
5473 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005474 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005475 continue;
5476 }
5477
5478 // OpenMP [2.14.3.6, Restrictions, p.1]
5479 // A list item that appears in a reduction clause of a worksharing
5480 // construct must be shared in the parallel regions to which any of the
5481 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf29276e2014-06-18 04:14:57 +00005482 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataev549210e2014-06-24 04:39:47 +00005483 if (isOpenMPWorksharingDirective(CurrDir) &&
5484 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005485 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005486 if (DVar.CKind != OMPC_shared) {
5487 Diag(ELoc, diag::err_omp_required_access)
5488 << getOpenMPClauseName(OMPC_reduction)
5489 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005490 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005491 continue;
5492 }
5493 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005494 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
5495 auto *LHSVD = BuildVarDecl(*this, ELoc, Type, ".reduction.lhs");
5496 auto *RHSVD = BuildVarDecl(*this, ELoc, Type, VD->getName());
5497 // Add initializer for private variable.
5498 Expr *Init = nullptr;
5499 switch (BOK) {
5500 case BO_Add:
5501 case BO_Xor:
5502 case BO_Or:
5503 case BO_LOr:
5504 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
5505 if (Type->isScalarType() || Type->isAnyComplexType()) {
5506 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005507 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005508 break;
5509 case BO_Mul:
5510 case BO_LAnd:
5511 if (Type->isScalarType() || Type->isAnyComplexType()) {
5512 // '*' and '&&' reduction ops - initializer is '1'.
5513 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
5514 }
5515 break;
5516 case BO_And: {
5517 // '&' reduction op - initializer is '~0'.
5518 QualType OrigType = Type;
5519 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
5520 Type = ComplexTy->getElementType();
5521 }
5522 if (Type->isRealFloatingType()) {
5523 llvm::APFloat InitValue =
5524 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
5525 /*isIEEE=*/true);
5526 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5527 Type, ELoc);
5528 } else if (Type->isScalarType()) {
5529 auto Size = Context.getTypeSize(Type);
5530 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
5531 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
5532 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5533 }
5534 if (Init && OrigType->isAnyComplexType()) {
5535 // Init = 0xFFFF + 0xFFFFi;
5536 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
5537 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
5538 }
5539 Type = OrigType;
5540 break;
5541 }
5542 case BO_LT:
5543 case BO_GT: {
5544 // 'min' reduction op - initializer is 'Largest representable number in
5545 // the reduction list item type'.
5546 // 'max' reduction op - initializer is 'Least representable number in
5547 // the reduction list item type'.
5548 if (Type->isIntegerType() || Type->isPointerType()) {
5549 bool IsSigned = Type->hasSignedIntegerRepresentation();
5550 auto Size = Context.getTypeSize(Type);
5551 QualType IntTy =
5552 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
5553 llvm::APInt InitValue =
5554 (BOK != BO_LT)
5555 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
5556 : llvm::APInt::getMinValue(Size)
5557 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
5558 : llvm::APInt::getMaxValue(Size);
5559 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5560 if (Type->isPointerType()) {
5561 // Cast to pointer type.
5562 auto CastExpr = BuildCStyleCastExpr(
5563 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
5564 SourceLocation(), Init);
5565 if (CastExpr.isInvalid())
5566 continue;
5567 Init = CastExpr.get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005568 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005569 } else if (Type->isRealFloatingType()) {
5570 llvm::APFloat InitValue = llvm::APFloat::getLargest(
5571 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
5572 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5573 Type, ELoc);
5574 }
5575 break;
5576 }
5577 case BO_PtrMemD:
5578 case BO_PtrMemI:
5579 case BO_MulAssign:
5580 case BO_Div:
5581 case BO_Rem:
5582 case BO_Sub:
5583 case BO_Shl:
5584 case BO_Shr:
5585 case BO_LE:
5586 case BO_GE:
5587 case BO_EQ:
5588 case BO_NE:
5589 case BO_AndAssign:
5590 case BO_XorAssign:
5591 case BO_OrAssign:
5592 case BO_Assign:
5593 case BO_AddAssign:
5594 case BO_SubAssign:
5595 case BO_DivAssign:
5596 case BO_RemAssign:
5597 case BO_ShlAssign:
5598 case BO_ShrAssign:
5599 case BO_Comma:
5600 llvm_unreachable("Unexpected reduction operation");
5601 }
5602 if (Init) {
5603 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
5604 /*TypeMayContainAuto=*/false);
5605 } else {
5606 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
5607 }
5608 if (!RHSVD->hasInit()) {
5609 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
5610 << ReductionIdRange;
5611 bool IsDecl =
5612 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5613 Diag(VD->getLocation(),
5614 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5615 << VD;
5616 continue;
5617 }
5618 auto *LHSDRE = BuildDeclRefExpr(LHSVD, Type, VK_LValue, ELoc).get();
5619 auto *RHSDRE = BuildDeclRefExpr(RHSVD, Type, VK_LValue, ELoc).get();
5620 ExprResult ReductionOp =
5621 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
5622 LHSDRE, RHSDRE);
5623 if (ReductionOp.isUsable()) {
5624 if (BOK != BO_LOr && BOK != BO_LAnd) {
5625 ReductionOp =
5626 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5627 BO_Assign, LHSDRE, ReductionOp.get());
5628 } else {
5629 auto *ConditionalOp = new (Context) ConditionalOperator(
5630 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
5631 RHSDRE, Type, VK_LValue, OK_Ordinary);
5632 ReductionOp =
5633 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5634 BO_Assign, LHSDRE, ConditionalOp);
5635 }
5636 if (ReductionOp.isUsable()) {
5637 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005638 }
5639 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005640 if (ReductionOp.isInvalid())
5641 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005642
5643 DSAStack->addDSA(VD, DE, OMPC_reduction);
5644 Vars.push_back(DE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005645 LHSs.push_back(LHSDRE);
5646 RHSs.push_back(RHSDRE);
5647 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005648 }
5649
5650 if (Vars.empty())
5651 return nullptr;
5652
5653 return OMPReductionClause::Create(
5654 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005655 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
5656 RHSs, ReductionOps);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005657}
5658
Alexander Musman8dba6642014-04-22 13:09:42 +00005659OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
5660 SourceLocation StartLoc,
5661 SourceLocation LParenLoc,
5662 SourceLocation ColonLoc,
5663 SourceLocation EndLoc) {
5664 SmallVector<Expr *, 8> Vars;
Alexander Musman3276a272015-03-21 10:12:56 +00005665 SmallVector<Expr *, 8> Inits;
Alexey Bataeved09d242014-05-28 05:53:51 +00005666 for (auto &RefExpr : VarList) {
5667 assert(RefExpr && "NULL expr in OpenMP linear clause.");
5668 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00005669 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005670 Vars.push_back(RefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00005671 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005672 continue;
5673 }
5674
5675 // OpenMP [2.14.3.7, linear clause]
5676 // A list item that appears in a linear clause is subject to the private
5677 // clause semantics described in Section 2.14.3.3 on page 159 except as
5678 // noted. In addition, the value of the new list item on each iteration
5679 // of the associated loop(s) corresponds to the value of the original
5680 // list item before entering the construct plus the logical number of
5681 // the iteration times linear-step.
5682
Alexey Bataeved09d242014-05-28 05:53:51 +00005683 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00005684 // OpenMP [2.1, C/C++]
5685 // A list item is a variable name.
5686 // OpenMP [2.14.3.3, Restrictions, p.1]
5687 // A variable that is part of another variable (as an array or
5688 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005689 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005690 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005691 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00005692 continue;
5693 }
5694
5695 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5696
5697 // OpenMP [2.14.3.7, linear clause]
5698 // A list-item cannot appear in more than one linear clause.
5699 // A list-item that appears in a linear clause cannot appear in any
5700 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005701 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00005702 if (DVar.RefExpr) {
5703 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5704 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005705 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00005706 continue;
5707 }
5708
5709 QualType QType = VD->getType();
5710 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
5711 // It will be analyzed later.
5712 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005713 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005714 continue;
5715 }
5716
5717 // A variable must not have an incomplete type or a reference type.
5718 if (RequireCompleteType(ELoc, QType,
5719 diag::err_omp_linear_incomplete_type)) {
5720 continue;
5721 }
5722 if (QType->isReferenceType()) {
5723 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5724 << getOpenMPClauseName(OMPC_linear) << QType;
5725 bool IsDecl =
5726 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5727 Diag(VD->getLocation(),
5728 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5729 << VD;
5730 continue;
5731 }
5732
5733 // A list item must not be const-qualified.
5734 if (QType.isConstant(Context)) {
5735 Diag(ELoc, diag::err_omp_const_variable)
5736 << getOpenMPClauseName(OMPC_linear);
5737 bool IsDecl =
5738 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5739 Diag(VD->getLocation(),
5740 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5741 << VD;
5742 continue;
5743 }
5744
5745 // A list item must be of integral or pointer type.
5746 QType = QType.getUnqualifiedType().getCanonicalType();
5747 const Type *Ty = QType.getTypePtrOrNull();
5748 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
5749 !Ty->isPointerType())) {
5750 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
5751 bool IsDecl =
5752 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5753 Diag(VD->getLocation(),
5754 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5755 << VD;
5756 continue;
5757 }
5758
Alexander Musman3276a272015-03-21 10:12:56 +00005759 // Build var to save initial value.
5760 VarDecl *Init = BuildVarDecl(*this, ELoc, DE->getType(), ".linear.start");
5761 AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
5762 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
5763 CurContext->addDecl(Init);
5764 Init->setIsUsed();
5765 auto InitRef = DeclRefExpr::Create(
5766 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
5767 /*TemplateKWLoc*/ SourceLocation(), Init,
5768 /*isEnclosingLocal*/ false, DE->getLocStart(), DE->getType(),
5769 /*VK*/ VK_LValue);
Alexander Musman8dba6642014-04-22 13:09:42 +00005770 DSAStack->addDSA(VD, DE, OMPC_linear);
5771 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005772 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00005773 }
5774
5775 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005776 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005777
5778 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00005779 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005780 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5781 !Step->isInstantiationDependent() &&
5782 !Step->containsUnexpandedParameterPack()) {
5783 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005784 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00005785 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005786 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005787 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00005788
Alexander Musman3276a272015-03-21 10:12:56 +00005789 // Build var to save the step value.
5790 VarDecl *SaveVar =
5791 BuildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
5792 CurContext->addDecl(SaveVar);
5793 SaveVar->setIsUsed();
5794 ExprResult SaveRef =
5795 BuildDeclRefExpr(SaveVar, StepExpr->getType(), VK_LValue, StepLoc);
5796 ExprResult CalcStep =
5797 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
5798
Alexander Musman8dba6642014-04-22 13:09:42 +00005799 // Warn about zero linear step (it would be probably better specified as
5800 // making corresponding variables 'const').
5801 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00005802 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
5803 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00005804 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
5805 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00005806 if (!IsConstant && CalcStep.isUsable()) {
5807 // Calculate the step beforehand instead of doing this on each iteration.
5808 // (This is not used if the number of iterations may be kfold-ed).
5809 CalcStepExpr = CalcStep.get();
5810 }
Alexander Musman8dba6642014-04-22 13:09:42 +00005811 }
5812
5813 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
Alexander Musman3276a272015-03-21 10:12:56 +00005814 Vars, Inits, StepExpr, CalcStepExpr);
5815}
5816
5817static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
5818 Expr *NumIterations, Sema &SemaRef,
5819 Scope *S) {
5820 // Walk the vars and build update/final expressions for the CodeGen.
5821 SmallVector<Expr *, 8> Updates;
5822 SmallVector<Expr *, 8> Finals;
5823 Expr *Step = Clause.getStep();
5824 Expr *CalcStep = Clause.getCalcStep();
5825 // OpenMP [2.14.3.7, linear clause]
5826 // If linear-step is not specified it is assumed to be 1.
5827 if (Step == nullptr)
5828 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5829 else if (CalcStep)
5830 Step = cast<BinaryOperator>(CalcStep)->getLHS();
5831 bool HasErrors = false;
5832 auto CurInit = Clause.inits().begin();
5833 for (auto &RefExpr : Clause.varlists()) {
5834 Expr *InitExpr = *CurInit;
5835
5836 // Build privatized reference to the current linear var.
5837 auto DE = cast<DeclRefExpr>(RefExpr);
5838 auto PrivateRef = DeclRefExpr::Create(
5839 SemaRef.Context, /*QualifierLoc*/ DE->getQualifierLoc(),
5840 /*TemplateKWLoc*/ SourceLocation(), DE->getDecl(),
5841 /* RefersToEnclosingVariableOrCapture */ true, DE->getLocStart(),
5842 DE->getType(), /*VK*/ VK_LValue);
5843
5844 // Build update: Var = InitExpr + IV * Step
5845 ExprResult Update =
5846 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
5847 InitExpr, IV, Step, /* Subtract */ false);
5848 Update = SemaRef.ActOnFinishFullExpr(Update.get());
5849
5850 // Build final: Var = InitExpr + NumIterations * Step
5851 ExprResult Final =
5852 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), RefExpr, InitExpr,
5853 NumIterations, Step, /* Subtract */ false);
5854 Final = SemaRef.ActOnFinishFullExpr(Final.get());
5855 if (!Update.isUsable() || !Final.isUsable()) {
5856 Updates.push_back(nullptr);
5857 Finals.push_back(nullptr);
5858 HasErrors = true;
5859 } else {
5860 Updates.push_back(Update.get());
5861 Finals.push_back(Final.get());
5862 }
5863 ++CurInit;
5864 }
5865 Clause.setUpdates(Updates);
5866 Clause.setFinals(Finals);
5867 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00005868}
5869
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005870OMPClause *Sema::ActOnOpenMPAlignedClause(
5871 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
5872 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
5873
5874 SmallVector<Expr *, 8> Vars;
5875 for (auto &RefExpr : VarList) {
5876 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
5877 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5878 // It will be analyzed later.
5879 Vars.push_back(RefExpr);
5880 continue;
5881 }
5882
5883 SourceLocation ELoc = RefExpr->getExprLoc();
5884 // OpenMP [2.1, C/C++]
5885 // A list item is a variable name.
5886 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5887 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5888 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5889 continue;
5890 }
5891
5892 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5893
5894 // OpenMP [2.8.1, simd construct, Restrictions]
5895 // The type of list items appearing in the aligned clause must be
5896 // array, pointer, reference to array, or reference to pointer.
5897 QualType QType = DE->getType()
5898 .getNonReferenceType()
5899 .getUnqualifiedType()
5900 .getCanonicalType();
5901 const Type *Ty = QType.getTypePtrOrNull();
5902 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
5903 !Ty->isPointerType())) {
5904 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
5905 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
5906 bool IsDecl =
5907 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5908 Diag(VD->getLocation(),
5909 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5910 << VD;
5911 continue;
5912 }
5913
5914 // OpenMP [2.8.1, simd construct, Restrictions]
5915 // A list-item cannot appear in more than one aligned clause.
5916 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
5917 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
5918 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
5919 << getOpenMPClauseName(OMPC_aligned);
5920 continue;
5921 }
5922
5923 Vars.push_back(DE);
5924 }
5925
5926 // OpenMP [2.8.1, simd construct, Description]
5927 // The parameter of the aligned clause, alignment, must be a constant
5928 // positive integer expression.
5929 // If no optional parameter is specified, implementation-defined default
5930 // alignments for SIMD instructions on the target platforms are assumed.
5931 if (Alignment != nullptr) {
5932 ExprResult AlignResult =
5933 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
5934 if (AlignResult.isInvalid())
5935 return nullptr;
5936 Alignment = AlignResult.get();
5937 }
5938 if (Vars.empty())
5939 return nullptr;
5940
5941 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
5942 EndLoc, Vars, Alignment);
5943}
5944
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005945OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
5946 SourceLocation StartLoc,
5947 SourceLocation LParenLoc,
5948 SourceLocation EndLoc) {
5949 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00005950 SmallVector<Expr *, 8> SrcExprs;
5951 SmallVector<Expr *, 8> DstExprs;
5952 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00005953 for (auto &RefExpr : VarList) {
5954 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
5955 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005956 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005957 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00005958 SrcExprs.push_back(nullptr);
5959 DstExprs.push_back(nullptr);
5960 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005961 continue;
5962 }
5963
Alexey Bataeved09d242014-05-28 05:53:51 +00005964 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005965 // OpenMP [2.1, C/C++]
5966 // A list item is a variable name.
5967 // OpenMP [2.14.4.1, Restrictions, p.1]
5968 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00005969 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005970 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005971 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005972 continue;
5973 }
5974
5975 Decl *D = DE->getDecl();
5976 VarDecl *VD = cast<VarDecl>(D);
5977
5978 QualType Type = VD->getType();
5979 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5980 // It will be analyzed later.
5981 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00005982 SrcExprs.push_back(nullptr);
5983 DstExprs.push_back(nullptr);
5984 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005985 continue;
5986 }
5987
5988 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
5989 // A list item that appears in a copyin clause must be threadprivate.
5990 if (!DSAStack->isThreadPrivate(VD)) {
5991 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00005992 << getOpenMPClauseName(OMPC_copyin)
5993 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005994 continue;
5995 }
5996
5997 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
5998 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00005999 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006000 // operator for the class type.
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006001 Type = Context.getBaseElementType(Type).getNonReferenceType();
6002 auto *SrcVD = BuildVarDecl(*this, DE->getLocStart(),
6003 Type.getUnqualifiedType(), ".copyin.src");
6004 auto *PseudoSrcExpr = BuildDeclRefExpr(SrcVD, Type.getUnqualifiedType(),
6005 VK_LValue, DE->getExprLoc())
6006 .get();
6007 auto *DstVD = BuildVarDecl(*this, DE->getLocStart(), Type, ".copyin.dst");
6008 auto *PseudoDstExpr =
6009 BuildDeclRefExpr(DstVD, Type, VK_LValue, DE->getExprLoc()).get();
6010 // For arrays generate assignment operation for single element and replace
6011 // it by the original array element in CodeGen.
6012 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6013 PseudoDstExpr, PseudoSrcExpr);
6014 if (AssignmentOp.isInvalid())
6015 continue;
6016 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6017 /*DiscardedValue=*/true);
6018 if (AssignmentOp.isInvalid())
6019 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006020
6021 DSAStack->addDSA(VD, DE, OMPC_copyin);
6022 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006023 SrcExprs.push_back(PseudoSrcExpr);
6024 DstExprs.push_back(PseudoDstExpr);
6025 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006026 }
6027
Alexey Bataeved09d242014-05-28 05:53:51 +00006028 if (Vars.empty())
6029 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006030
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006031 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
6032 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006033}
6034
Alexey Bataevbae9a792014-06-27 10:37:06 +00006035OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
6036 SourceLocation StartLoc,
6037 SourceLocation LParenLoc,
6038 SourceLocation EndLoc) {
6039 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00006040 SmallVector<Expr *, 8> SrcExprs;
6041 SmallVector<Expr *, 8> DstExprs;
6042 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006043 for (auto &RefExpr : VarList) {
6044 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
6045 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6046 // It will be analyzed later.
6047 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006048 SrcExprs.push_back(nullptr);
6049 DstExprs.push_back(nullptr);
6050 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006051 continue;
6052 }
6053
6054 SourceLocation ELoc = RefExpr->getExprLoc();
6055 // OpenMP [2.1, C/C++]
6056 // A list item is a variable name.
6057 // OpenMP [2.14.4.1, Restrictions, p.1]
6058 // A list item that appears in a copyin clause must be threadprivate.
6059 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6060 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6061 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6062 continue;
6063 }
6064
6065 Decl *D = DE->getDecl();
6066 VarDecl *VD = cast<VarDecl>(D);
6067
6068 QualType Type = VD->getType();
6069 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6070 // It will be analyzed later.
6071 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006072 SrcExprs.push_back(nullptr);
6073 DstExprs.push_back(nullptr);
6074 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006075 continue;
6076 }
6077
6078 // OpenMP [2.14.4.2, Restrictions, p.2]
6079 // A list item that appears in a copyprivate clause may not appear in a
6080 // private or firstprivate clause on the single construct.
6081 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006082 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006083 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
6084 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00006085 Diag(ELoc, diag::err_omp_wrong_dsa)
6086 << getOpenMPClauseName(DVar.CKind)
6087 << getOpenMPClauseName(OMPC_copyprivate);
6088 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6089 continue;
6090 }
6091
6092 // OpenMP [2.11.4.2, Restrictions, p.1]
6093 // All list items that appear in a copyprivate clause must be either
6094 // threadprivate or private in the enclosing context.
6095 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006096 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006097 if (DVar.CKind == OMPC_shared) {
6098 Diag(ELoc, diag::err_omp_required_access)
6099 << getOpenMPClauseName(OMPC_copyprivate)
6100 << "threadprivate or private in the enclosing context";
6101 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6102 continue;
6103 }
6104 }
6105 }
6106
6107 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6108 // A variable of class type (or array thereof) that appears in a
6109 // copyin clause requires an accessible, unambiguous copy assignment
6110 // operator for the class type.
Alexey Bataev420d45b2015-04-14 05:11:24 +00006111 Type = Context.getBaseElementType(Type).getUnqualifiedType();
6112 auto *SrcVD =
6113 BuildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src");
6114 auto *PseudoSrcExpr =
6115 BuildDeclRefExpr(SrcVD, Type, VK_LValue, DE->getExprLoc()).get();
6116 auto *DstVD =
6117 BuildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst");
6118 auto *PseudoDstExpr =
6119 BuildDeclRefExpr(DstVD, Type, VK_LValue, DE->getExprLoc()).get();
Alexey Bataeva63048e2015-03-23 06:18:07 +00006120 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6121 PseudoDstExpr, PseudoSrcExpr);
6122 if (AssignmentOp.isInvalid())
6123 continue;
6124 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6125 /*DiscardedValue=*/true);
6126 if (AssignmentOp.isInvalid())
6127 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006128
6129 // No need to mark vars as copyprivate, they are already threadprivate or
6130 // implicitly private.
6131 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006132 SrcExprs.push_back(PseudoSrcExpr);
6133 DstExprs.push_back(PseudoDstExpr);
6134 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00006135 }
6136
6137 if (Vars.empty())
6138 return nullptr;
6139
Alexey Bataeva63048e2015-03-23 06:18:07 +00006140 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6141 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006142}
6143
Alexey Bataev6125da92014-07-21 11:26:11 +00006144OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
6145 SourceLocation StartLoc,
6146 SourceLocation LParenLoc,
6147 SourceLocation EndLoc) {
6148 if (VarList.empty())
6149 return nullptr;
6150
6151 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
6152}
Alexey Bataevdea47612014-07-23 07:46:59 +00006153