blob: dd3ff37c37baaa6b57c4d8021f76ad88bcb3b96b [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 Bataev9c821032015-04-30 04:23:23 +000085 typedef llvm::DenseSet<VarDecl *> LoopControlVariablesSetTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000086
87 struct SharingMapTy {
88 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000089 AlignedMapTy AlignedMap;
Alexey Bataev9c821032015-04-30 04:23:23 +000090 LoopControlVariablesSetTy LCVSet;
Alexey Bataev758e55e2013-09-06 18:03:48 +000091 DefaultDataSharingAttributes DefaultAttr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000092 SourceLocation DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +000093 OpenMPDirectiveKind Directive;
94 DeclarationNameInfo DirectiveName;
95 Scope *CurScope;
Alexey Bataevbae9a792014-06-27 10:37:06 +000096 SourceLocation ConstructLoc;
Alexey Bataev9fb6e642014-07-22 06:45:04 +000097 bool OrderedRegion;
Alexey Bataev9c821032015-04-30 04:23:23 +000098 unsigned CollapseNumber;
Alexey Bataev13314bf2014-10-09 04:18:56 +000099 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000100 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000101 Scope *CurScope, SourceLocation Loc)
Alexey Bataev9c821032015-04-30 04:23:23 +0000102 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000103 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
Alexey Bataev9c821032015-04-30 04:23:23 +0000104 ConstructLoc(Loc), OrderedRegion(false), CollapseNumber(1),
105 InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000106 SharingMapTy()
Alexey Bataev9c821032015-04-30 04:23:23 +0000107 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000108 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
Alexey Bataev9c821032015-04-30 04:23:23 +0000109 ConstructLoc(), OrderedRegion(false), CollapseNumber(1),
110 InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000111 };
112
113 typedef SmallVector<SharingMapTy, 64> StackTy;
114
115 /// \brief Stack of used declaration and their data-sharing attributes.
116 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000117 /// \brief true, if check for DSA must be from parent directive, false, if
118 /// from current directive.
119 bool FromParent;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000120 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000121
122 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
123
124 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000125
126 /// \brief Checks if the variable is a local for OpenMP region.
127 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000128
Alexey Bataev758e55e2013-09-06 18:03:48 +0000129public:
Alexey Bataev39f915b82015-05-08 10:41:21 +0000130 explicit DSAStackTy(Sema &S) : Stack(1), FromParent(false), SemaRef(S) {}
131
132 bool isFromParent() const { return FromParent; }
133 void setFromParent(bool Flag) { FromParent = Flag; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000134
135 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000136 Scope *CurScope, SourceLocation Loc) {
137 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
138 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000139 }
140
141 void pop() {
142 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
143 Stack.pop_back();
144 }
145
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000146 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000147 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000148 /// for diagnostics.
149 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
150
Alexey Bataev9c821032015-04-30 04:23:23 +0000151 /// \brief Register specified variable as loop control variable.
152 void addLoopControlVariable(VarDecl *D);
153 /// \brief Check if the specified variable is a loop control variable for
154 /// current region.
155 bool isLoopControlVariable(VarDecl *D);
156
Alexey Bataev758e55e2013-09-06 18:03:48 +0000157 /// \brief Adds explicit data sharing attribute to the specified declaration.
158 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
159
Alexey Bataev758e55e2013-09-06 18:03:48 +0000160 /// \brief Returns data sharing attributes from top of the stack for the
161 /// specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000162 DSAVarData getTopDSA(VarDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000163 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000164 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000165 /// \brief Checks if the specified variables has data-sharing attributes which
166 /// match specified \a CPred predicate in any directive which matches \a DPred
167 /// predicate.
168 template <class ClausesPredicate, class DirectivesPredicate>
169 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000170 DirectivesPredicate DPred, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000171 /// \brief Checks if the specified variables has data-sharing attributes which
172 /// match specified \a CPred predicate in any innermost directive which
173 /// matches \a DPred predicate.
174 template <class ClausesPredicate, class DirectivesPredicate>
175 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000176 DirectivesPredicate DPred,
177 bool FromParent);
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000178 /// \brief Finds a directive which matches specified \a DPred predicate.
179 template <class NamedDirectivesPredicate>
180 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000181
Alexey Bataev758e55e2013-09-06 18:03:48 +0000182 /// \brief Returns currently analyzed directive.
183 OpenMPDirectiveKind getCurrentDirective() const {
184 return Stack.back().Directive;
185 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000186 /// \brief Returns parent directive.
187 OpenMPDirectiveKind getParentDirective() const {
188 if (Stack.size() > 2)
189 return Stack[Stack.size() - 2].Directive;
190 return OMPD_unknown;
191 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000192
193 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000194 void setDefaultDSANone(SourceLocation Loc) {
195 Stack.back().DefaultAttr = DSA_none;
196 Stack.back().DefaultAttrLoc = Loc;
197 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000198 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000199 void setDefaultDSAShared(SourceLocation Loc) {
200 Stack.back().DefaultAttr = DSA_shared;
201 Stack.back().DefaultAttrLoc = Loc;
202 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000203
204 DefaultDataSharingAttributes getDefaultDSA() const {
205 return Stack.back().DefaultAttr;
206 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000207 SourceLocation getDefaultDSALocation() const {
208 return Stack.back().DefaultAttrLoc;
209 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000210
Alexey Bataevf29276e2014-06-18 04:14:57 +0000211 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000212 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000213 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000214 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000215 }
216
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000217 /// \brief Marks current region as ordered (it has an 'ordered' clause).
218 void setOrderedRegion(bool IsOrdered = true) {
219 Stack.back().OrderedRegion = IsOrdered;
220 }
221 /// \brief Returns true, if parent region is ordered (has associated
222 /// 'ordered' clause), false - otherwise.
223 bool isParentOrderedRegion() const {
224 if (Stack.size() > 2)
225 return Stack[Stack.size() - 2].OrderedRegion;
226 return false;
227 }
228
Alexey Bataev9c821032015-04-30 04:23:23 +0000229 /// \brief Set collapse value for the region.
230 void setCollapseNumber(unsigned Val) { Stack.back().CollapseNumber = Val; }
231 /// \brief Return collapse value for region.
232 unsigned getCollapseNumber() const {
233 return Stack.back().CollapseNumber;
234 }
235
Alexey Bataev13314bf2014-10-09 04:18:56 +0000236 /// \brief Marks current target region as one with closely nested teams
237 /// region.
238 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
239 if (Stack.size() > 2)
240 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
241 }
242 /// \brief Returns true, if current region has closely nested teams region.
243 bool hasInnerTeamsRegion() const {
244 return getInnerTeamsRegionLoc().isValid();
245 }
246 /// \brief Returns location of the nested teams region (if any).
247 SourceLocation getInnerTeamsRegionLoc() const {
248 if (Stack.size() > 1)
249 return Stack.back().InnerTeamsRegionLoc;
250 return SourceLocation();
251 }
252
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000253 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000254 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000255 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000256};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000257bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
258 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
Alexey Bataev13314bf2014-10-09 04:18:56 +0000259 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000260}
Alexey Bataeved09d242014-05-28 05:53:51 +0000261} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000262
263DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
264 VarDecl *D) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000265 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000266 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000267 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000268 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
269 // in a region but not in construct]
270 // File-scope or namespace-scope variables referenced in called routines
271 // in the region are shared unless they appear in a threadprivate
272 // directive.
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000273 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000274 DVar.CKind = OMPC_shared;
275
276 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
277 // in a region but not in construct]
278 // Variables with static storage duration that are declared in called
279 // routines in the region are shared.
280 if (D->hasGlobalStorage())
281 DVar.CKind = OMPC_shared;
282
Alexey Bataev758e55e2013-09-06 18:03:48 +0000283 return DVar;
284 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000285
Alexey Bataev758e55e2013-09-06 18:03:48 +0000286 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000287 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
288 // in a Construct, C/C++, predetermined, p.1]
289 // Variables with automatic storage duration that are declared in a scope
290 // inside the construct are private.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000291 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
292 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
293 DVar.CKind = OMPC_private;
294 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000295 }
296
Alexey Bataev758e55e2013-09-06 18:03:48 +0000297 // Explicitly specified attributes and local variables with predetermined
298 // attributes.
299 if (Iter->SharingMap.count(D)) {
300 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
301 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000302 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000303 return DVar;
304 }
305
306 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
307 // in a Construct, C/C++, implicitly determined, p.1]
308 // In a parallel or task construct, the data-sharing attributes of these
309 // variables are determined by the default clause, if present.
310 switch (Iter->DefaultAttr) {
311 case DSA_shared:
312 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000313 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000314 return DVar;
315 case DSA_none:
316 return DVar;
317 case DSA_unspecified:
318 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
319 // in a Construct, implicitly determined, p.2]
320 // In a parallel construct, if no default clause is present, these
321 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000322 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000323 if (isOpenMPParallelDirective(DVar.DKind) ||
324 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000325 DVar.CKind = OMPC_shared;
326 return DVar;
327 }
328
329 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
330 // in a Construct, implicitly determined, p.4]
331 // In a task construct, if no default clause is present, a variable that in
332 // the enclosing context is determined to be shared by all implicit tasks
333 // bound to the current team is shared.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000334 if (DVar.DKind == OMPD_task) {
335 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000336 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000337 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000338 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
339 // Referenced
Alexey Bataev758e55e2013-09-06 18:03:48 +0000340 // in a Construct, implicitly determined, p.6]
341 // In a task construct, if no default clause is present, a variable
342 // whose data-sharing attribute is not determined by the rules above is
343 // firstprivate.
344 DVarTemp = getDSA(I, D);
345 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000346 DVar.RefExpr = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000347 DVar.DKind = OMPD_task;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000348 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000349 return DVar;
350 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000351 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000352 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000353 }
354 DVar.DKind = OMPD_task;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000355 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000356 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000357 return DVar;
358 }
359 }
360 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
361 // in a Construct, implicitly determined, p.3]
362 // For constructs other than task, if no default clause is present, these
363 // variables inherit their data-sharing attributes from the enclosing
364 // context.
Benjamin Kramer167e9992014-03-02 12:20:24 +0000365 return getDSA(std::next(Iter), D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000366}
367
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000368DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
369 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000370 D = D->getCanonicalDecl();
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000371 auto It = Stack.back().AlignedMap.find(D);
372 if (It == Stack.back().AlignedMap.end()) {
373 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
374 Stack.back().AlignedMap[D] = NewDE;
375 return nullptr;
376 } else {
377 assert(It->second && "Unexpected nullptr expr in the aligned map");
378 return It->second;
379 }
380 return nullptr;
381}
382
Alexey Bataev9c821032015-04-30 04:23:23 +0000383void DSAStackTy::addLoopControlVariable(VarDecl *D) {
384 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
385 D = D->getCanonicalDecl();
386 Stack.back().LCVSet.insert(D);
387}
388
389bool DSAStackTy::isLoopControlVariable(VarDecl *D) {
390 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
391 D = D->getCanonicalDecl();
392 return Stack.back().LCVSet.count(D) > 0;
393}
394
Alexey Bataev758e55e2013-09-06 18:03:48 +0000395void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000396 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000397 if (A == OMPC_threadprivate) {
398 Stack[0].SharingMap[D].Attributes = A;
399 Stack[0].SharingMap[D].RefExpr = E;
400 } else {
401 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
402 Stack.back().SharingMap[D].Attributes = A;
403 Stack.back().SharingMap[D].RefExpr = E;
404 }
405}
406
Alexey Bataeved09d242014-05-28 05:53:51 +0000407bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000408 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000409 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000410 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000411 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000412 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000413 ++I;
414 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000415 if (I == E)
416 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000417 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000418 Scope *CurScope = getCurScope();
419 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000420 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000421 }
422 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000423 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000424 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000425}
426
Alexey Bataev39f915b82015-05-08 10:41:21 +0000427/// \brief Build a variable declaration for OpenMP loop iteration variable.
428static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
429 StringRef Name) {
430 DeclContext *DC = SemaRef.CurContext;
431 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
432 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
433 VarDecl *Decl =
434 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
435 Decl->setImplicit();
436 return Decl;
437}
438
439static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
440 SourceLocation Loc,
441 bool RefersToCapture = false) {
442 D->setReferenced();
443 D->markUsed(S.Context);
444 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
445 SourceLocation(), D, RefersToCapture, Loc, Ty,
446 VK_LValue);
447}
448
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000449DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000450 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000451 DSAVarData DVar;
452
453 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
454 // in a Construct, C/C++, predetermined, p.1]
455 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev26a39242015-01-13 03:35:30 +0000456 if (D->getTLSKind() != VarDecl::TLS_None ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +0000457 (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() &&
458 !D->isLocalVarDecl())) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000459 addDSA(D, buildDeclRefExpr(SemaRef, D, D->getType().getNonReferenceType(),
460 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000461 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000462 }
463 if (Stack[0].SharingMap.count(D)) {
464 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
465 DVar.CKind = OMPC_threadprivate;
466 return DVar;
467 }
468
469 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
470 // in a Construct, C/C++, predetermined, p.1]
471 // Variables with automatic storage duration that are declared in a scope
472 // inside the construct are private.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000473 OpenMPDirectiveKind Kind =
474 FromParent ? getParentDirective() : getCurrentDirective();
475 auto StartI = std::next(Stack.rbegin());
476 auto EndI = std::prev(Stack.rend());
477 if (FromParent && StartI != EndI) {
478 StartI = std::next(StartI);
479 }
480 if (!isParallelOrTaskRegion(Kind)) {
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000481 if (isOpenMPLocal(D, StartI) &&
482 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
483 D->getStorageClass() == SC_None)) ||
484 isa<ParmVarDecl>(D))) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000485 DVar.CKind = OMPC_private;
486 return DVar;
Alexander Musman8dba6642014-04-22 13:09:42 +0000487 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000488
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000489 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
490 // in a Construct, C/C++, predetermined, p.4]
491 // Static data members are shared.
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000492 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
493 // in a Construct, C/C++, predetermined, p.7]
494 // Variables with static storage duration that are declared in a scope
495 // inside the construct are shared.
Alexey Bataev42971a32015-01-20 07:03:46 +0000496 if (D->isStaticDataMember() || D->isStaticLocal()) {
497 DSAVarData DVarTemp =
498 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
499 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
500 return DVar;
501
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000502 DVar.CKind = OMPC_shared;
503 return DVar;
504 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000505 }
506
507 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataev7ff55242014-06-19 09:13:45 +0000508 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
Alexey Bataev758e55e2013-09-06 18:03:48 +0000509 while (Type->isArrayType()) {
510 QualType ElemType = cast<ArrayType>(Type.getTypePtr())->getElementType();
511 Type = ElemType.getNonReferenceType().getCanonicalType();
512 }
513 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
514 // in a Construct, C/C++, predetermined, p.6]
515 // Variables with const qualified type having no mutable member are
516 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000517 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000518 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000519 if (IsConstant &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000520 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000521 // Variables with const-qualified type having no mutable member may be
522 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000523 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
524 MatchesAlways(), FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000525 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
526 return DVar;
527
Alexey Bataev758e55e2013-09-06 18:03:48 +0000528 DVar.CKind = OMPC_shared;
529 return DVar;
530 }
531
Alexey Bataev758e55e2013-09-06 18:03:48 +0000532 // Explicitly specified attributes and local variables with predetermined
533 // attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000534 auto I = std::prev(StartI);
535 if (I->SharingMap.count(D)) {
536 DVar.RefExpr = I->SharingMap[D].RefExpr;
537 DVar.CKind = I->SharingMap[D].Attributes;
538 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000539 }
540
541 return DVar;
542}
543
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000544DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000545 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000546 auto StartI = Stack.rbegin();
547 auto EndI = std::prev(Stack.rend());
548 if (FromParent && StartI != EndI) {
549 StartI = std::next(StartI);
550 }
551 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000552}
553
Alexey Bataevf29276e2014-06-18 04:14:57 +0000554template <class ClausesPredicate, class DirectivesPredicate>
555DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000556 DirectivesPredicate DPred,
557 bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000558 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000559 auto StartI = std::next(Stack.rbegin());
560 auto EndI = std::prev(Stack.rend());
561 if (FromParent && StartI != EndI) {
562 StartI = std::next(StartI);
563 }
564 for (auto I = StartI, EE = EndI; I != EE; ++I) {
565 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000566 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000567 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000568 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000569 return DVar;
570 }
571 return DSAVarData();
572}
573
Alexey Bataevf29276e2014-06-18 04:14:57 +0000574template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000575DSAStackTy::DSAVarData
576DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
577 DirectivesPredicate DPred, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000578 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000579 auto StartI = std::next(Stack.rbegin());
580 auto EndI = std::prev(Stack.rend());
581 if (FromParent && StartI != EndI) {
582 StartI = std::next(StartI);
583 }
584 for (auto I = StartI, EE = EndI; I != EE; ++I) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000585 if (!DPred(I->Directive))
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000586 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +0000587 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000588 if (CPred(DVar.CKind))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000589 return DVar;
590 return DSAVarData();
591 }
592 return DSAVarData();
593}
594
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000595template <class NamedDirectivesPredicate>
596bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
597 auto StartI = std::next(Stack.rbegin());
598 auto EndI = std::prev(Stack.rend());
599 if (FromParent && StartI != EndI) {
600 StartI = std::next(StartI);
601 }
602 for (auto I = StartI, EE = EndI; I != EE; ++I) {
603 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
604 return true;
605 }
606 return false;
607}
608
Alexey Bataev758e55e2013-09-06 18:03:48 +0000609void Sema::InitDataSharingAttributesStack() {
610 VarDataSharingAttributesStack = new DSAStackTy(*this);
611}
612
613#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
614
Alexey Bataevf841bd92014-12-16 07:00:22 +0000615bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
616 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000617 VD = VD->getCanonicalDecl();
Alexey Bataevf841bd92014-12-16 07:00:22 +0000618 if (DSAStack->getCurrentDirective() != OMPD_unknown) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000619 if (DSAStack->isLoopControlVariable(VD) ||
620 (VD->hasLocalStorage() &&
621 isParallelOrTaskRegion(DSAStack->getCurrentDirective())))
Alexey Bataev9c821032015-04-30 04:23:23 +0000622 return true;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000623 auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isFromParent());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000624 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
625 return true;
626 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000627 DSAStack->isFromParent());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000628 return DVarPrivate.CKind != OMPC_unknown;
629 }
630 return false;
631}
632
Alexey Bataeved09d242014-05-28 05:53:51 +0000633void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000634
635void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
636 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000637 Scope *CurScope, SourceLocation Loc) {
638 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000639 PushExpressionEvaluationContext(PotentiallyEvaluated);
640}
641
Alexey Bataev39f915b82015-05-08 10:41:21 +0000642void Sema::StartOpenMPClauses() {
643 DSAStack->setFromParent(/*Flag=*/true);
644}
645
646void Sema::EndOpenMPClauses() {
647 DSAStack->setFromParent(/*Flag=*/false);
648}
649
Alexey Bataev758e55e2013-09-06 18:03:48 +0000650void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000651 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
652 // A variable of class type (or array thereof) that appears in a lastprivate
653 // clause requires an accessible, unambiguous default constructor for the
654 // class type, unless the list item is also specified in a firstprivate
655 // clause.
656 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000657 for (auto *C : D->clauses()) {
658 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
659 SmallVector<Expr *, 8> PrivateCopies;
660 for (auto *DE : Clause->varlists()) {
661 if (DE->isValueDependent() || DE->isTypeDependent()) {
662 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000663 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +0000664 }
665 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000666 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000667 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000668 // Generate helper private variable and initialize it with the
669 // default value. The address of the original variable is replaced
670 // by the address of the new private variable in CodeGen. This new
671 // variable is not added to IdResolver, so the code in the OpenMP
672 // region uses original variable for proper diagnostics.
Alexey Bataev39f915b82015-05-08 10:41:21 +0000673 auto *VDPrivate =
674 buildVarDecl(*this, DE->getExprLoc(),
675 VD->getType().getUnqualifiedType(), VD->getName());
Alexey Bataev38e89532015-04-16 04:54:05 +0000676 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
677 if (VDPrivate->isInvalidDecl())
678 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000679 PrivateCopies.push_back(buildDeclRefExpr(
680 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +0000681 } else {
682 // The variable is also a firstprivate, so initialization sequence
683 // for private copy is generated already.
684 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000685 }
686 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000687 // Set initializers to private copies if no errors were found.
688 if (PrivateCopies.size() == Clause->varlist_size()) {
689 Clause->setPrivateCopies(PrivateCopies);
690 }
Alexey Bataevf29276e2014-06-18 04:14:57 +0000691 }
692 }
693 }
694
Alexey Bataev758e55e2013-09-06 18:03:48 +0000695 DSAStack->pop();
696 DiscardCleanupsInEvaluationContext();
697 PopExpressionEvaluationContext();
698}
699
Alexander Musman3276a272015-03-21 10:12:56 +0000700static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
701 Expr *NumIterations, Sema &SemaRef,
702 Scope *S);
703
Alexey Bataeva769e072013-03-22 06:34:35 +0000704namespace {
705
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000706class VarDeclFilterCCC : public CorrectionCandidateCallback {
707private:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000708 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +0000709
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000710public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000711 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +0000712 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000713 NamedDecl *ND = Candidate.getCorrectionDecl();
714 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
715 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000716 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
717 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +0000718 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000719 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +0000720 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000721};
Alexey Bataeved09d242014-05-28 05:53:51 +0000722} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000723
724ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
725 CXXScopeSpec &ScopeSpec,
726 const DeclarationNameInfo &Id) {
727 LookupResult Lookup(*this, Id, LookupOrdinaryName);
728 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
729
730 if (Lookup.isAmbiguous())
731 return ExprError();
732
733 VarDecl *VD;
734 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000735 if (TypoCorrection Corrected = CorrectTypo(
736 Id, LookupOrdinaryName, CurScope, nullptr,
737 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000738 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000739 PDiag(Lookup.empty()
740 ? diag::err_undeclared_var_use_suggest
741 : diag::err_omp_expected_var_arg_suggest)
742 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +0000743 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000744 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000745 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
746 : diag::err_omp_expected_var_arg)
747 << Id.getName();
748 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000749 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000750 } else {
751 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000752 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000753 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
754 return ExprError();
755 }
756 }
757 Lookup.suppressDiagnostics();
758
759 // OpenMP [2.9.2, Syntax, C/C++]
760 // Variables must be file-scope, namespace-scope, or static block-scope.
761 if (!VD->hasGlobalStorage()) {
762 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000763 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
764 bool IsDecl =
765 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000766 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +0000767 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
768 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000769 return ExprError();
770 }
771
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000772 VarDecl *CanonicalVD = VD->getCanonicalDecl();
773 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000774 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
775 // A threadprivate directive for file-scope variables must appear outside
776 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000777 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
778 !getCurLexicalContext()->isTranslationUnit()) {
779 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000780 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
781 bool IsDecl =
782 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
783 Diag(VD->getLocation(),
784 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
785 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000786 return ExprError();
787 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000788 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
789 // A threadprivate directive for static class member variables must appear
790 // in the class definition, in the same scope in which the member
791 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000792 if (CanonicalVD->isStaticDataMember() &&
793 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
794 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000795 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
796 bool IsDecl =
797 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
798 Diag(VD->getLocation(),
799 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
800 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000801 return ExprError();
802 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000803 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
804 // A threadprivate directive for namespace-scope variables must appear
805 // outside any definition or declaration other than the namespace
806 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000807 if (CanonicalVD->getDeclContext()->isNamespace() &&
808 (!getCurLexicalContext()->isFileContext() ||
809 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
810 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000811 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
812 bool IsDecl =
813 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
814 Diag(VD->getLocation(),
815 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
816 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000817 return ExprError();
818 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000819 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
820 // A threadprivate directive for static block-scope variables must appear
821 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000822 if (CanonicalVD->isStaticLocal() && CurScope &&
823 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000824 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000825 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
826 bool IsDecl =
827 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
828 Diag(VD->getLocation(),
829 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
830 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000831 return ExprError();
832 }
833
834 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
835 // A threadprivate directive must lexically precede all references to any
836 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000837 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000838 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +0000839 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000840 return ExprError();
841 }
842
843 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +0000844 ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000845 return DE;
846}
847
Alexey Bataeved09d242014-05-28 05:53:51 +0000848Sema::DeclGroupPtrTy
849Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
850 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000851 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000852 CurContext->addDecl(D);
853 return DeclGroupPtrTy::make(DeclGroupRef(D));
854 }
855 return DeclGroupPtrTy();
856}
857
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000858namespace {
859class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
860 Sema &SemaRef;
861
862public:
863 bool VisitDeclRefExpr(const DeclRefExpr *E) {
864 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
865 if (VD->hasLocalStorage()) {
866 SemaRef.Diag(E->getLocStart(),
867 diag::err_omp_local_var_in_threadprivate_init)
868 << E->getSourceRange();
869 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
870 << VD << VD->getSourceRange();
871 return true;
872 }
873 }
874 return false;
875 }
876 bool VisitStmt(const Stmt *S) {
877 for (auto Child : S->children()) {
878 if (Child && Visit(Child))
879 return true;
880 }
881 return false;
882 }
Alexey Bataev23b69422014-06-18 07:08:49 +0000883 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000884};
885} // namespace
886
Alexey Bataeved09d242014-05-28 05:53:51 +0000887OMPThreadPrivateDecl *
888Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000889 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +0000890 for (auto &RefExpr : VarList) {
891 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000892 VarDecl *VD = cast<VarDecl>(DE->getDecl());
893 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +0000894
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000895 QualType QType = VD->getType();
896 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
897 // It will be analyzed later.
898 Vars.push_back(DE);
899 continue;
900 }
901
Alexey Bataeva769e072013-03-22 06:34:35 +0000902 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
903 // A threadprivate variable must not have an incomplete type.
904 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000905 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000906 continue;
907 }
908
909 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
910 // A threadprivate variable must not have a reference type.
911 if (VD->getType()->isReferenceType()) {
912 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000913 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
914 bool IsDecl =
915 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
916 Diag(VD->getLocation(),
917 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
918 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000919 continue;
920 }
921
Richard Smithfd3834f2013-04-13 02:43:54 +0000922 // Check if this is a TLS variable.
Alexey Bataev26a39242015-01-13 03:35:30 +0000923 if (VD->getTLSKind() != VarDecl::TLS_None ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +0000924 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
925 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +0000926 Diag(ILoc, diag::err_omp_var_thread_local)
927 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +0000928 bool IsDecl =
929 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
930 Diag(VD->getLocation(),
931 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
932 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000933 continue;
934 }
935
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000936 // Check if initial value of threadprivate variable reference variable with
937 // local storage (it is not supported by runtime).
938 if (auto Init = VD->getAnyInitializer()) {
939 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000940 if (Checker.Visit(Init))
941 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000942 }
943
Alexey Bataeved09d242014-05-28 05:53:51 +0000944 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +0000945 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +0000946 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
947 Context, SourceRange(Loc, Loc)));
948 if (auto *ML = Context.getASTMutationListener())
949 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +0000950 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000951 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000952 if (!Vars.empty()) {
953 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
954 Vars);
955 D->setAccess(AS_public);
956 }
957 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +0000958}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000959
Alexey Bataev7ff55242014-06-19 09:13:45 +0000960static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
961 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
962 bool IsLoopIterVar = false) {
963 if (DVar.RefExpr) {
964 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
965 << getOpenMPClauseName(DVar.CKind);
966 return;
967 }
968 enum {
969 PDSA_StaticMemberShared,
970 PDSA_StaticLocalVarShared,
971 PDSA_LoopIterVarPrivate,
972 PDSA_LoopIterVarLinear,
973 PDSA_LoopIterVarLastprivate,
974 PDSA_ConstVarShared,
975 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000976 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000977 PDSA_LocalVarPrivate,
978 PDSA_Implicit
979 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000980 bool ReportHint = false;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000981 auto ReportLoc = VD->getLocation();
Alexey Bataev7ff55242014-06-19 09:13:45 +0000982 if (IsLoopIterVar) {
983 if (DVar.CKind == OMPC_private)
984 Reason = PDSA_LoopIterVarPrivate;
985 else if (DVar.CKind == OMPC_lastprivate)
986 Reason = PDSA_LoopIterVarLastprivate;
987 else
988 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000989 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
990 Reason = PDSA_TaskVarFirstprivate;
991 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000992 } else if (VD->isStaticLocal())
993 Reason = PDSA_StaticLocalVarShared;
994 else if (VD->isStaticDataMember())
995 Reason = PDSA_StaticMemberShared;
996 else if (VD->isFileVarDecl())
997 Reason = PDSA_GlobalVarShared;
998 else if (VD->getType().isConstant(SemaRef.getASTContext()))
999 Reason = PDSA_ConstVarShared;
Alexey Bataevbae9a792014-06-27 10:37:06 +00001000 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001001 ReportHint = true;
1002 Reason = PDSA_LocalVarPrivate;
1003 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001004 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001005 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001006 << Reason << ReportHint
1007 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1008 } else if (DVar.ImplicitDSALoc.isValid()) {
1009 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1010 << getOpenMPClauseName(DVar.CKind);
1011 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001012}
1013
Alexey Bataev758e55e2013-09-06 18:03:48 +00001014namespace {
1015class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1016 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001017 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001018 bool ErrorFound;
1019 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001020 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001021 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001022
Alexey Bataev758e55e2013-09-06 18:03:48 +00001023public:
1024 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001025 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001026 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001027 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1028 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001029
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001030 auto DVar = Stack->getTopDSA(VD, false);
1031 // Check if the variable has explicit DSA set and stop analysis if it so.
1032 if (DVar.RefExpr) return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001033
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001034 auto ELoc = E->getExprLoc();
1035 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001036 // The default(none) clause requires that each variable that is referenced
1037 // in the construct, and does not have a predetermined data-sharing
1038 // attribute, must have its data-sharing attribute explicitly determined
1039 // by being listed in a data-sharing attribute clause.
1040 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001041 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001042 VarsWithInheritedDSA.count(VD) == 0) {
1043 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001044 return;
1045 }
1046
1047 // OpenMP [2.9.3.6, Restrictions, p.2]
1048 // A list item that appears in a reduction clause of the innermost
1049 // enclosing worksharing or parallel construct may not be accessed in an
1050 // explicit task.
Alexey Bataevf29276e2014-06-18 04:14:57 +00001051 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001052 [](OpenMPDirectiveKind K) -> bool {
1053 return isOpenMPParallelDirective(K) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001054 isOpenMPWorksharingDirective(K) ||
1055 isOpenMPTeamsDirective(K);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001056 },
1057 false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001058 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1059 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001060 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1061 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001062 return;
1063 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001064
1065 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001066 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001067 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001068 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001069 }
1070 }
1071 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001072 for (auto *C : S->clauses()) {
1073 // Skip analysis of arguments of implicitly defined firstprivate clause
1074 // for task directives.
1075 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1076 for (auto *CC : C->children()) {
1077 if (CC)
1078 Visit(CC);
1079 }
1080 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001081 }
1082 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001083 for (auto *C : S->children()) {
1084 if (C && !isa<OMPExecutableDirective>(C))
1085 Visit(C);
1086 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001087 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001088
1089 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001090 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001091 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1092 return VarsWithInheritedDSA;
1093 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001094
Alexey Bataev7ff55242014-06-19 09:13:45 +00001095 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1096 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001097};
Alexey Bataeved09d242014-05-28 05:53:51 +00001098} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001099
Alexey Bataevbae9a792014-06-27 10:37:06 +00001100void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001101 switch (DKind) {
1102 case OMPD_parallel: {
1103 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1104 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001105 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001106 std::make_pair(".global_tid.", KmpInt32PtrTy),
1107 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1108 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001109 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001110 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1111 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001112 break;
1113 }
1114 case OMPD_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001115 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001116 std::make_pair(StringRef(), QualType()) // __context with shared vars
1117 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001118 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1119 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001120 break;
1121 }
1122 case OMPD_for: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001123 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001124 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001125 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001126 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1127 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001128 break;
1129 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001130 case OMPD_for_simd: {
1131 Sema::CapturedParamNameType Params[] = {
1132 std::make_pair(StringRef(), QualType()) // __context with shared vars
1133 };
1134 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1135 Params);
1136 break;
1137 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001138 case OMPD_sections: {
1139 Sema::CapturedParamNameType Params[] = {
1140 std::make_pair(StringRef(), QualType()) // __context with shared vars
1141 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001142 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1143 Params);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001144 break;
1145 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001146 case OMPD_section: {
1147 Sema::CapturedParamNameType Params[] = {
1148 std::make_pair(StringRef(), QualType()) // __context with shared vars
1149 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001150 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1151 Params);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001152 break;
1153 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001154 case OMPD_single: {
1155 Sema::CapturedParamNameType Params[] = {
1156 std::make_pair(StringRef(), QualType()) // __context with shared vars
1157 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001158 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1159 Params);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001160 break;
1161 }
Alexander Musman80c22892014-07-17 08:54:58 +00001162 case OMPD_master: {
1163 Sema::CapturedParamNameType Params[] = {
1164 std::make_pair(StringRef(), QualType()) // __context with shared vars
1165 };
1166 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1167 Params);
1168 break;
1169 }
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001170 case OMPD_critical: {
1171 Sema::CapturedParamNameType Params[] = {
1172 std::make_pair(StringRef(), QualType()) // __context with shared vars
1173 };
1174 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1175 Params);
1176 break;
1177 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001178 case OMPD_parallel_for: {
1179 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1180 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1181 Sema::CapturedParamNameType Params[] = {
1182 std::make_pair(".global_tid.", KmpInt32PtrTy),
1183 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1184 std::make_pair(StringRef(), QualType()) // __context with shared vars
1185 };
1186 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1187 Params);
1188 break;
1189 }
Alexander Musmane4e893b2014-09-23 09:33:00 +00001190 case OMPD_parallel_for_simd: {
1191 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1192 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1193 Sema::CapturedParamNameType Params[] = {
1194 std::make_pair(".global_tid.", KmpInt32PtrTy),
1195 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1196 std::make_pair(StringRef(), QualType()) // __context with shared vars
1197 };
1198 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1199 Params);
1200 break;
1201 }
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001202 case OMPD_parallel_sections: {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001203 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1204 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001205 Sema::CapturedParamNameType Params[] = {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001206 std::make_pair(".global_tid.", KmpInt32PtrTy),
1207 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001208 std::make_pair(StringRef(), QualType()) // __context with shared vars
1209 };
1210 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1211 Params);
1212 break;
1213 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001214 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001215 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001216 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001217 std::make_pair(".global_tid.", KmpInt32Ty),
1218 std::make_pair(".part_id.", KmpInt32Ty),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001219 std::make_pair(StringRef(), QualType()) // __context with shared vars
1220 };
1221 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1222 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001223 // Mark this captured region as inlined, because we don't use outlined
1224 // function directly.
1225 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1226 AlwaysInlineAttr::CreateImplicit(
1227 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001228 break;
1229 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001230 case OMPD_ordered: {
1231 Sema::CapturedParamNameType Params[] = {
1232 std::make_pair(StringRef(), QualType()) // __context with shared vars
1233 };
1234 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1235 Params);
1236 break;
1237 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001238 case OMPD_atomic: {
1239 Sema::CapturedParamNameType Params[] = {
1240 std::make_pair(StringRef(), QualType()) // __context with shared vars
1241 };
1242 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1243 Params);
1244 break;
1245 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001246 case OMPD_target: {
1247 Sema::CapturedParamNameType Params[] = {
1248 std::make_pair(StringRef(), QualType()) // __context with shared vars
1249 };
1250 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1251 Params);
1252 break;
1253 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001254 case OMPD_teams: {
1255 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1256 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1257 Sema::CapturedParamNameType Params[] = {
1258 std::make_pair(".global_tid.", KmpInt32PtrTy),
1259 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1260 std::make_pair(StringRef(), QualType()) // __context with shared vars
1261 };
1262 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1263 Params);
1264 break;
1265 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001266 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001267 case OMPD_taskyield:
1268 case OMPD_barrier:
1269 case OMPD_taskwait:
1270 case OMPD_flush:
Alexey Bataev9959db52014-05-06 10:08:46 +00001271 llvm_unreachable("OpenMP Directive is not allowed");
1272 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001273 llvm_unreachable("Unknown OpenMP directive");
1274 }
1275}
1276
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001277StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1278 ArrayRef<OMPClause *> Clauses) {
1279 if (!S.isUsable()) {
1280 ActOnCapturedRegionError();
1281 return StmtError();
1282 }
Alexey Bataev040d5402015-05-12 08:35:28 +00001283 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001284 for (auto *Clause : Clauses) {
1285 if (isOpenMPPrivate(Clause->getClauseKind())) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001286 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001287 for (auto *VarRef : Clause->children()) {
1288 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001289 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001290 }
1291 }
Alexey Bataev040d5402015-05-12 08:35:28 +00001292 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
1293 Clause->getClauseKind() == OMPC_schedule) {
1294 // Mark all variables in private list clauses as used in inner region.
1295 // Required for proper codegen of combined directives.
1296 // TODO: add processing for other clauses.
1297 if (auto *E = cast_or_null<Expr>(
1298 cast<OMPScheduleClause>(Clause)->getHelperChunkSize())) {
1299 MarkDeclarationsReferencedInExpr(E);
1300 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001301 }
1302 }
1303 return ActOnCapturedRegionEnd(S.get());
1304}
1305
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001306static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1307 OpenMPDirectiveKind CurrentRegion,
1308 const DeclarationNameInfo &CurrentName,
1309 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001310 // Allowed nesting of constructs
1311 // +------------------+-----------------+------------------------------------+
1312 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1313 // +------------------+-----------------+------------------------------------+
1314 // | parallel | parallel | * |
1315 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001316 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001317 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001318 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001319 // | parallel | simd | * |
1320 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001321 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001322 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001323 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001324 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001325 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001326 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001327 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001328 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001329 // | parallel | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001330 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001331 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001332 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001333 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001334 // | parallel | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001335 // +------------------+-----------------+------------------------------------+
1336 // | for | parallel | * |
1337 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001338 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001339 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001340 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001341 // | for | simd | * |
1342 // | for | sections | + |
1343 // | for | section | + |
1344 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001345 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001346 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001347 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001348 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001349 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001350 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001351 // | for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001352 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001353 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001354 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001355 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001356 // | for | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001357 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001358 // | master | parallel | * |
1359 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001360 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001361 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001362 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001363 // | master | simd | * |
1364 // | master | sections | + |
1365 // | master | section | + |
1366 // | master | single | + |
1367 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001368 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001369 // | master |parallel sections| * |
1370 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001371 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001372 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001373 // | master | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001374 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001375 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001376 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001377 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001378 // | master | teams | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001379 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001380 // | critical | parallel | * |
1381 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001382 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001383 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001384 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001385 // | critical | simd | * |
1386 // | critical | sections | + |
1387 // | critical | section | + |
1388 // | critical | single | + |
1389 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001390 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001391 // | critical |parallel sections| * |
1392 // | critical | task | * |
1393 // | critical | taskyield | * |
1394 // | critical | barrier | + |
1395 // | critical | taskwait | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001396 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001397 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001398 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001399 // | critical | teams | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001400 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001401 // | simd | parallel | |
1402 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001403 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001404 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001405 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001406 // | simd | simd | |
1407 // | simd | sections | |
1408 // | simd | section | |
1409 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001410 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001411 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001412 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001413 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001414 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001415 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001416 // | simd | taskwait | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001417 // | simd | flush | |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001418 // | simd | ordered | |
Alexey Bataev0162e452014-07-22 10:10:35 +00001419 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001420 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001421 // | simd | teams | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001422 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001423 // | for simd | parallel | |
1424 // | for simd | for | |
1425 // | for simd | for simd | |
1426 // | for simd | master | |
1427 // | for simd | critical | |
1428 // | for simd | simd | |
1429 // | for simd | sections | |
1430 // | for simd | section | |
1431 // | for simd | single | |
1432 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001433 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001434 // | for simd |parallel sections| |
1435 // | for simd | task | |
1436 // | for simd | taskyield | |
1437 // | for simd | barrier | |
1438 // | for simd | taskwait | |
1439 // | for simd | flush | |
1440 // | for simd | ordered | |
1441 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001442 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001443 // | for simd | teams | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001444 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001445 // | parallel for simd| parallel | |
1446 // | parallel for simd| for | |
1447 // | parallel for simd| for simd | |
1448 // | parallel for simd| master | |
1449 // | parallel for simd| critical | |
1450 // | parallel for simd| simd | |
1451 // | parallel for simd| sections | |
1452 // | parallel for simd| section | |
1453 // | parallel for simd| single | |
1454 // | parallel for simd| parallel for | |
1455 // | parallel for simd|parallel for simd| |
1456 // | parallel for simd|parallel sections| |
1457 // | parallel for simd| task | |
1458 // | parallel for simd| taskyield | |
1459 // | parallel for simd| barrier | |
1460 // | parallel for simd| taskwait | |
1461 // | parallel for simd| flush | |
1462 // | parallel for simd| ordered | |
1463 // | parallel for simd| atomic | |
1464 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001465 // | parallel for simd| teams | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001466 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001467 // | sections | parallel | * |
1468 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001469 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001470 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001471 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001472 // | sections | simd | * |
1473 // | sections | sections | + |
1474 // | sections | section | * |
1475 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001476 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001477 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001478 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001479 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001480 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001481 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001482 // | sections | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001483 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001484 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001485 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001486 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001487 // | sections | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001488 // +------------------+-----------------+------------------------------------+
1489 // | section | parallel | * |
1490 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001491 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001492 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001493 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001494 // | section | simd | * |
1495 // | section | sections | + |
1496 // | section | section | + |
1497 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001498 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001499 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001500 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001501 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001502 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001503 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001504 // | section | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001505 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001506 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001507 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001508 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001509 // | section | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001510 // +------------------+-----------------+------------------------------------+
1511 // | single | parallel | * |
1512 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001513 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001514 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001515 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001516 // | single | simd | * |
1517 // | single | sections | + |
1518 // | single | section | + |
1519 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001520 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001521 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001522 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001523 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001524 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001525 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001526 // | single | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001527 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001528 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001529 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001530 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001531 // | single | teams | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001532 // +------------------+-----------------+------------------------------------+
1533 // | parallel for | parallel | * |
1534 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001535 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001536 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001537 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001538 // | parallel for | simd | * |
1539 // | parallel for | sections | + |
1540 // | parallel for | section | + |
1541 // | parallel for | single | + |
1542 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001543 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001544 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001545 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001546 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001547 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001548 // | parallel for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001549 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001550 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001551 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001552 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001553 // | parallel for | teams | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001554 // +------------------+-----------------+------------------------------------+
1555 // | parallel sections| parallel | * |
1556 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001557 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001558 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001559 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001560 // | parallel sections| simd | * |
1561 // | parallel sections| sections | + |
1562 // | parallel sections| section | * |
1563 // | parallel sections| single | + |
1564 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001565 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001566 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001567 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001568 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001569 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001570 // | parallel sections| taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001571 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001572 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001573 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001574 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001575 // | parallel sections| teams | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001576 // +------------------+-----------------+------------------------------------+
1577 // | task | parallel | * |
1578 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001579 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001580 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001581 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001582 // | task | simd | * |
1583 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001584 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001585 // | task | single | + |
1586 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001587 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001588 // | task |parallel sections| * |
1589 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001590 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001591 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001592 // | task | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001593 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001594 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001595 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001596 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001597 // | task | teams | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001598 // +------------------+-----------------+------------------------------------+
1599 // | ordered | parallel | * |
1600 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001601 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001602 // | ordered | master | * |
1603 // | ordered | critical | * |
1604 // | ordered | simd | * |
1605 // | ordered | sections | + |
1606 // | ordered | section | + |
1607 // | ordered | single | + |
1608 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001609 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001610 // | ordered |parallel sections| * |
1611 // | ordered | task | * |
1612 // | ordered | taskyield | * |
1613 // | ordered | barrier | + |
1614 // | ordered | taskwait | * |
1615 // | ordered | flush | * |
1616 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001617 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001618 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001619 // | ordered | teams | + |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001620 // +------------------+-----------------+------------------------------------+
1621 // | atomic | parallel | |
1622 // | atomic | for | |
1623 // | atomic | for simd | |
1624 // | atomic | master | |
1625 // | atomic | critical | |
1626 // | atomic | simd | |
1627 // | atomic | sections | |
1628 // | atomic | section | |
1629 // | atomic | single | |
1630 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001631 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001632 // | atomic |parallel sections| |
1633 // | atomic | task | |
1634 // | atomic | taskyield | |
1635 // | atomic | barrier | |
1636 // | atomic | taskwait | |
1637 // | atomic | flush | |
1638 // | atomic | ordered | |
1639 // | atomic | atomic | |
1640 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001641 // | atomic | teams | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001642 // +------------------+-----------------+------------------------------------+
1643 // | target | parallel | * |
1644 // | target | for | * |
1645 // | target | for simd | * |
1646 // | target | master | * |
1647 // | target | critical | * |
1648 // | target | simd | * |
1649 // | target | sections | * |
1650 // | target | section | * |
1651 // | target | single | * |
1652 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001653 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001654 // | target |parallel sections| * |
1655 // | target | task | * |
1656 // | target | taskyield | * |
1657 // | target | barrier | * |
1658 // | target | taskwait | * |
1659 // | target | flush | * |
1660 // | target | ordered | * |
1661 // | target | atomic | * |
1662 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001663 // | target | teams | * |
1664 // +------------------+-----------------+------------------------------------+
1665 // | teams | parallel | * |
1666 // | teams | for | + |
1667 // | teams | for simd | + |
1668 // | teams | master | + |
1669 // | teams | critical | + |
1670 // | teams | simd | + |
1671 // | teams | sections | + |
1672 // | teams | section | + |
1673 // | teams | single | + |
1674 // | teams | parallel for | * |
1675 // | teams |parallel for simd| * |
1676 // | teams |parallel sections| * |
1677 // | teams | task | + |
1678 // | teams | taskyield | + |
1679 // | teams | barrier | + |
1680 // | teams | taskwait | + |
1681 // | teams | flush | + |
1682 // | teams | ordered | + |
1683 // | teams | atomic | + |
1684 // | teams | target | + |
1685 // | teams | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001686 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00001687 if (Stack->getCurScope()) {
1688 auto ParentRegion = Stack->getParentDirective();
1689 bool NestingProhibited = false;
1690 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001691 enum {
1692 NoRecommend,
1693 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001694 ShouldBeInOrderedRegion,
1695 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001696 } Recommend = NoRecommend;
Alexey Bataev549210e2014-06-24 04:39:47 +00001697 if (isOpenMPSimdDirective(ParentRegion)) {
1698 // OpenMP [2.16, Nesting of Regions]
1699 // OpenMP constructs may not be nested inside a simd region.
1700 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1701 return true;
1702 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001703 if (ParentRegion == OMPD_atomic) {
1704 // OpenMP [2.16, Nesting of Regions]
1705 // OpenMP constructs may not be nested inside an atomic region.
1706 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1707 return true;
1708 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001709 if (CurrentRegion == OMPD_section) {
1710 // OpenMP [2.7.2, sections Construct, Restrictions]
1711 // Orphaned section directives are prohibited. That is, the section
1712 // directives must appear within the sections construct and must not be
1713 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001714 if (ParentRegion != OMPD_sections &&
1715 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001716 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1717 << (ParentRegion != OMPD_unknown)
1718 << getOpenMPDirectiveName(ParentRegion);
1719 return true;
1720 }
1721 return false;
1722 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001723 // Allow some constructs to be orphaned (they could be used in functions,
1724 // called from OpenMP regions with the required preconditions).
1725 if (ParentRegion == OMPD_unknown)
1726 return false;
Alexander Musman80c22892014-07-17 08:54:58 +00001727 if (CurrentRegion == OMPD_master) {
1728 // OpenMP [2.16, Nesting of Regions]
1729 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001730 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001731 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1732 ParentRegion == OMPD_task;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001733 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1734 // OpenMP [2.16, Nesting of Regions]
1735 // A critical region may not be nested (closely or otherwise) inside a
1736 // critical region with the same name. Note that this restriction is not
1737 // sufficient to prevent deadlock.
1738 SourceLocation PreviousCriticalLoc;
1739 bool DeadLock =
1740 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1741 OpenMPDirectiveKind K,
1742 const DeclarationNameInfo &DNI,
1743 SourceLocation Loc)
1744 ->bool {
1745 if (K == OMPD_critical &&
1746 DNI.getName() == CurrentName.getName()) {
1747 PreviousCriticalLoc = Loc;
1748 return true;
1749 } else
1750 return false;
1751 },
1752 false /* skip top directive */);
1753 if (DeadLock) {
1754 SemaRef.Diag(StartLoc,
1755 diag::err_omp_prohibited_region_critical_same_name)
1756 << CurrentName.getName();
1757 if (PreviousCriticalLoc.isValid())
1758 SemaRef.Diag(PreviousCriticalLoc,
1759 diag::note_omp_previous_critical_region);
1760 return true;
1761 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001762 } else if (CurrentRegion == OMPD_barrier) {
1763 // OpenMP [2.16, Nesting of Regions]
1764 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001765 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001766 NestingProhibited =
1767 isOpenMPWorksharingDirective(ParentRegion) ||
1768 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1769 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001770 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00001771 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001772 // OpenMP [2.16, Nesting of Regions]
1773 // A worksharing region may not be closely nested inside a worksharing,
1774 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001775 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00001776 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001777 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1778 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1779 Recommend = ShouldBeInParallelRegion;
1780 } else if (CurrentRegion == OMPD_ordered) {
1781 // OpenMP [2.16, Nesting of Regions]
1782 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00001783 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001784 // An ordered region must be closely nested inside a loop region (or
1785 // parallel loop region) with an ordered clause.
1786 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00001787 ParentRegion == OMPD_task ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001788 !Stack->isParentOrderedRegion();
1789 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001790 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1791 // OpenMP [2.16, Nesting of Regions]
1792 // If specified, a teams construct must be contained within a target
1793 // construct.
1794 NestingProhibited = ParentRegion != OMPD_target;
1795 Recommend = ShouldBeInTargetRegion;
1796 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1797 }
1798 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1799 // OpenMP [2.16, Nesting of Regions]
1800 // distribute, parallel, parallel sections, parallel workshare, and the
1801 // parallel loop and parallel loop SIMD constructs are the only OpenMP
1802 // constructs that can be closely nested in the teams region.
1803 // TODO: add distribute directive.
1804 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1805 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001806 }
1807 if (NestingProhibited) {
1808 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001809 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1810 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00001811 return true;
1812 }
1813 }
1814 return false;
1815}
1816
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001817StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001818 const DeclarationNameInfo &DirName,
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001819 ArrayRef<OMPClause *> Clauses,
1820 Stmt *AStmt,
1821 SourceLocation StartLoc,
1822 SourceLocation EndLoc) {
1823 StmtResult Res = StmtError();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001824 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00001825 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001826
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001827 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00001828 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001829 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00001830 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00001831 if (AStmt) {
1832 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1833
1834 // Check default data sharing attributes for referenced variables.
1835 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1836 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1837 if (DSAChecker.isErrorFound())
1838 return StmtError();
1839 // Generate list of implicitly defined firstprivate variables.
1840 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00001841
1842 if (!DSAChecker.getImplicitFirstprivate().empty()) {
1843 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1844 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1845 SourceLocation(), SourceLocation())) {
1846 ClausesWithImplicit.push_back(Implicit);
1847 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1848 DSAChecker.getImplicitFirstprivate().size();
1849 } else
1850 ErrorFound = true;
1851 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001852 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001853
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001854 switch (Kind) {
1855 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00001856 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1857 EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001858 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001859 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001860 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1861 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001862 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00001863 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001864 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1865 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001866 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00001867 case OMPD_for_simd:
1868 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
1869 EndLoc, VarsWithInheritedDSA);
1870 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001871 case OMPD_sections:
1872 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1873 EndLoc);
1874 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001875 case OMPD_section:
1876 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00001877 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001878 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1879 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001880 case OMPD_single:
1881 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1882 EndLoc);
1883 break;
Alexander Musman80c22892014-07-17 08:54:58 +00001884 case OMPD_master:
1885 assert(ClausesWithImplicit.empty() &&
1886 "No clauses are allowed for 'omp master' directive");
1887 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1888 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001889 case OMPD_critical:
1890 assert(ClausesWithImplicit.empty() &&
1891 "No clauses are allowed for 'omp critical' directive");
1892 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1893 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001894 case OMPD_parallel_for:
1895 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1896 EndLoc, VarsWithInheritedDSA);
1897 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00001898 case OMPD_parallel_for_simd:
1899 Res = ActOnOpenMPParallelForSimdDirective(
1900 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
1901 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001902 case OMPD_parallel_sections:
1903 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1904 StartLoc, EndLoc);
1905 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001906 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001907 Res =
1908 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1909 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00001910 case OMPD_taskyield:
1911 assert(ClausesWithImplicit.empty() &&
1912 "No clauses are allowed for 'omp taskyield' directive");
1913 assert(AStmt == nullptr &&
1914 "No associated statement allowed for 'omp taskyield' directive");
1915 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1916 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001917 case OMPD_barrier:
1918 assert(ClausesWithImplicit.empty() &&
1919 "No clauses are allowed for 'omp barrier' directive");
1920 assert(AStmt == nullptr &&
1921 "No associated statement allowed for 'omp barrier' directive");
1922 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1923 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00001924 case OMPD_taskwait:
1925 assert(ClausesWithImplicit.empty() &&
1926 "No clauses are allowed for 'omp taskwait' directive");
1927 assert(AStmt == nullptr &&
1928 "No associated statement allowed for 'omp taskwait' directive");
1929 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1930 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00001931 case OMPD_flush:
1932 assert(AStmt == nullptr &&
1933 "No associated statement allowed for 'omp flush' directive");
1934 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
1935 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001936 case OMPD_ordered:
1937 assert(ClausesWithImplicit.empty() &&
1938 "No clauses are allowed for 'omp ordered' directive");
1939 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
1940 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00001941 case OMPD_atomic:
1942 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
1943 EndLoc);
1944 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001945 case OMPD_teams:
1946 Res =
1947 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1948 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001949 case OMPD_target:
1950 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
1951 EndLoc);
1952 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001953 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001954 llvm_unreachable("OpenMP Directive is not allowed");
1955 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001956 llvm_unreachable("Unknown OpenMP directive");
1957 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001958
Alexey Bataev4acb8592014-07-07 13:01:15 +00001959 for (auto P : VarsWithInheritedDSA) {
1960 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1961 << P.first << P.second->getSourceRange();
1962 }
1963 if (!VarsWithInheritedDSA.empty())
1964 return StmtError();
1965
Alexey Bataeved09d242014-05-28 05:53:51 +00001966 if (ErrorFound)
1967 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001968 return Res;
1969}
1970
1971StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
1972 Stmt *AStmt,
1973 SourceLocation StartLoc,
1974 SourceLocation EndLoc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001975 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
1976 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
1977 // 1.2.2 OpenMP Language Terminology
1978 // Structured block - An executable statement with a single entry at the
1979 // top and a single exit at the bottom.
1980 // The point of exit cannot be a branch out of the structured block.
1981 // longjmp() and throw() must not violate the entry/exit criteria.
1982 CS->getCapturedDecl()->setNothrow();
1983
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001984 getCurFunction()->setHasBranchProtectedScope();
1985
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001986 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
1987 AStmt);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001988}
1989
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001990namespace {
1991/// \brief Helper class for checking canonical form of the OpenMP loops and
1992/// extracting iteration space of each loop in the loop nest, that will be used
1993/// for IR generation.
1994class OpenMPIterationSpaceChecker {
1995 /// \brief Reference to Sema.
1996 Sema &SemaRef;
1997 /// \brief A location for diagnostics (when there is no some better location).
1998 SourceLocation DefaultLoc;
1999 /// \brief A location for diagnostics (when increment is not compatible).
2000 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002001 /// \brief A source location for referring to loop init later.
2002 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002003 /// \brief A source location for referring to condition later.
2004 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002005 /// \brief A source location for referring to increment later.
2006 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002007 /// \brief Loop variable.
2008 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002009 /// \brief Reference to loop variable.
2010 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002011 /// \brief Lower bound (initializer for the var).
2012 Expr *LB;
2013 /// \brief Upper bound.
2014 Expr *UB;
2015 /// \brief Loop step (increment).
2016 Expr *Step;
2017 /// \brief This flag is true when condition is one of:
2018 /// Var < UB
2019 /// Var <= UB
2020 /// UB > Var
2021 /// UB >= Var
2022 bool TestIsLessOp;
2023 /// \brief This flag is true when condition is strict ( < or > ).
2024 bool TestIsStrictOp;
2025 /// \brief This flag is true when step is subtracted on each iteration.
2026 bool SubtractStep;
2027
2028public:
2029 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2030 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00002031 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
2032 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002033 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
2034 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002035 /// \brief Check init-expr for canonical loop form and save loop counter
2036 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002037 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002038 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2039 /// for less/greater and for strict/non-strict comparison.
2040 bool CheckCond(Expr *S);
2041 /// \brief Check incr-expr for canonical loop form and return true if it
2042 /// does not conform, otherwise save loop step (#Step).
2043 bool CheckInc(Expr *S);
2044 /// \brief Return the loop counter variable.
2045 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002046 /// \brief Return the reference expression to loop counter variable.
2047 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002048 /// \brief Source range of the loop init.
2049 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2050 /// \brief Source range of the loop condition.
2051 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2052 /// \brief Source range of the loop increment.
2053 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2054 /// \brief True if the step should be subtracted.
2055 bool ShouldSubtractStep() const { return SubtractStep; }
2056 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002057 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002058 /// \brief Build the precondition expression for the loops.
2059 Expr *BuildPreCond(Scope *S, Expr *Cond) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002060 /// \brief Build reference expression to the counter be used for codegen.
2061 Expr *BuildCounterVar() const;
2062 /// \brief Build initization of the counter be used for codegen.
2063 Expr *BuildCounterInit() const;
2064 /// \brief Build step of the counter be used for codegen.
2065 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002066 /// \brief Return true if any expression is dependent.
2067 bool Dependent() const;
2068
2069private:
2070 /// \brief Check the right-hand side of an assignment in the increment
2071 /// expression.
2072 bool CheckIncRHS(Expr *RHS);
2073 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002074 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002075 /// \brief Helper to set upper bound.
2076 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
2077 const SourceLocation &SL);
2078 /// \brief Helper to set loop increment.
2079 bool SetStep(Expr *NewStep, bool Subtract);
2080};
2081
2082bool OpenMPIterationSpaceChecker::Dependent() const {
2083 if (!Var) {
2084 assert(!LB && !UB && !Step);
2085 return false;
2086 }
2087 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2088 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2089}
2090
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002091bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2092 DeclRefExpr *NewVarRefExpr,
2093 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002094 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002095 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2096 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002097 if (!NewVar || !NewLB)
2098 return true;
2099 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002100 VarRef = NewVarRefExpr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002101 LB = NewLB;
2102 return false;
2103}
2104
2105bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2106 const SourceRange &SR,
2107 const SourceLocation &SL) {
2108 // State consistency checking to ensure correct usage.
2109 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2110 !TestIsLessOp && !TestIsStrictOp);
2111 if (!NewUB)
2112 return true;
2113 UB = NewUB;
2114 TestIsLessOp = LessOp;
2115 TestIsStrictOp = StrictOp;
2116 ConditionSrcRange = SR;
2117 ConditionLoc = SL;
2118 return false;
2119}
2120
2121bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2122 // State consistency checking to ensure correct usage.
2123 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2124 if (!NewStep)
2125 return true;
2126 if (!NewStep->isValueDependent()) {
2127 // Check that the step is integer expression.
2128 SourceLocation StepLoc = NewStep->getLocStart();
2129 ExprResult Val =
2130 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2131 if (Val.isInvalid())
2132 return true;
2133 NewStep = Val.get();
2134
2135 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2136 // If test-expr is of form var relational-op b and relational-op is < or
2137 // <= then incr-expr must cause var to increase on each iteration of the
2138 // loop. If test-expr is of form var relational-op b and relational-op is
2139 // > or >= then incr-expr must cause var to decrease on each iteration of
2140 // the loop.
2141 // If test-expr is of form b relational-op var and relational-op is < or
2142 // <= then incr-expr must cause var to decrease on each iteration of the
2143 // loop. If test-expr is of form b relational-op var and relational-op is
2144 // > or >= then incr-expr must cause var to increase on each iteration of
2145 // the loop.
2146 llvm::APSInt Result;
2147 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2148 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2149 bool IsConstNeg =
2150 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002151 bool IsConstPos =
2152 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002153 bool IsConstZero = IsConstant && !Result.getBoolValue();
2154 if (UB && (IsConstZero ||
2155 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002156 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002157 SemaRef.Diag(NewStep->getExprLoc(),
2158 diag::err_omp_loop_incr_not_compatible)
2159 << Var << TestIsLessOp << NewStep->getSourceRange();
2160 SemaRef.Diag(ConditionLoc,
2161 diag::note_omp_loop_cond_requres_compatible_incr)
2162 << TestIsLessOp << ConditionSrcRange;
2163 return true;
2164 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002165 if (TestIsLessOp == Subtract) {
2166 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2167 NewStep).get();
2168 Subtract = !Subtract;
2169 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002170 }
2171
2172 Step = NewStep;
2173 SubtractStep = Subtract;
2174 return false;
2175}
2176
Alexey Bataev9c821032015-04-30 04:23:23 +00002177bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002178 // Check init-expr for canonical loop form and save loop counter
2179 // variable - #Var and its initialization value - #LB.
2180 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2181 // var = lb
2182 // integer-type var = lb
2183 // random-access-iterator-type var = lb
2184 // pointer-type var = lb
2185 //
2186 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002187 if (EmitDiags) {
2188 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2189 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002190 return true;
2191 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002192 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002193 if (Expr *E = dyn_cast<Expr>(S))
2194 S = E->IgnoreParens();
2195 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2196 if (BO->getOpcode() == BO_Assign)
2197 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002198 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002199 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002200 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2201 if (DS->isSingleDecl()) {
2202 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2203 if (Var->hasInit()) {
2204 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002205 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002206 SemaRef.Diag(S->getLocStart(),
2207 diag::ext_omp_loop_not_canonical_init)
2208 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002209 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002210 }
2211 }
2212 }
2213 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2214 if (CE->getOperator() == OO_Equal)
2215 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002216 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2217 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002218
Alexey Bataev9c821032015-04-30 04:23:23 +00002219 if (EmitDiags) {
2220 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2221 << S->getSourceRange();
2222 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002223 return true;
2224}
2225
Alexey Bataev23b69422014-06-18 07:08:49 +00002226/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002227/// variable (which may be the loop variable) if possible.
2228static const VarDecl *GetInitVarDecl(const Expr *E) {
2229 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002230 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002231 E = E->IgnoreParenImpCasts();
2232 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2233 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2234 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
2235 CE->getArg(0) != nullptr)
2236 E = CE->getArg(0)->IgnoreParenImpCasts();
2237 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2238 if (!DRE)
2239 return nullptr;
2240 return dyn_cast<VarDecl>(DRE->getDecl());
2241}
2242
2243bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2244 // Check test-expr for canonical form, save upper-bound UB, flags for
2245 // less/greater and for strict/non-strict comparison.
2246 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2247 // var relational-op b
2248 // b relational-op var
2249 //
2250 if (!S) {
2251 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2252 return true;
2253 }
2254 S = S->IgnoreParenImpCasts();
2255 SourceLocation CondLoc = S->getLocStart();
2256 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2257 if (BO->isRelationalOp()) {
2258 if (GetInitVarDecl(BO->getLHS()) == Var)
2259 return SetUB(BO->getRHS(),
2260 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2261 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2262 BO->getSourceRange(), BO->getOperatorLoc());
2263 if (GetInitVarDecl(BO->getRHS()) == Var)
2264 return SetUB(BO->getLHS(),
2265 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2266 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2267 BO->getSourceRange(), BO->getOperatorLoc());
2268 }
2269 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2270 if (CE->getNumArgs() == 2) {
2271 auto Op = CE->getOperator();
2272 switch (Op) {
2273 case OO_Greater:
2274 case OO_GreaterEqual:
2275 case OO_Less:
2276 case OO_LessEqual:
2277 if (GetInitVarDecl(CE->getArg(0)) == Var)
2278 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2279 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2280 CE->getOperatorLoc());
2281 if (GetInitVarDecl(CE->getArg(1)) == Var)
2282 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2283 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2284 CE->getOperatorLoc());
2285 break;
2286 default:
2287 break;
2288 }
2289 }
2290 }
2291 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2292 << S->getSourceRange() << Var;
2293 return true;
2294}
2295
2296bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2297 // RHS of canonical loop form increment can be:
2298 // var + incr
2299 // incr + var
2300 // var - incr
2301 //
2302 RHS = RHS->IgnoreParenImpCasts();
2303 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2304 if (BO->isAdditiveOp()) {
2305 bool IsAdd = BO->getOpcode() == BO_Add;
2306 if (GetInitVarDecl(BO->getLHS()) == Var)
2307 return SetStep(BO->getRHS(), !IsAdd);
2308 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2309 return SetStep(BO->getLHS(), false);
2310 }
2311 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2312 bool IsAdd = CE->getOperator() == OO_Plus;
2313 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2314 if (GetInitVarDecl(CE->getArg(0)) == Var)
2315 return SetStep(CE->getArg(1), !IsAdd);
2316 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2317 return SetStep(CE->getArg(0), false);
2318 }
2319 }
2320 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2321 << RHS->getSourceRange() << Var;
2322 return true;
2323}
2324
2325bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2326 // Check incr-expr for canonical loop form and return true if it
2327 // does not conform.
2328 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2329 // ++var
2330 // var++
2331 // --var
2332 // var--
2333 // var += incr
2334 // var -= incr
2335 // var = var + incr
2336 // var = incr + var
2337 // var = var - incr
2338 //
2339 if (!S) {
2340 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2341 return true;
2342 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002343 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002344 S = S->IgnoreParens();
2345 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2346 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2347 return SetStep(
2348 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2349 (UO->isDecrementOp() ? -1 : 1)).get(),
2350 false);
2351 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2352 switch (BO->getOpcode()) {
2353 case BO_AddAssign:
2354 case BO_SubAssign:
2355 if (GetInitVarDecl(BO->getLHS()) == Var)
2356 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2357 break;
2358 case BO_Assign:
2359 if (GetInitVarDecl(BO->getLHS()) == Var)
2360 return CheckIncRHS(BO->getRHS());
2361 break;
2362 default:
2363 break;
2364 }
2365 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2366 switch (CE->getOperator()) {
2367 case OO_PlusPlus:
2368 case OO_MinusMinus:
2369 if (GetInitVarDecl(CE->getArg(0)) == Var)
2370 return SetStep(
2371 SemaRef.ActOnIntegerConstant(
2372 CE->getLocStart(),
2373 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2374 false);
2375 break;
2376 case OO_PlusEqual:
2377 case OO_MinusEqual:
2378 if (GetInitVarDecl(CE->getArg(0)) == Var)
2379 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2380 break;
2381 case OO_Equal:
2382 if (GetInitVarDecl(CE->getArg(0)) == Var)
2383 return CheckIncRHS(CE->getArg(1));
2384 break;
2385 default:
2386 break;
2387 }
2388 }
2389 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2390 << S->getSourceRange() << Var;
2391 return true;
2392}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002393
2394/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002395Expr *
2396OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2397 const bool LimitedType) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002398 ExprResult Diff;
2399 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2400 SemaRef.getLangOpts().CPlusPlus) {
2401 // Upper - Lower
2402 Expr *Upper = TestIsLessOp ? UB : LB;
2403 Expr *Lower = TestIsLessOp ? LB : UB;
2404
2405 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2406
2407 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2408 // BuildBinOp already emitted error, this one is to point user to upper
2409 // and lower bound, and to tell what is passed to 'operator-'.
2410 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2411 << Upper->getSourceRange() << Lower->getSourceRange();
2412 return nullptr;
2413 }
2414 }
2415
2416 if (!Diff.isUsable())
2417 return nullptr;
2418
2419 // Upper - Lower [- 1]
2420 if (TestIsStrictOp)
2421 Diff = SemaRef.BuildBinOp(
2422 S, DefaultLoc, BO_Sub, Diff.get(),
2423 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2424 if (!Diff.isUsable())
2425 return nullptr;
2426
2427 // Upper - Lower [- 1] + Step
2428 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2429 Step->IgnoreImplicit());
2430 if (!Diff.isUsable())
2431 return nullptr;
2432
2433 // Parentheses (for dumping/debugging purposes only).
2434 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2435 if (!Diff.isUsable())
2436 return nullptr;
2437
2438 // (Upper - Lower [- 1] + Step) / Step
2439 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2440 Step->IgnoreImplicit());
2441 if (!Diff.isUsable())
2442 return nullptr;
2443
Alexander Musman174b3ca2014-10-06 11:16:29 +00002444 // OpenMP runtime requires 32-bit or 64-bit loop variables.
2445 if (LimitedType) {
2446 auto &C = SemaRef.Context;
2447 QualType Type = Diff.get()->getType();
2448 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2449 if (NewSize != C.getTypeSize(Type)) {
2450 if (NewSize < C.getTypeSize(Type)) {
2451 assert(NewSize == 64 && "incorrect loop var size");
2452 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2453 << InitSrcRange << ConditionSrcRange;
2454 }
2455 QualType NewType = C.getIntTypeForBitwidth(
2456 NewSize, Type->hasSignedIntegerRepresentation());
2457 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2458 Sema::AA_Converting, true);
2459 if (!Diff.isUsable())
2460 return nullptr;
2461 }
2462 }
2463
Alexander Musmana5f070a2014-10-01 06:03:56 +00002464 return Diff.get();
2465}
2466
Alexey Bataev62dbb972015-04-22 11:59:37 +00002467Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
2468 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
2469 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
2470 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
2471 auto CondExpr = SemaRef.BuildBinOp(
2472 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
2473 : (TestIsStrictOp ? BO_GT : BO_GE),
2474 LB, UB);
2475 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
2476 // Otherwise use original loop conditon and evaluate it in runtime.
2477 return CondExpr.isUsable() ? CondExpr.get() : Cond;
2478}
2479
Alexander Musmana5f070a2014-10-01 06:03:56 +00002480/// \brief Build reference expression to the counter be used for codegen.
2481Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
Alexey Bataev39f915b82015-05-08 10:41:21 +00002482 return buildDeclRefExpr(SemaRef, Var, Var->getType(), DefaultLoc);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002483}
2484
2485/// \brief Build initization of the counter be used for codegen.
2486Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2487
2488/// \brief Build step of the counter be used for codegen.
2489Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2490
2491/// \brief Iteration space of a single for loop.
2492struct LoopIterationSpace {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002493 /// \brief Condition of the loop.
2494 Expr *PreCond;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002495 /// \brief This expression calculates the number of iterations in the loop.
2496 /// It is always possible to calculate it before starting the loop.
2497 Expr *NumIterations;
2498 /// \brief The loop counter variable.
2499 Expr *CounterVar;
2500 /// \brief This is initializer for the initial value of #CounterVar.
2501 Expr *CounterInit;
2502 /// \brief This is step for the #CounterVar used to generate its update:
2503 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2504 Expr *CounterStep;
2505 /// \brief Should step be subtracted?
2506 bool Subtract;
2507 /// \brief Source range of the loop init.
2508 SourceRange InitSrcRange;
2509 /// \brief Source range of the loop condition.
2510 SourceRange CondSrcRange;
2511 /// \brief Source range of the loop increment.
2512 SourceRange IncSrcRange;
2513};
2514
Alexey Bataev23b69422014-06-18 07:08:49 +00002515} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002516
Alexey Bataev9c821032015-04-30 04:23:23 +00002517void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
2518 assert(getLangOpts().OpenMP && "OpenMP is not active.");
2519 assert(Init && "Expected loop in canonical form.");
2520 unsigned CollapseIteration = DSAStack->getCollapseNumber();
2521 if (CollapseIteration > 0 &&
2522 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2523 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
2524 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
2525 DSAStack->addLoopControlVariable(ISC.GetLoopVar());
2526 }
2527 DSAStack->setCollapseNumber(CollapseIteration - 1);
2528 }
2529}
2530
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002531/// \brief Called on a for stmt to check and extract its iteration space
2532/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00002533static bool CheckOpenMPIterationSpace(
2534 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2535 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2536 Expr *NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002537 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2538 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002539 // OpenMP [2.6, Canonical Loop Form]
2540 // for (init-expr; test-expr; incr-expr) structured-block
2541 auto For = dyn_cast_or_null<ForStmt>(S);
2542 if (!For) {
2543 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002544 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2545 << NestedLoopCount << (CurrentNestedLoopCount > 0)
2546 << CurrentNestedLoopCount;
2547 if (NestedLoopCount > 1)
2548 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2549 diag::note_omp_collapse_expr)
2550 << NestedLoopCountExpr->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002551 return true;
2552 }
2553 assert(For->getBody());
2554
2555 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2556
2557 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002558 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002559 if (ISC.CheckInit(Init)) {
2560 return true;
2561 }
2562
2563 bool HasErrors = false;
2564
2565 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002566 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002567
2568 // OpenMP [2.6, Canonical Loop Form]
2569 // Var is one of the following:
2570 // A variable of signed or unsigned integer type.
2571 // For C++, a variable of a random access iterator type.
2572 // For C, a variable of a pointer type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002573 auto VarType = Var->getType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002574 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2575 !VarType->isPointerType() &&
2576 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2577 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2578 << SemaRef.getLangOpts().CPlusPlus;
2579 HasErrors = true;
2580 }
2581
Alexey Bataev4acb8592014-07-07 13:01:15 +00002582 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2583 // Construct
2584 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2585 // parallel for construct is (are) private.
2586 // The loop iteration variable in the associated for-loop of a simd construct
2587 // with just one associated for-loop is linear with a constant-linear-step
2588 // that is the increment of the associated for-loop.
2589 // Exclude loop var from the list of variables with implicitly defined data
2590 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00002591 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002592
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002593 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2594 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00002595 // The loop iteration variable in the associated for-loop of a simd construct
2596 // with just one associated for-loop may be listed in a linear clause with a
2597 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00002598 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2599 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002600 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002601 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2602 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2603 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002604 auto PredeterminedCKind =
2605 isOpenMPSimdDirective(DKind)
2606 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2607 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002608 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00002609 DVar.CKind != OMPC_threadprivate && DVar.CKind != PredeterminedCKind) ||
Alexander Musmanf82886e2014-09-18 05:12:34 +00002610 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2611 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00002612 DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_threadprivate)) &&
2613 ((DVar.CKind != OMPC_private && DVar.CKind != OMPC_threadprivate) ||
2614 DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002615 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00002616 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2617 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataevf2453a02015-05-06 07:25:08 +00002618 if (DVar.RefExpr == nullptr)
2619 DVar.CKind = PredeterminedCKind;
2620 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002621 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002622 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002623 // Make the loop iteration variable private (for worksharing constructs),
2624 // linear (for simd directives with the only one associated loop) or
2625 // lastprivate (for simd directives with several collapsed loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00002626 if (DVar.CKind == OMPC_unknown)
2627 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2628 /*FromParent=*/false);
Alexey Bataev9c821032015-04-30 04:23:23 +00002629 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002630 }
2631
Alexey Bataev7ff55242014-06-19 09:13:45 +00002632 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00002633
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002634 // Check test-expr.
2635 HasErrors |= ISC.CheckCond(For->getCond());
2636
2637 // Check incr-expr.
2638 HasErrors |= ISC.CheckInc(For->getInc());
2639
Alexander Musmana5f070a2014-10-01 06:03:56 +00002640 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002641 return HasErrors;
2642
Alexander Musmana5f070a2014-10-01 06:03:56 +00002643 // Build the loop's iteration space representation.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002644 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
Alexander Musman174b3ca2014-10-06 11:16:29 +00002645 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2646 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
Alexander Musmana5f070a2014-10-01 06:03:56 +00002647 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2648 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2649 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2650 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2651 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2652 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2653 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2654
Alexey Bataev62dbb972015-04-22 11:59:37 +00002655 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
2656 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00002657 ResultIterSpace.CounterVar == nullptr ||
2658 ResultIterSpace.CounterInit == nullptr ||
2659 ResultIterSpace.CounterStep == nullptr);
2660
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002661 return HasErrors;
2662}
2663
Alexander Musmana5f070a2014-10-01 06:03:56 +00002664/// \brief Build 'VarRef = Start + Iter * Step'.
2665static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2666 SourceLocation Loc, ExprResult VarRef,
2667 ExprResult Start, ExprResult Iter,
2668 ExprResult Step, bool Subtract) {
2669 // Add parentheses (for debugging purposes only).
2670 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2671 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2672 !Step.isUsable())
2673 return ExprError();
2674
2675 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2676 Step.get()->IgnoreImplicit());
2677 if (!Update.isUsable())
2678 return ExprError();
2679
2680 // Build 'VarRef = Start + Iter * Step'.
2681 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2682 Start.get()->IgnoreImplicit(), Update.get());
2683 if (!Update.isUsable())
2684 return ExprError();
2685
2686 Update = SemaRef.PerformImplicitConversion(
2687 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2688 if (!Update.isUsable())
2689 return ExprError();
2690
2691 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2692 return Update;
2693}
2694
2695/// \brief Convert integer expression \a E to make it have at least \a Bits
2696/// bits.
2697static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2698 Sema &SemaRef) {
2699 if (E == nullptr)
2700 return ExprError();
2701 auto &C = SemaRef.Context;
2702 QualType OldType = E->getType();
2703 unsigned HasBits = C.getTypeSize(OldType);
2704 if (HasBits >= Bits)
2705 return ExprResult(E);
2706 // OK to convert to signed, because new type has more bits than old.
2707 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2708 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2709 true);
2710}
2711
2712/// \brief Check if the given expression \a E is a constant integer that fits
2713/// into \a Bits bits.
2714static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2715 if (E == nullptr)
2716 return false;
2717 llvm::APSInt Result;
2718 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2719 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2720 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002721}
2722
2723/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00002724/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2725/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002726static unsigned
2727CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2728 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002729 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00002730 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002731 unsigned NestedLoopCount = 1;
2732 if (NestedLoopCountExpr) {
2733 // Found 'collapse' clause - calculate collapse number.
2734 llvm::APSInt Result;
2735 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2736 NestedLoopCount = Result.getLimitedValue();
2737 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002738 // This is helper routine for loop directives (e.g., 'for', 'simd',
2739 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00002740 SmallVector<LoopIterationSpace, 4> IterSpaces;
2741 IterSpaces.resize(NestedLoopCount);
2742 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002743 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002744 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev4acb8592014-07-07 13:01:15 +00002745 NestedLoopCount, NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002746 VarsWithImplicitDSA, IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00002747 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002748 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002749 // OpenMP [2.8.1, simd construct, Restrictions]
2750 // All loops associated with the construct must be perfectly nested; that
2751 // is, there must be no intervening code nor any OpenMP directive between
2752 // any two loops.
2753 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002754 }
2755
Alexander Musmana5f070a2014-10-01 06:03:56 +00002756 Built.clear(/* size */ NestedLoopCount);
2757
2758 if (SemaRef.CurContext->isDependentContext())
2759 return NestedLoopCount;
2760
2761 // An example of what is generated for the following code:
2762 //
2763 // #pragma omp simd collapse(2)
2764 // for (i = 0; i < NI; ++i)
2765 // for (j = J0; j < NJ; j+=2) {
2766 // <loop body>
2767 // }
2768 //
2769 // We generate the code below.
2770 // Note: the loop body may be outlined in CodeGen.
2771 // Note: some counters may be C++ classes, operator- is used to find number of
2772 // iterations and operator+= to calculate counter value.
2773 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2774 // or i64 is currently supported).
2775 //
2776 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2777 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2778 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2779 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2780 // // similar updates for vars in clauses (e.g. 'linear')
2781 // <loop body (using local i and j)>
2782 // }
2783 // i = NI; // assign final values of counters
2784 // j = NJ;
2785 //
2786
2787 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2788 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002789 // Precondition tests if there is at least one iteration (all conditions are
2790 // true).
2791 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002792 auto N0 = IterSpaces[0].NumIterations;
2793 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2794 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2795
2796 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2797 return NestedLoopCount;
2798
2799 auto &C = SemaRef.Context;
2800 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
2801
2802 Scope *CurScope = DSA.getCurScope();
2803 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002804 if (PreCond.isUsable()) {
2805 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
2806 PreCond.get(), IterSpaces[Cnt].PreCond);
2807 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002808 auto N = IterSpaces[Cnt].NumIterations;
2809 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
2810 if (LastIteration32.isUsable())
2811 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2812 LastIteration32.get(), N);
2813 if (LastIteration64.isUsable())
2814 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2815 LastIteration64.get(), N);
2816 }
2817
2818 // Choose either the 32-bit or 64-bit version.
2819 ExprResult LastIteration = LastIteration64;
2820 if (LastIteration32.isUsable() &&
2821 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
2822 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
2823 FitsInto(
2824 32 /* Bits */,
2825 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
2826 LastIteration64.get(), SemaRef)))
2827 LastIteration = LastIteration32;
2828
2829 if (!LastIteration.isUsable())
2830 return 0;
2831
2832 // Save the number of iterations.
2833 ExprResult NumIterations = LastIteration;
2834 {
2835 LastIteration = SemaRef.BuildBinOp(
2836 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
2837 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2838 if (!LastIteration.isUsable())
2839 return 0;
2840 }
2841
2842 // Calculate the last iteration number beforehand instead of doing this on
2843 // each iteration. Do not do this if the number of iterations may be kfold-ed.
2844 llvm::APSInt Result;
2845 bool IsConstant =
2846 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
2847 ExprResult CalcLastIteration;
2848 if (!IsConstant) {
2849 SourceLocation SaveLoc;
2850 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00002851 buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00002852 ".omp.last.iteration");
Alexey Bataev39f915b82015-05-08 10:41:21 +00002853 ExprResult SaveRef = buildDeclRefExpr(
2854 SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002855 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
2856 SaveRef.get(), LastIteration.get());
2857 LastIteration = SaveRef;
2858
2859 // Prepare SaveRef + 1.
2860 NumIterations = SemaRef.BuildBinOp(
2861 CurScope, SaveLoc, BO_Add, SaveRef.get(),
2862 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2863 if (!NumIterations.isUsable())
2864 return 0;
2865 }
2866
2867 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
2868
Alexander Musmanc6388682014-12-15 07:07:06 +00002869 QualType VType = LastIteration.get()->getType();
2870 // Build variables passed into runtime, nesessary for worksharing directives.
2871 ExprResult LB, UB, IL, ST, EUB;
2872 if (isOpenMPWorksharingDirective(DKind)) {
2873 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00002874 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
2875 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002876 SemaRef.AddInitializerToDecl(
2877 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2878 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2879
2880 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00002881 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
2882 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002883 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
2884 /*DirectInit*/ false,
2885 /*TypeMayContainAuto*/ false);
2886
2887 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
2888 // This will be used to implement clause 'lastprivate'.
2889 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002890 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
2891 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002892 SemaRef.AddInitializerToDecl(
2893 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2894 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2895
2896 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev39f915b82015-05-08 10:41:21 +00002897 VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
2898 ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002899 SemaRef.AddInitializerToDecl(
2900 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
2901 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2902
2903 // Build expression: UB = min(UB, LastIteration)
2904 // It is nesessary for CodeGen of directives with static scheduling.
2905 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
2906 UB.get(), LastIteration.get());
2907 ExprResult CondOp = SemaRef.ActOnConditionalOp(
2908 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
2909 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
2910 CondOp.get());
2911 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
2912 }
2913
2914 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002915 ExprResult IV;
2916 ExprResult Init;
2917 {
Alexey Bataev39f915b82015-05-08 10:41:21 +00002918 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
2919 IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002920 Expr *RHS = isOpenMPWorksharingDirective(DKind)
2921 ? LB.get()
2922 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
2923 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
2924 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002925 }
2926
Alexander Musmanc6388682014-12-15 07:07:06 +00002927 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002928 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00002929 ExprResult Cond =
2930 isOpenMPWorksharingDirective(DKind)
2931 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
2932 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
2933 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002934 // Loop condition with 1 iteration separated (IV < LastIteration)
2935 ExprResult SeparatedCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT,
2936 IV.get(), LastIteration.get());
2937
2938 // Loop increment (IV = IV + 1)
2939 SourceLocation IncLoc;
2940 ExprResult Inc =
2941 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
2942 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
2943 if (!Inc.isUsable())
2944 return 0;
2945 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00002946 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
2947 if (!Inc.isUsable())
2948 return 0;
2949
2950 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
2951 // Used for directives with static scheduling.
2952 ExprResult NextLB, NextUB;
2953 if (isOpenMPWorksharingDirective(DKind)) {
2954 // LB + ST
2955 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
2956 if (!NextLB.isUsable())
2957 return 0;
2958 // LB = LB + ST
2959 NextLB =
2960 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
2961 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
2962 if (!NextLB.isUsable())
2963 return 0;
2964 // UB + ST
2965 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
2966 if (!NextUB.isUsable())
2967 return 0;
2968 // UB = UB + ST
2969 NextUB =
2970 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
2971 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
2972 if (!NextUB.isUsable())
2973 return 0;
2974 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002975
2976 // Build updates and final values of the loop counters.
2977 bool HasErrors = false;
2978 Built.Counters.resize(NestedLoopCount);
2979 Built.Updates.resize(NestedLoopCount);
2980 Built.Finals.resize(NestedLoopCount);
2981 {
2982 ExprResult Div;
2983 // Go from inner nested loop to outer.
2984 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
2985 LoopIterationSpace &IS = IterSpaces[Cnt];
2986 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
2987 // Build: Iter = (IV / Div) % IS.NumIters
2988 // where Div is product of previous iterations' IS.NumIters.
2989 ExprResult Iter;
2990 if (Div.isUsable()) {
2991 Iter =
2992 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
2993 } else {
2994 Iter = IV;
2995 assert((Cnt == (int)NestedLoopCount - 1) &&
2996 "unusable div expected on first iteration only");
2997 }
2998
2999 if (Cnt != 0 && Iter.isUsable())
3000 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
3001 IS.NumIterations);
3002 if (!Iter.isUsable()) {
3003 HasErrors = true;
3004 break;
3005 }
3006
Alexey Bataev39f915b82015-05-08 10:41:21 +00003007 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
3008 auto *CounterVar = buildDeclRefExpr(
3009 SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
3010 IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
3011 /*RefersToCapture=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003012 ExprResult Update =
Alexey Bataev39f915b82015-05-08 10:41:21 +00003013 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003014 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
3015 if (!Update.isUsable()) {
3016 HasErrors = true;
3017 break;
3018 }
3019
3020 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
3021 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00003022 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003023 IS.NumIterations, IS.CounterStep, IS.Subtract);
3024 if (!Final.isUsable()) {
3025 HasErrors = true;
3026 break;
3027 }
3028
3029 // Build Div for the next iteration: Div <- Div * IS.NumIters
3030 if (Cnt != 0) {
3031 if (Div.isUnset())
3032 Div = IS.NumIterations;
3033 else
3034 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
3035 IS.NumIterations);
3036
3037 // Add parentheses (for debugging purposes only).
3038 if (Div.isUsable())
3039 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
3040 if (!Div.isUsable()) {
3041 HasErrors = true;
3042 break;
3043 }
3044 }
3045 if (!Update.isUsable() || !Final.isUsable()) {
3046 HasErrors = true;
3047 break;
3048 }
3049 // Save results
3050 Built.Counters[Cnt] = IS.CounterVar;
3051 Built.Updates[Cnt] = Update.get();
3052 Built.Finals[Cnt] = Final.get();
3053 }
3054 }
3055
3056 if (HasErrors)
3057 return 0;
3058
3059 // Save results
3060 Built.IterationVarRef = IV.get();
3061 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00003062 Built.NumIterations = NumIterations.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003063 Built.CalcLastIteration = CalcLastIteration.get();
3064 Built.PreCond = PreCond.get();
3065 Built.Cond = Cond.get();
3066 Built.SeparatedCond = SeparatedCond.get();
3067 Built.Init = Init.get();
3068 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00003069 Built.LB = LB.get();
3070 Built.UB = UB.get();
3071 Built.IL = IL.get();
3072 Built.ST = ST.get();
3073 Built.EUB = EUB.get();
3074 Built.NLB = NextLB.get();
3075 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003076
Alexey Bataevabfc0692014-06-25 06:52:00 +00003077 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003078}
3079
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003080static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Alexey Bataevc925aa32015-04-27 08:00:32 +00003081 auto &&CollapseFilter = [](const OMPClause *C) -> bool {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003082 return C->getClauseKind() == OMPC_collapse;
3083 };
3084 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
Alexey Bataevc925aa32015-04-27 08:00:32 +00003085 Clauses, std::move(CollapseFilter));
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003086 if (I)
3087 return cast<OMPCollapseClause>(*I)->getNumForLoops();
3088 return nullptr;
3089}
3090
Alexey Bataev4acb8592014-07-07 13:01:15 +00003091StmtResult Sema::ActOnOpenMPSimdDirective(
3092 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3093 SourceLocation EndLoc,
3094 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003095 OMPLoopDirective::HelperExprs B;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003096 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003097 unsigned NestedLoopCount =
3098 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003099 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003100 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003101 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003102
Alexander Musmana5f070a2014-10-01 06:03:56 +00003103 assert((CurContext->isDependentContext() || B.builtAll()) &&
3104 "omp simd loop exprs were not built");
3105
Alexander Musman3276a272015-03-21 10:12:56 +00003106 if (!CurContext->isDependentContext()) {
3107 // Finalize the clauses that need pre-built expressions for CodeGen.
3108 for (auto C : Clauses) {
3109 if (auto LC = dyn_cast<OMPLinearClause>(C))
3110 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3111 B.NumIterations, *this, CurScope))
3112 return StmtError();
3113 }
3114 }
3115
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003116 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003117 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3118 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003119}
3120
Alexey Bataev4acb8592014-07-07 13:01:15 +00003121StmtResult Sema::ActOnOpenMPForDirective(
3122 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3123 SourceLocation EndLoc,
3124 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003125 OMPLoopDirective::HelperExprs B;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003126 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003127 unsigned NestedLoopCount =
3128 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003129 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003130 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00003131 return StmtError();
3132
Alexander Musmana5f070a2014-10-01 06:03:56 +00003133 assert((CurContext->isDependentContext() || B.builtAll()) &&
3134 "omp for loop exprs were not built");
3135
Alexey Bataevf29276e2014-06-18 04:14:57 +00003136 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003137 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3138 Clauses, AStmt, B);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003139}
3140
Alexander Musmanf82886e2014-09-18 05:12:34 +00003141StmtResult Sema::ActOnOpenMPForSimdDirective(
3142 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3143 SourceLocation EndLoc,
3144 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003145 OMPLoopDirective::HelperExprs B;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003146 // In presence of clause 'collapse', it will define the nested loops number.
3147 unsigned NestedLoopCount =
3148 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003149 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003150 if (NestedLoopCount == 0)
3151 return StmtError();
3152
Alexander Musmanc6388682014-12-15 07:07:06 +00003153 assert((CurContext->isDependentContext() || B.builtAll()) &&
3154 "omp for simd loop exprs were not built");
3155
Alexander Musmanf82886e2014-09-18 05:12:34 +00003156 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003157 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3158 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003159}
3160
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003161StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3162 Stmt *AStmt,
3163 SourceLocation StartLoc,
3164 SourceLocation EndLoc) {
3165 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3166 auto BaseStmt = AStmt;
3167 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3168 BaseStmt = CS->getCapturedStmt();
3169 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3170 auto S = C->children();
3171 if (!S)
3172 return StmtError();
3173 // All associated statements must be '#pragma omp section' except for
3174 // the first one.
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003175 for (++S; S; ++S) {
3176 auto SectionStmt = *S;
3177 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3178 if (SectionStmt)
3179 Diag(SectionStmt->getLocStart(),
3180 diag::err_omp_sections_substmt_not_section);
3181 return StmtError();
3182 }
3183 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003184 } else {
3185 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3186 return StmtError();
3187 }
3188
3189 getCurFunction()->setHasBranchProtectedScope();
3190
3191 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3192 AStmt);
3193}
3194
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003195StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3196 SourceLocation StartLoc,
3197 SourceLocation EndLoc) {
3198 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3199
3200 getCurFunction()->setHasBranchProtectedScope();
3201
3202 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3203}
3204
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003205StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3206 Stmt *AStmt,
3207 SourceLocation StartLoc,
3208 SourceLocation EndLoc) {
Alexey Bataev74a05c92014-07-15 02:55:09 +00003209 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3210
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003211 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00003212
Alexey Bataev3255bf32015-01-19 05:20:46 +00003213 // OpenMP [2.7.3, single Construct, Restrictions]
3214 // The copyprivate clause must not be used with the nowait clause.
3215 OMPClause *Nowait = nullptr;
3216 OMPClause *Copyprivate = nullptr;
3217 for (auto *Clause : Clauses) {
3218 if (Clause->getClauseKind() == OMPC_nowait)
3219 Nowait = Clause;
3220 else if (Clause->getClauseKind() == OMPC_copyprivate)
3221 Copyprivate = Clause;
3222 if (Copyprivate && Nowait) {
3223 Diag(Copyprivate->getLocStart(),
3224 diag::err_omp_single_copyprivate_with_nowait);
3225 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3226 return StmtError();
3227 }
3228 }
3229
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003230 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3231}
3232
Alexander Musman80c22892014-07-17 08:54:58 +00003233StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3234 SourceLocation StartLoc,
3235 SourceLocation EndLoc) {
3236 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3237
3238 getCurFunction()->setHasBranchProtectedScope();
3239
3240 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3241}
3242
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003243StmtResult
3244Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3245 Stmt *AStmt, SourceLocation StartLoc,
3246 SourceLocation EndLoc) {
3247 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3248
3249 getCurFunction()->setHasBranchProtectedScope();
3250
3251 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3252 AStmt);
3253}
3254
Alexey Bataev4acb8592014-07-07 13:01:15 +00003255StmtResult Sema::ActOnOpenMPParallelForDirective(
3256 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3257 SourceLocation EndLoc,
3258 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3259 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3260 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3261 // 1.2.2 OpenMP Language Terminology
3262 // Structured block - An executable statement with a single entry at the
3263 // top and a single exit at the bottom.
3264 // The point of exit cannot be a branch out of the structured block.
3265 // longjmp() and throw() must not violate the entry/exit criteria.
3266 CS->getCapturedDecl()->setNothrow();
3267
Alexander Musmanc6388682014-12-15 07:07:06 +00003268 OMPLoopDirective::HelperExprs B;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003269 // In presence of clause 'collapse', it will define the nested loops number.
3270 unsigned NestedLoopCount =
3271 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003272 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003273 if (NestedLoopCount == 0)
3274 return StmtError();
3275
Alexander Musmana5f070a2014-10-01 06:03:56 +00003276 assert((CurContext->isDependentContext() || B.builtAll()) &&
3277 "omp parallel for loop exprs were not built");
3278
Alexey Bataev4acb8592014-07-07 13:01:15 +00003279 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003280 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3281 NestedLoopCount, Clauses, AStmt, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003282}
3283
Alexander Musmane4e893b2014-09-23 09:33:00 +00003284StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3285 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3286 SourceLocation EndLoc,
3287 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3288 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3289 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3290 // 1.2.2 OpenMP Language Terminology
3291 // Structured block - An executable statement with a single entry at the
3292 // top and a single exit at the bottom.
3293 // The point of exit cannot be a branch out of the structured block.
3294 // longjmp() and throw() must not violate the entry/exit criteria.
3295 CS->getCapturedDecl()->setNothrow();
3296
Alexander Musmanc6388682014-12-15 07:07:06 +00003297 OMPLoopDirective::HelperExprs B;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003298 // In presence of clause 'collapse', it will define the nested loops number.
3299 unsigned NestedLoopCount =
3300 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003301 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003302 if (NestedLoopCount == 0)
3303 return StmtError();
3304
3305 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003306 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00003307 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003308}
3309
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003310StmtResult
3311Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3312 Stmt *AStmt, SourceLocation StartLoc,
3313 SourceLocation EndLoc) {
3314 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3315 auto BaseStmt = AStmt;
3316 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3317 BaseStmt = CS->getCapturedStmt();
3318 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3319 auto S = C->children();
3320 if (!S)
3321 return StmtError();
3322 // All associated statements must be '#pragma omp section' except for
3323 // the first one.
3324 for (++S; S; ++S) {
3325 auto SectionStmt = *S;
3326 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3327 if (SectionStmt)
3328 Diag(SectionStmt->getLocStart(),
3329 diag::err_omp_parallel_sections_substmt_not_section);
3330 return StmtError();
3331 }
3332 }
3333 } else {
3334 Diag(AStmt->getLocStart(),
3335 diag::err_omp_parallel_sections_not_compound_stmt);
3336 return StmtError();
3337 }
3338
3339 getCurFunction()->setHasBranchProtectedScope();
3340
3341 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3342 Clauses, AStmt);
3343}
3344
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003345StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3346 Stmt *AStmt, SourceLocation StartLoc,
3347 SourceLocation EndLoc) {
3348 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3349 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3350 // 1.2.2 OpenMP Language Terminology
3351 // Structured block - An executable statement with a single entry at the
3352 // top and a single exit at the bottom.
3353 // The point of exit cannot be a branch out of the structured block.
3354 // longjmp() and throw() must not violate the entry/exit criteria.
3355 CS->getCapturedDecl()->setNothrow();
3356
3357 getCurFunction()->setHasBranchProtectedScope();
3358
3359 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3360}
3361
Alexey Bataev68446b72014-07-18 07:47:19 +00003362StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3363 SourceLocation EndLoc) {
3364 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3365}
3366
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003367StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3368 SourceLocation EndLoc) {
3369 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3370}
3371
Alexey Bataev2df347a2014-07-18 10:17:07 +00003372StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3373 SourceLocation EndLoc) {
3374 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3375}
3376
Alexey Bataev6125da92014-07-21 11:26:11 +00003377StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3378 SourceLocation StartLoc,
3379 SourceLocation EndLoc) {
3380 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3381 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3382}
3383
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003384StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3385 SourceLocation StartLoc,
3386 SourceLocation EndLoc) {
3387 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3388
3389 getCurFunction()->setHasBranchProtectedScope();
3390
3391 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3392}
3393
Alexey Bataev1d160b12015-03-13 12:27:31 +00003394namespace {
3395/// \brief Helper class for checking expression in 'omp atomic [update]'
3396/// construct.
3397class OpenMPAtomicUpdateChecker {
3398 /// \brief Error results for atomic update expressions.
3399 enum ExprAnalysisErrorCode {
3400 /// \brief A statement is not an expression statement.
3401 NotAnExpression,
3402 /// \brief Expression is not builtin binary or unary operation.
3403 NotABinaryOrUnaryExpression,
3404 /// \brief Unary operation is not post-/pre- increment/decrement operation.
3405 NotAnUnaryIncDecExpression,
3406 /// \brief An expression is not of scalar type.
3407 NotAScalarType,
3408 /// \brief A binary operation is not an assignment operation.
3409 NotAnAssignmentOp,
3410 /// \brief RHS part of the binary operation is not a binary expression.
3411 NotABinaryExpression,
3412 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
3413 /// expression.
3414 NotABinaryOperator,
3415 /// \brief RHS binary operation does not have reference to the updated LHS
3416 /// part.
3417 NotAnUpdateExpression,
3418 /// \brief No errors is found.
3419 NoError
3420 };
3421 /// \brief Reference to Sema.
3422 Sema &SemaRef;
3423 /// \brief A location for note diagnostics (when error is found).
3424 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003425 /// \brief 'x' lvalue part of the source atomic expression.
3426 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003427 /// \brief 'expr' rvalue part of the source atomic expression.
3428 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003429 /// \brief Helper expression of the form
3430 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3431 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3432 Expr *UpdateExpr;
3433 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
3434 /// important for non-associative operations.
3435 bool IsXLHSInRHSPart;
3436 BinaryOperatorKind Op;
3437 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003438 /// \brief true if the source expression is a postfix unary operation, false
3439 /// if it is a prefix unary operation.
3440 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003441
3442public:
3443 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00003444 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00003445 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00003446 /// \brief Check specified statement that it is suitable for 'atomic update'
3447 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00003448 /// expression. If DiagId and NoteId == 0, then only check is performed
3449 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00003450 /// \param DiagId Diagnostic which should be emitted if error is found.
3451 /// \param NoteId Diagnostic note for the main error message.
3452 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00003453 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003454 /// \brief Return the 'x' lvalue part of the source atomic expression.
3455 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00003456 /// \brief Return the 'expr' rvalue part of the source atomic expression.
3457 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00003458 /// \brief Return the update expression used in calculation of the updated
3459 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3460 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3461 Expr *getUpdateExpr() const { return UpdateExpr; }
3462 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
3463 /// false otherwise.
3464 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
3465
Alexey Bataevb78ca832015-04-01 03:33:17 +00003466 /// \brief true if the source expression is a postfix unary operation, false
3467 /// if it is a prefix unary operation.
3468 bool isPostfixUpdate() const { return IsPostfixUpdate; }
3469
Alexey Bataev1d160b12015-03-13 12:27:31 +00003470private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00003471 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
3472 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003473};
3474} // namespace
3475
3476bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
3477 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
3478 ExprAnalysisErrorCode ErrorFound = NoError;
3479 SourceLocation ErrorLoc, NoteLoc;
3480 SourceRange ErrorRange, NoteRange;
3481 // Allowed constructs are:
3482 // x = x binop expr;
3483 // x = expr binop x;
3484 if (AtomicBinOp->getOpcode() == BO_Assign) {
3485 X = AtomicBinOp->getLHS();
3486 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
3487 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
3488 if (AtomicInnerBinOp->isMultiplicativeOp() ||
3489 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
3490 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003491 Op = AtomicInnerBinOp->getOpcode();
3492 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003493 auto *LHS = AtomicInnerBinOp->getLHS();
3494 auto *RHS = AtomicInnerBinOp->getRHS();
3495 llvm::FoldingSetNodeID XId, LHSId, RHSId;
3496 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
3497 /*Canonical=*/true);
3498 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
3499 /*Canonical=*/true);
3500 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
3501 /*Canonical=*/true);
3502 if (XId == LHSId) {
3503 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003504 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003505 } else if (XId == RHSId) {
3506 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003507 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003508 } else {
3509 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3510 ErrorRange = AtomicInnerBinOp->getSourceRange();
3511 NoteLoc = X->getExprLoc();
3512 NoteRange = X->getSourceRange();
3513 ErrorFound = NotAnUpdateExpression;
3514 }
3515 } else {
3516 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3517 ErrorRange = AtomicInnerBinOp->getSourceRange();
3518 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
3519 NoteRange = SourceRange(NoteLoc, NoteLoc);
3520 ErrorFound = NotABinaryOperator;
3521 }
3522 } else {
3523 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
3524 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
3525 ErrorFound = NotABinaryExpression;
3526 }
3527 } else {
3528 ErrorLoc = AtomicBinOp->getExprLoc();
3529 ErrorRange = AtomicBinOp->getSourceRange();
3530 NoteLoc = AtomicBinOp->getOperatorLoc();
3531 NoteRange = SourceRange(NoteLoc, NoteLoc);
3532 ErrorFound = NotAnAssignmentOp;
3533 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003534 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003535 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3536 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3537 return true;
3538 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003539 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003540 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003541}
3542
3543bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
3544 unsigned NoteId) {
3545 ExprAnalysisErrorCode ErrorFound = NoError;
3546 SourceLocation ErrorLoc, NoteLoc;
3547 SourceRange ErrorRange, NoteRange;
3548 // Allowed constructs are:
3549 // x++;
3550 // x--;
3551 // ++x;
3552 // --x;
3553 // x binop= expr;
3554 // x = x binop expr;
3555 // x = expr binop x;
3556 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
3557 AtomicBody = AtomicBody->IgnoreParenImpCasts();
3558 if (AtomicBody->getType()->isScalarType() ||
3559 AtomicBody->isInstantiationDependent()) {
3560 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
3561 AtomicBody->IgnoreParenImpCasts())) {
3562 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003563 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00003564 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003565 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003566 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003567 X = AtomicCompAssignOp->getLHS();
3568 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003569 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
3570 AtomicBody->IgnoreParenImpCasts())) {
3571 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003572 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
3573 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003574 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00003575 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
3576 // Check for Unary Operation
3577 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003578 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003579 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
3580 OpLoc = AtomicUnaryOp->getOperatorLoc();
3581 X = AtomicUnaryOp->getSubExpr();
3582 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
3583 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003584 } else {
3585 ErrorFound = NotAnUnaryIncDecExpression;
3586 ErrorLoc = AtomicUnaryOp->getExprLoc();
3587 ErrorRange = AtomicUnaryOp->getSourceRange();
3588 NoteLoc = AtomicUnaryOp->getOperatorLoc();
3589 NoteRange = SourceRange(NoteLoc, NoteLoc);
3590 }
3591 } else {
3592 ErrorFound = NotABinaryOrUnaryExpression;
3593 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
3594 NoteRange = ErrorRange = AtomicBody->getSourceRange();
3595 }
3596 } else {
3597 ErrorFound = NotAScalarType;
3598 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
3599 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3600 }
3601 } else {
3602 ErrorFound = NotAnExpression;
3603 NoteLoc = ErrorLoc = S->getLocStart();
3604 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3605 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003606 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003607 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3608 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3609 return true;
3610 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003611 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003612 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003613 // Build an update expression of form 'OpaqueValueExpr(x) binop
3614 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
3615 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
3616 auto *OVEX = new (SemaRef.getASTContext())
3617 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
3618 auto *OVEExpr = new (SemaRef.getASTContext())
3619 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
3620 auto Update =
3621 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
3622 IsXLHSInRHSPart ? OVEExpr : OVEX);
3623 if (Update.isInvalid())
3624 return true;
3625 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
3626 Sema::AA_Casting);
3627 if (Update.isInvalid())
3628 return true;
3629 UpdateExpr = Update.get();
3630 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003631 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003632}
3633
Alexey Bataev0162e452014-07-22 10:10:35 +00003634StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3635 Stmt *AStmt,
3636 SourceLocation StartLoc,
3637 SourceLocation EndLoc) {
3638 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003639 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00003640 // 1.2.2 OpenMP Language Terminology
3641 // Structured block - An executable statement with a single entry at the
3642 // top and a single exit at the bottom.
3643 // The point of exit cannot be a branch out of the structured block.
3644 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00003645 OpenMPClauseKind AtomicKind = OMPC_unknown;
3646 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003647 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00003648 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00003649 C->getClauseKind() == OMPC_update ||
3650 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00003651 if (AtomicKind != OMPC_unknown) {
3652 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3653 << SourceRange(C->getLocStart(), C->getLocEnd());
3654 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3655 << getOpenMPClauseName(AtomicKind);
3656 } else {
3657 AtomicKind = C->getClauseKind();
3658 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003659 }
3660 }
3661 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003662
Alexey Bataev459dec02014-07-24 06:46:57 +00003663 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00003664 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
3665 Body = EWC->getSubExpr();
3666
Alexey Bataev62cec442014-11-18 10:14:22 +00003667 Expr *X = nullptr;
3668 Expr *V = nullptr;
3669 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003670 Expr *UE = nullptr;
3671 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003672 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00003673 // OpenMP [2.12.6, atomic Construct]
3674 // In the next expressions:
3675 // * x and v (as applicable) are both l-value expressions with scalar type.
3676 // * During the execution of an atomic region, multiple syntactic
3677 // occurrences of x must designate the same storage location.
3678 // * Neither of v and expr (as applicable) may access the storage location
3679 // designated by x.
3680 // * Neither of x and expr (as applicable) may access the storage location
3681 // designated by v.
3682 // * expr is an expression with scalar type.
3683 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3684 // * binop, binop=, ++, and -- are not overloaded operators.
3685 // * The expression x binop expr must be numerically equivalent to x binop
3686 // (expr). This requirement is satisfied if the operators in expr have
3687 // precedence greater than binop, or by using parentheses around expr or
3688 // subexpressions of expr.
3689 // * The expression expr binop x must be numerically equivalent to (expr)
3690 // binop x. This requirement is satisfied if the operators in expr have
3691 // precedence equal to or greater than binop, or by using parentheses around
3692 // expr or subexpressions of expr.
3693 // * For forms that allow multiple occurrences of x, the number of times
3694 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00003695 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003696 enum {
3697 NotAnExpression,
3698 NotAnAssignmentOp,
3699 NotAScalarType,
3700 NotAnLValue,
3701 NoError
3702 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00003703 SourceLocation ErrorLoc, NoteLoc;
3704 SourceRange ErrorRange, NoteRange;
3705 // If clause is read:
3706 // v = x;
3707 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3708 auto AtomicBinOp =
3709 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3710 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3711 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3712 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3713 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3714 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3715 if (!X->isLValue() || !V->isLValue()) {
3716 auto NotLValueExpr = X->isLValue() ? V : X;
3717 ErrorFound = NotAnLValue;
3718 ErrorLoc = AtomicBinOp->getExprLoc();
3719 ErrorRange = AtomicBinOp->getSourceRange();
3720 NoteLoc = NotLValueExpr->getExprLoc();
3721 NoteRange = NotLValueExpr->getSourceRange();
3722 }
3723 } else if (!X->isInstantiationDependent() ||
3724 !V->isInstantiationDependent()) {
3725 auto NotScalarExpr =
3726 (X->isInstantiationDependent() || X->getType()->isScalarType())
3727 ? V
3728 : X;
3729 ErrorFound = NotAScalarType;
3730 ErrorLoc = AtomicBinOp->getExprLoc();
3731 ErrorRange = AtomicBinOp->getSourceRange();
3732 NoteLoc = NotScalarExpr->getExprLoc();
3733 NoteRange = NotScalarExpr->getSourceRange();
3734 }
3735 } else {
3736 ErrorFound = NotAnAssignmentOp;
3737 ErrorLoc = AtomicBody->getExprLoc();
3738 ErrorRange = AtomicBody->getSourceRange();
3739 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3740 : AtomicBody->getExprLoc();
3741 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3742 : AtomicBody->getSourceRange();
3743 }
3744 } else {
3745 ErrorFound = NotAnExpression;
3746 NoteLoc = ErrorLoc = Body->getLocStart();
3747 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003748 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003749 if (ErrorFound != NoError) {
3750 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3751 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003752 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3753 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00003754 return StmtError();
3755 } else if (CurContext->isDependentContext())
3756 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00003757 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003758 enum {
3759 NotAnExpression,
3760 NotAnAssignmentOp,
3761 NotAScalarType,
3762 NotAnLValue,
3763 NoError
3764 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003765 SourceLocation ErrorLoc, NoteLoc;
3766 SourceRange ErrorRange, NoteRange;
3767 // If clause is write:
3768 // x = expr;
3769 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3770 auto AtomicBinOp =
3771 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3772 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00003773 X = AtomicBinOp->getLHS();
3774 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00003775 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3776 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
3777 if (!X->isLValue()) {
3778 ErrorFound = NotAnLValue;
3779 ErrorLoc = AtomicBinOp->getExprLoc();
3780 ErrorRange = AtomicBinOp->getSourceRange();
3781 NoteLoc = X->getExprLoc();
3782 NoteRange = X->getSourceRange();
3783 }
3784 } else if (!X->isInstantiationDependent() ||
3785 !E->isInstantiationDependent()) {
3786 auto NotScalarExpr =
3787 (X->isInstantiationDependent() || X->getType()->isScalarType())
3788 ? E
3789 : X;
3790 ErrorFound = NotAScalarType;
3791 ErrorLoc = AtomicBinOp->getExprLoc();
3792 ErrorRange = AtomicBinOp->getSourceRange();
3793 NoteLoc = NotScalarExpr->getExprLoc();
3794 NoteRange = NotScalarExpr->getSourceRange();
3795 }
3796 } else {
3797 ErrorFound = NotAnAssignmentOp;
3798 ErrorLoc = AtomicBody->getExprLoc();
3799 ErrorRange = AtomicBody->getSourceRange();
3800 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3801 : AtomicBody->getExprLoc();
3802 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3803 : AtomicBody->getSourceRange();
3804 }
3805 } else {
3806 ErrorFound = NotAnExpression;
3807 NoteLoc = ErrorLoc = Body->getLocStart();
3808 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003809 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00003810 if (ErrorFound != NoError) {
3811 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
3812 << ErrorRange;
3813 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3814 << NoteRange;
3815 return StmtError();
3816 } else if (CurContext->isDependentContext())
3817 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00003818 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003819 // If clause is update:
3820 // x++;
3821 // x--;
3822 // ++x;
3823 // --x;
3824 // x binop= expr;
3825 // x = x binop expr;
3826 // x = expr binop x;
3827 OpenMPAtomicUpdateChecker Checker(*this);
3828 if (Checker.checkStatement(
3829 Body, (AtomicKind == OMPC_update)
3830 ? diag::err_omp_atomic_update_not_expression_statement
3831 : diag::err_omp_atomic_not_expression_statement,
3832 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00003833 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003834 if (!CurContext->isDependentContext()) {
3835 E = Checker.getExpr();
3836 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003837 UE = Checker.getUpdateExpr();
3838 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00003839 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003840 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003841 enum {
3842 NotAnAssignmentOp,
3843 NotACompoundStatement,
3844 NotTwoSubstatements,
3845 NotASpecificExpression,
3846 NoError
3847 } ErrorFound = NoError;
3848 SourceLocation ErrorLoc, NoteLoc;
3849 SourceRange ErrorRange, NoteRange;
3850 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
3851 // If clause is a capture:
3852 // v = x++;
3853 // v = x--;
3854 // v = ++x;
3855 // v = --x;
3856 // v = x binop= expr;
3857 // v = x = x binop expr;
3858 // v = x = expr binop x;
3859 auto *AtomicBinOp =
3860 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3861 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3862 V = AtomicBinOp->getLHS();
3863 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3864 OpenMPAtomicUpdateChecker Checker(*this);
3865 if (Checker.checkStatement(
3866 Body, diag::err_omp_atomic_capture_not_expression_statement,
3867 diag::note_omp_atomic_update))
3868 return StmtError();
3869 E = Checker.getExpr();
3870 X = Checker.getX();
3871 UE = Checker.getUpdateExpr();
3872 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3873 IsPostfixUpdate = Checker.isPostfixUpdate();
3874 } else {
3875 ErrorLoc = AtomicBody->getExprLoc();
3876 ErrorRange = AtomicBody->getSourceRange();
3877 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3878 : AtomicBody->getExprLoc();
3879 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3880 : AtomicBody->getSourceRange();
3881 ErrorFound = NotAnAssignmentOp;
3882 }
3883 if (ErrorFound != NoError) {
3884 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
3885 << ErrorRange;
3886 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3887 return StmtError();
3888 } else if (CurContext->isDependentContext()) {
3889 UE = V = E = X = nullptr;
3890 }
3891 } else {
3892 // If clause is a capture:
3893 // { v = x; x = expr; }
3894 // { v = x; x++; }
3895 // { v = x; x--; }
3896 // { v = x; ++x; }
3897 // { v = x; --x; }
3898 // { v = x; x binop= expr; }
3899 // { v = x; x = x binop expr; }
3900 // { v = x; x = expr binop x; }
3901 // { x++; v = x; }
3902 // { x--; v = x; }
3903 // { ++x; v = x; }
3904 // { --x; v = x; }
3905 // { x binop= expr; v = x; }
3906 // { x = x binop expr; v = x; }
3907 // { x = expr binop x; v = x; }
3908 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
3909 // Check that this is { expr1; expr2; }
3910 if (CS->size() == 2) {
3911 auto *First = CS->body_front();
3912 auto *Second = CS->body_back();
3913 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
3914 First = EWC->getSubExpr()->IgnoreParenImpCasts();
3915 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
3916 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
3917 // Need to find what subexpression is 'v' and what is 'x'.
3918 OpenMPAtomicUpdateChecker Checker(*this);
3919 bool IsUpdateExprFound = !Checker.checkStatement(Second);
3920 BinaryOperator *BinOp = nullptr;
3921 if (IsUpdateExprFound) {
3922 BinOp = dyn_cast<BinaryOperator>(First);
3923 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3924 }
3925 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3926 // { v = x; x++; }
3927 // { v = x; x--; }
3928 // { v = x; ++x; }
3929 // { v = x; --x; }
3930 // { v = x; x binop= expr; }
3931 // { v = x; x = x binop expr; }
3932 // { v = x; x = expr binop x; }
3933 // Check that the first expression has form v = x.
3934 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3935 llvm::FoldingSetNodeID XId, PossibleXId;
3936 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3937 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3938 IsUpdateExprFound = XId == PossibleXId;
3939 if (IsUpdateExprFound) {
3940 V = BinOp->getLHS();
3941 X = Checker.getX();
3942 E = Checker.getExpr();
3943 UE = Checker.getUpdateExpr();
3944 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003945 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003946 }
3947 }
3948 if (!IsUpdateExprFound) {
3949 IsUpdateExprFound = !Checker.checkStatement(First);
3950 BinOp = nullptr;
3951 if (IsUpdateExprFound) {
3952 BinOp = dyn_cast<BinaryOperator>(Second);
3953 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3954 }
3955 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3956 // { x++; v = x; }
3957 // { x--; v = x; }
3958 // { ++x; v = x; }
3959 // { --x; v = x; }
3960 // { x binop= expr; v = x; }
3961 // { x = x binop expr; v = x; }
3962 // { x = expr binop x; v = x; }
3963 // Check that the second expression has form v = x.
3964 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3965 llvm::FoldingSetNodeID XId, PossibleXId;
3966 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3967 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3968 IsUpdateExprFound = XId == PossibleXId;
3969 if (IsUpdateExprFound) {
3970 V = BinOp->getLHS();
3971 X = Checker.getX();
3972 E = Checker.getExpr();
3973 UE = Checker.getUpdateExpr();
3974 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003975 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003976 }
3977 }
3978 }
3979 if (!IsUpdateExprFound) {
3980 // { v = x; x = expr; }
3981 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
3982 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
3983 ErrorFound = NotAnAssignmentOp;
3984 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
3985 : First->getLocStart();
3986 NoteRange = ErrorRange = FirstBinOp
3987 ? FirstBinOp->getSourceRange()
3988 : SourceRange(ErrorLoc, ErrorLoc);
3989 } else {
3990 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
3991 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
3992 ErrorFound = NotAnAssignmentOp;
3993 NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
3994 : Second->getLocStart();
3995 NoteRange = ErrorRange = SecondBinOp
3996 ? SecondBinOp->getSourceRange()
3997 : SourceRange(ErrorLoc, ErrorLoc);
3998 } else {
3999 auto *PossibleXRHSInFirst =
4000 FirstBinOp->getRHS()->IgnoreParenImpCasts();
4001 auto *PossibleXLHSInSecond =
4002 SecondBinOp->getLHS()->IgnoreParenImpCasts();
4003 llvm::FoldingSetNodeID X1Id, X2Id;
4004 PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
4005 PossibleXLHSInSecond->Profile(X2Id, Context,
4006 /*Canonical=*/true);
4007 IsUpdateExprFound = X1Id == X2Id;
4008 if (IsUpdateExprFound) {
4009 V = FirstBinOp->getLHS();
4010 X = SecondBinOp->getLHS();
4011 E = SecondBinOp->getRHS();
4012 UE = nullptr;
4013 IsXLHSInRHSPart = false;
4014 IsPostfixUpdate = true;
4015 } else {
4016 ErrorFound = NotASpecificExpression;
4017 ErrorLoc = FirstBinOp->getExprLoc();
4018 ErrorRange = FirstBinOp->getSourceRange();
4019 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
4020 NoteRange = SecondBinOp->getRHS()->getSourceRange();
4021 }
4022 }
4023 }
4024 }
4025 } else {
4026 NoteLoc = ErrorLoc = Body->getLocStart();
4027 NoteRange = ErrorRange =
4028 SourceRange(Body->getLocStart(), Body->getLocStart());
4029 ErrorFound = NotTwoSubstatements;
4030 }
4031 } else {
4032 NoteLoc = ErrorLoc = Body->getLocStart();
4033 NoteRange = ErrorRange =
4034 SourceRange(Body->getLocStart(), Body->getLocStart());
4035 ErrorFound = NotACompoundStatement;
4036 }
4037 if (ErrorFound != NoError) {
4038 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
4039 << ErrorRange;
4040 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4041 return StmtError();
4042 } else if (CurContext->isDependentContext()) {
4043 UE = V = E = X = nullptr;
4044 }
Alexey Bataev459dec02014-07-24 06:46:57 +00004045 }
Alexey Bataevdea47612014-07-23 07:46:59 +00004046 }
Alexey Bataev0162e452014-07-22 10:10:35 +00004047
4048 getCurFunction()->setHasBranchProtectedScope();
4049
Alexey Bataev62cec442014-11-18 10:14:22 +00004050 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00004051 X, V, E, UE, IsXLHSInRHSPart,
4052 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00004053}
4054
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004055StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
4056 Stmt *AStmt,
4057 SourceLocation StartLoc,
4058 SourceLocation EndLoc) {
4059 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4060
Alexey Bataev13314bf2014-10-09 04:18:56 +00004061 // OpenMP [2.16, Nesting of Regions]
4062 // If specified, a teams construct must be contained within a target
4063 // construct. That target construct must contain no statements or directives
4064 // outside of the teams construct.
4065 if (DSAStack->hasInnerTeamsRegion()) {
4066 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
4067 bool OMPTeamsFound = true;
4068 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
4069 auto I = CS->body_begin();
4070 while (I != CS->body_end()) {
4071 auto OED = dyn_cast<OMPExecutableDirective>(*I);
4072 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
4073 OMPTeamsFound = false;
4074 break;
4075 }
4076 ++I;
4077 }
4078 assert(I != CS->body_end() && "Not found statement");
4079 S = *I;
4080 }
4081 if (!OMPTeamsFound) {
4082 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
4083 Diag(DSAStack->getInnerTeamsRegionLoc(),
4084 diag::note_omp_nested_teams_construct_here);
4085 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
4086 << isa<OMPExecutableDirective>(S);
4087 return StmtError();
4088 }
4089 }
4090
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004091 getCurFunction()->setHasBranchProtectedScope();
4092
4093 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4094}
4095
Alexey Bataev13314bf2014-10-09 04:18:56 +00004096StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
4097 Stmt *AStmt, SourceLocation StartLoc,
4098 SourceLocation EndLoc) {
4099 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4100 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4101 // 1.2.2 OpenMP Language Terminology
4102 // Structured block - An executable statement with a single entry at the
4103 // top and a single exit at the bottom.
4104 // The point of exit cannot be a branch out of the structured block.
4105 // longjmp() and throw() must not violate the entry/exit criteria.
4106 CS->getCapturedDecl()->setNothrow();
4107
4108 getCurFunction()->setHasBranchProtectedScope();
4109
4110 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4111}
4112
Alexey Bataeved09d242014-05-28 05:53:51 +00004113OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004114 SourceLocation StartLoc,
4115 SourceLocation LParenLoc,
4116 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004117 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004118 switch (Kind) {
4119 case OMPC_if:
4120 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
4121 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00004122 case OMPC_final:
4123 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
4124 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00004125 case OMPC_num_threads:
4126 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
4127 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004128 case OMPC_safelen:
4129 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
4130 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00004131 case OMPC_collapse:
4132 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
4133 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004134 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004135 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004136 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004137 case OMPC_private:
4138 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004139 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004140 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004141 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004142 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004143 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004144 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004145 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004146 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004147 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004148 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004149 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004150 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004151 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004152 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004153 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004154 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004155 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004156 case OMPC_seq_cst:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004157 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004158 llvm_unreachable("Clause is not allowed.");
4159 }
4160 return Res;
4161}
4162
Alexey Bataeved09d242014-05-28 05:53:51 +00004163OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004164 SourceLocation LParenLoc,
4165 SourceLocation EndLoc) {
4166 Expr *ValExpr = Condition;
4167 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4168 !Condition->isInstantiationDependent() &&
4169 !Condition->containsUnexpandedParameterPack()) {
4170 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00004171 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004172 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004173 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004174
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004175 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004176 }
4177
4178 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4179}
4180
Alexey Bataev3778b602014-07-17 07:32:53 +00004181OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
4182 SourceLocation StartLoc,
4183 SourceLocation LParenLoc,
4184 SourceLocation EndLoc) {
4185 Expr *ValExpr = Condition;
4186 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4187 !Condition->isInstantiationDependent() &&
4188 !Condition->containsUnexpandedParameterPack()) {
4189 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4190 Condition->getExprLoc(), Condition);
4191 if (Val.isInvalid())
4192 return nullptr;
4193
4194 ValExpr = Val.get();
4195 }
4196
4197 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4198}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004199ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
4200 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004201 if (!Op)
4202 return ExprError();
4203
4204 class IntConvertDiagnoser : public ICEConvertDiagnoser {
4205 public:
4206 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00004207 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00004208 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
4209 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004210 return S.Diag(Loc, diag::err_omp_not_integral) << T;
4211 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004212 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4213 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004214 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
4215 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004216 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4217 QualType T,
4218 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004219 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
4220 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004221 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4222 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004223 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004224 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004225 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004226 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4227 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004228 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
4229 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004230 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4231 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004232 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004233 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004234 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004235 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
4236 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004237 llvm_unreachable("conversion functions are permitted");
4238 }
4239 } ConvertDiagnoser;
4240 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
4241}
4242
4243OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
4244 SourceLocation StartLoc,
4245 SourceLocation LParenLoc,
4246 SourceLocation EndLoc) {
4247 Expr *ValExpr = NumThreads;
4248 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
Alexey Bataev568a8332014-03-06 06:15:19 +00004249 !NumThreads->containsUnexpandedParameterPack()) {
4250 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
4251 ExprResult Val =
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004252 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
Alexey Bataev568a8332014-03-06 06:15:19 +00004253 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004254 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004255
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004256 ValExpr = Val.get();
Alexey Bataev568a8332014-03-06 06:15:19 +00004257
4258 // OpenMP [2.5, Restrictions]
4259 // The num_threads expression must evaluate to a positive integer value.
4260 llvm::APSInt Result;
Alexey Bataeved09d242014-05-28 05:53:51 +00004261 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
4262 !Result.isStrictlyPositive()) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004263 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
4264 << "num_threads" << NumThreads->getSourceRange();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004265 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004266 }
4267 }
4268
Alexey Bataeved09d242014-05-28 05:53:51 +00004269 return new (Context)
4270 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00004271}
4272
Alexey Bataev62c87d22014-03-21 04:51:18 +00004273ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
4274 OpenMPClauseKind CKind) {
4275 if (!E)
4276 return ExprError();
4277 if (E->isValueDependent() || E->isTypeDependent() ||
4278 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004279 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004280 llvm::APSInt Result;
4281 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
4282 if (ICE.isInvalid())
4283 return ExprError();
4284 if (!Result.isStrictlyPositive()) {
4285 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
4286 << getOpenMPClauseName(CKind) << E->getSourceRange();
4287 return ExprError();
4288 }
Alexander Musman09184fe2014-09-30 05:29:28 +00004289 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
4290 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
4291 << E->getSourceRange();
4292 return ExprError();
4293 }
Alexey Bataev9c821032015-04-30 04:23:23 +00004294 if (CKind == OMPC_collapse) {
4295 DSAStack->setCollapseNumber(Result.getExtValue());
4296 }
Alexey Bataev62c87d22014-03-21 04:51:18 +00004297 return ICE;
4298}
4299
4300OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
4301 SourceLocation LParenLoc,
4302 SourceLocation EndLoc) {
4303 // OpenMP [2.8.1, simd construct, Description]
4304 // The parameter of the safelen clause must be a constant
4305 // positive integer expression.
4306 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
4307 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004308 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004309 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004310 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00004311}
4312
Alexander Musman64d33f12014-06-04 07:53:32 +00004313OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
4314 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00004315 SourceLocation LParenLoc,
4316 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00004317 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004318 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00004319 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004320 // The parameter of the collapse clause must be a constant
4321 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00004322 ExprResult NumForLoopsResult =
4323 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
4324 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00004325 return nullptr;
4326 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00004327 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00004328}
4329
Alexey Bataeved09d242014-05-28 05:53:51 +00004330OMPClause *Sema::ActOnOpenMPSimpleClause(
4331 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
4332 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004333 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004334 switch (Kind) {
4335 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004336 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00004337 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
4338 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004339 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004340 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00004341 Res = ActOnOpenMPProcBindClause(
4342 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
4343 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004344 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004345 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004346 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004347 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004348 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004349 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004350 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004351 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004352 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004353 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004354 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004355 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004356 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004357 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004358 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004359 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004360 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004361 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004362 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004363 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004364 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004365 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004366 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004367 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004368 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004369 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004370 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004371 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004372 llvm_unreachable("Clause is not allowed.");
4373 }
4374 return Res;
4375}
4376
4377OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
4378 SourceLocation KindKwLoc,
4379 SourceLocation StartLoc,
4380 SourceLocation LParenLoc,
4381 SourceLocation EndLoc) {
4382 if (Kind == OMPC_DEFAULT_unknown) {
4383 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004384 static_assert(OMPC_DEFAULT_unknown > 0,
4385 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00004386 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004387 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004388 Values += "'";
4389 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
4390 Values += "'";
4391 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004392 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004393 Values += " or ";
4394 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004395 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004396 break;
4397 default:
4398 Values += Sep;
4399 break;
4400 }
4401 }
4402 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004403 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004404 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004405 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004406 switch (Kind) {
4407 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004408 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004409 break;
4410 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004411 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004412 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004413 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004414 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00004415 break;
4416 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004417 return new (Context)
4418 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004419}
4420
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004421OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
4422 SourceLocation KindKwLoc,
4423 SourceLocation StartLoc,
4424 SourceLocation LParenLoc,
4425 SourceLocation EndLoc) {
4426 if (Kind == OMPC_PROC_BIND_unknown) {
4427 std::string Values;
4428 std::string Sep(", ");
4429 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
4430 Values += "'";
4431 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
4432 Values += "'";
4433 switch (i) {
4434 case OMPC_PROC_BIND_unknown - 2:
4435 Values += " or ";
4436 break;
4437 case OMPC_PROC_BIND_unknown - 1:
4438 break;
4439 default:
4440 Values += Sep;
4441 break;
4442 }
4443 }
4444 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004445 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004446 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004447 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004448 return new (Context)
4449 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004450}
4451
Alexey Bataev56dafe82014-06-20 07:16:17 +00004452OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
4453 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
4454 SourceLocation StartLoc, SourceLocation LParenLoc,
4455 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
4456 SourceLocation EndLoc) {
4457 OMPClause *Res = nullptr;
4458 switch (Kind) {
4459 case OMPC_schedule:
4460 Res = ActOnOpenMPScheduleClause(
4461 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
4462 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
4463 break;
4464 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004465 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004466 case OMPC_num_threads:
4467 case OMPC_safelen:
4468 case OMPC_collapse:
4469 case OMPC_default:
4470 case OMPC_proc_bind:
4471 case OMPC_private:
4472 case OMPC_firstprivate:
4473 case OMPC_lastprivate:
4474 case OMPC_shared:
4475 case OMPC_reduction:
4476 case OMPC_linear:
4477 case OMPC_aligned:
4478 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004479 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004480 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004481 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004482 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004483 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004484 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004485 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004486 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004487 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004488 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004489 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004490 case OMPC_seq_cst:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004491 case OMPC_unknown:
4492 llvm_unreachable("Clause is not allowed.");
4493 }
4494 return Res;
4495}
4496
4497OMPClause *Sema::ActOnOpenMPScheduleClause(
4498 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
4499 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
4500 SourceLocation EndLoc) {
4501 if (Kind == OMPC_SCHEDULE_unknown) {
4502 std::string Values;
4503 std::string Sep(", ");
4504 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
4505 Values += "'";
4506 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
4507 Values += "'";
4508 switch (i) {
4509 case OMPC_SCHEDULE_unknown - 2:
4510 Values += " or ";
4511 break;
4512 case OMPC_SCHEDULE_unknown - 1:
4513 break;
4514 default:
4515 Values += Sep;
4516 break;
4517 }
4518 }
4519 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
4520 << Values << getOpenMPClauseName(OMPC_schedule);
4521 return nullptr;
4522 }
4523 Expr *ValExpr = ChunkSize;
Alexey Bataev040d5402015-05-12 08:35:28 +00004524 Expr *HelperValExpr = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00004525 if (ChunkSize) {
4526 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
4527 !ChunkSize->isInstantiationDependent() &&
4528 !ChunkSize->containsUnexpandedParameterPack()) {
4529 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
4530 ExprResult Val =
4531 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
4532 if (Val.isInvalid())
4533 return nullptr;
4534
4535 ValExpr = Val.get();
4536
4537 // OpenMP [2.7.1, Restrictions]
4538 // chunk_size must be a loop invariant integer expression with a positive
4539 // value.
4540 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00004541 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
4542 if (Result.isSigned() && !Result.isStrictlyPositive()) {
4543 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
4544 << "schedule" << ChunkSize->getSourceRange();
4545 return nullptr;
4546 }
4547 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
4548 auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
4549 ChunkSize->getType(), ".chunk.");
4550 auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
4551 ChunkSize->getExprLoc(),
4552 /*RefersToCapture=*/true);
4553 HelperValExpr = ImpVarRef;
Alexey Bataev56dafe82014-06-20 07:16:17 +00004554 }
4555 }
4556 }
4557
4558 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
Alexey Bataev040d5402015-05-12 08:35:28 +00004559 EndLoc, Kind, ValExpr, HelperValExpr);
Alexey Bataev56dafe82014-06-20 07:16:17 +00004560}
4561
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004562OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
4563 SourceLocation StartLoc,
4564 SourceLocation EndLoc) {
4565 OMPClause *Res = nullptr;
4566 switch (Kind) {
4567 case OMPC_ordered:
4568 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
4569 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00004570 case OMPC_nowait:
4571 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
4572 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004573 case OMPC_untied:
4574 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
4575 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004576 case OMPC_mergeable:
4577 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
4578 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004579 case OMPC_read:
4580 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
4581 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00004582 case OMPC_write:
4583 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
4584 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004585 case OMPC_update:
4586 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
4587 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00004588 case OMPC_capture:
4589 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
4590 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004591 case OMPC_seq_cst:
4592 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
4593 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004594 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004595 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004596 case OMPC_num_threads:
4597 case OMPC_safelen:
4598 case OMPC_collapse:
4599 case OMPC_schedule:
4600 case OMPC_private:
4601 case OMPC_firstprivate:
4602 case OMPC_lastprivate:
4603 case OMPC_shared:
4604 case OMPC_reduction:
4605 case OMPC_linear:
4606 case OMPC_aligned:
4607 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004608 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004609 case OMPC_default:
4610 case OMPC_proc_bind:
4611 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004612 case OMPC_flush:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004613 case OMPC_unknown:
4614 llvm_unreachable("Clause is not allowed.");
4615 }
4616 return Res;
4617}
4618
4619OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
4620 SourceLocation EndLoc) {
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004621 DSAStack->setOrderedRegion();
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004622 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
4623}
4624
Alexey Bataev236070f2014-06-20 11:19:47 +00004625OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
4626 SourceLocation EndLoc) {
4627 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
4628}
4629
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004630OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
4631 SourceLocation EndLoc) {
4632 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
4633}
4634
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004635OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
4636 SourceLocation EndLoc) {
4637 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
4638}
4639
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004640OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
4641 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004642 return new (Context) OMPReadClause(StartLoc, EndLoc);
4643}
4644
Alexey Bataevdea47612014-07-23 07:46:59 +00004645OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
4646 SourceLocation EndLoc) {
4647 return new (Context) OMPWriteClause(StartLoc, EndLoc);
4648}
4649
Alexey Bataev67a4f222014-07-23 10:25:33 +00004650OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
4651 SourceLocation EndLoc) {
4652 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
4653}
4654
Alexey Bataev459dec02014-07-24 06:46:57 +00004655OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
4656 SourceLocation EndLoc) {
4657 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
4658}
4659
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004660OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
4661 SourceLocation EndLoc) {
4662 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
4663}
4664
Alexey Bataevc5e02582014-06-16 07:08:35 +00004665OMPClause *Sema::ActOnOpenMPVarListClause(
4666 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
4667 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
4668 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
4669 const DeclarationNameInfo &ReductionId) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004670 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004671 switch (Kind) {
4672 case OMPC_private:
4673 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4674 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004675 case OMPC_firstprivate:
4676 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4677 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00004678 case OMPC_lastprivate:
4679 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4680 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00004681 case OMPC_shared:
4682 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
4683 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00004684 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00004685 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
4686 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00004687 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00004688 case OMPC_linear:
4689 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
4690 ColonLoc, EndLoc);
4691 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004692 case OMPC_aligned:
4693 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
4694 ColonLoc, EndLoc);
4695 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004696 case OMPC_copyin:
4697 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
4698 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00004699 case OMPC_copyprivate:
4700 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4701 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004702 case OMPC_flush:
4703 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4704 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004705 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004706 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004707 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004708 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004709 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004710 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004711 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004712 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004713 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004714 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004715 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004716 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004717 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004718 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004719 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004720 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004721 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004722 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004723 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004724 llvm_unreachable("Clause is not allowed.");
4725 }
4726 return Res;
4727}
4728
4729OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
4730 SourceLocation StartLoc,
4731 SourceLocation LParenLoc,
4732 SourceLocation EndLoc) {
4733 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00004734 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00004735 for (auto &RefExpr : VarList) {
4736 assert(RefExpr && "NULL expr in OpenMP private clause.");
4737 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004738 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004739 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004740 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004741 continue;
4742 }
4743
Alexey Bataeved09d242014-05-28 05:53:51 +00004744 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004745 // OpenMP [2.1, C/C++]
4746 // A list item is a variable name.
4747 // OpenMP [2.9.3.3, Restrictions, p.1]
4748 // A variable that is part of another variable (as an array or
4749 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004750 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004751 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004752 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004753 continue;
4754 }
4755 Decl *D = DE->getDecl();
4756 VarDecl *VD = cast<VarDecl>(D);
4757
4758 QualType Type = VD->getType();
4759 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4760 // It will be analyzed later.
4761 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004762 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004763 continue;
4764 }
4765
4766 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4767 // A variable that appears in a private clause must not have an incomplete
4768 // type or a reference type.
4769 if (RequireCompleteType(ELoc, Type,
4770 diag::err_omp_private_incomplete_type)) {
4771 continue;
4772 }
4773 if (Type->isReferenceType()) {
4774 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00004775 << getOpenMPClauseName(OMPC_private) << Type;
4776 bool IsDecl =
4777 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4778 Diag(VD->getLocation(),
4779 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4780 << VD;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004781 continue;
4782 }
4783
4784 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
4785 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004786 // clause requires an accessible, unambiguous default constructor for the
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004787 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00004788 while (Type->isArrayType()) {
4789 Type = cast<ArrayType>(Type.getTypePtr())->getElementType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004790 }
4791
Alexey Bataev758e55e2013-09-06 18:03:48 +00004792 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4793 // in a Construct]
4794 // Variables with the predetermined data-sharing attributes may not be
4795 // listed in data-sharing attributes clauses, except for the cases
4796 // listed below. For these exceptions only, listing a predetermined
4797 // variable in a data-sharing attribute clause is allowed and overrides
4798 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004799 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004800 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004801 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4802 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004803 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004804 continue;
4805 }
4806
Alexey Bataev03b340a2014-10-21 03:16:40 +00004807 // Generate helper private variable and initialize it with the default
4808 // value. The address of the original variable is replaced by the address of
4809 // the new private variable in CodeGen. This new variable is not added to
4810 // IdResolver, so the code in the OpenMP region uses original variable for
4811 // proper diagnostics.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004812 auto VDPrivate =
4813 buildVarDecl(*this, DE->getExprLoc(),
4814 VD->getType().getUnqualifiedType(), VD->getName());
4815 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004816 if (VDPrivate->isInvalidDecl())
4817 continue;
Alexey Bataev07649fb2014-12-16 08:01:48 +00004818 auto VDPrivateRefExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00004819 buildDeclRefExpr(*this, VDPrivate, DE->getType(), DE->getExprLoc());
Alexey Bataev03b340a2014-10-21 03:16:40 +00004820
Alexey Bataev758e55e2013-09-06 18:03:48 +00004821 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004822 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004823 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004824 }
4825
Alexey Bataeved09d242014-05-28 05:53:51 +00004826 if (Vars.empty())
4827 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004828
Alexey Bataev03b340a2014-10-21 03:16:40 +00004829 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
4830 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004831}
4832
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004833namespace {
4834class DiagsUninitializedSeveretyRAII {
4835private:
4836 DiagnosticsEngine &Diags;
4837 SourceLocation SavedLoc;
4838 bool IsIgnored;
4839
4840public:
4841 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
4842 bool IsIgnored)
4843 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
4844 if (!IsIgnored) {
4845 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
4846 /*Map*/ diag::Severity::Ignored, Loc);
4847 }
4848 }
4849 ~DiagsUninitializedSeveretyRAII() {
4850 if (!IsIgnored)
4851 Diags.popMappings(SavedLoc);
4852 }
4853};
4854}
4855
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004856OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
4857 SourceLocation StartLoc,
4858 SourceLocation LParenLoc,
4859 SourceLocation EndLoc) {
4860 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004861 SmallVector<Expr *, 8> PrivateCopies;
4862 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004863 bool IsImplicitClause =
4864 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
4865 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
4866
Alexey Bataeved09d242014-05-28 05:53:51 +00004867 for (auto &RefExpr : VarList) {
4868 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
4869 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004870 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004871 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004872 PrivateCopies.push_back(nullptr);
4873 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004874 continue;
4875 }
4876
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004877 SourceLocation ELoc =
4878 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004879 // OpenMP [2.1, C/C++]
4880 // A list item is a variable name.
4881 // OpenMP [2.9.3.3, Restrictions, p.1]
4882 // A variable that is part of another variable (as an array or
4883 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004884 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004885 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004886 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004887 continue;
4888 }
4889 Decl *D = DE->getDecl();
4890 VarDecl *VD = cast<VarDecl>(D);
4891
4892 QualType Type = VD->getType();
4893 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4894 // It will be analyzed later.
4895 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004896 PrivateCopies.push_back(nullptr);
4897 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004898 continue;
4899 }
4900
4901 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4902 // A variable that appears in a private clause must not have an incomplete
4903 // type or a reference type.
4904 if (RequireCompleteType(ELoc, Type,
4905 diag::err_omp_firstprivate_incomplete_type)) {
4906 continue;
4907 }
4908 if (Type->isReferenceType()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004909 if (IsImplicitClause) {
4910 Diag(ImplicitClauseLoc,
4911 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
4912 << Type;
4913 Diag(RefExpr->getExprLoc(), diag::note_used_here);
4914 } else {
4915 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4916 << getOpenMPClauseName(OMPC_firstprivate) << Type;
4917 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004918 bool IsDecl =
4919 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4920 Diag(VD->getLocation(),
4921 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4922 << VD;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004923 continue;
4924 }
4925
4926 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
4927 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004928 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004929 // class type.
Alexey Bataev69c62a92015-04-15 04:52:20 +00004930 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004931
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004932 // If an implicit firstprivate variable found it was checked already.
4933 if (!IsImplicitClause) {
4934 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004935 Type = Type.getNonReferenceType().getCanonicalType();
4936 bool IsConstant = Type.isConstant(Context);
4937 Type = Context.getBaseElementType(Type);
4938 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
4939 // A list item that specifies a given variable may not appear in more
4940 // than one clause on the same directive, except that a variable may be
4941 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004942 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00004943 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004944 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004945 << getOpenMPClauseName(DVar.CKind)
4946 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004947 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004948 continue;
4949 }
4950
4951 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4952 // in a Construct]
4953 // Variables with the predetermined data-sharing attributes may not be
4954 // listed in data-sharing attributes clauses, except for the cases
4955 // listed below. For these exceptions only, listing a predetermined
4956 // variable in a data-sharing attribute clause is allowed and overrides
4957 // the variable's predetermined data-sharing attributes.
4958 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4959 // in a Construct, C/C++, p.2]
4960 // Variables with const-qualified type having no mutable member may be
4961 // listed in a firstprivate clause, even if they are static data members.
4962 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
4963 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
4964 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004965 << getOpenMPClauseName(DVar.CKind)
4966 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004967 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004968 continue;
4969 }
4970
Alexey Bataevf29276e2014-06-18 04:14:57 +00004971 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004972 // OpenMP [2.9.3.4, Restrictions, p.2]
4973 // A list item that is private within a parallel region must not appear
4974 // in a firstprivate clause on a worksharing construct if any of the
4975 // worksharing regions arising from the worksharing construct ever bind
4976 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00004977 if (isOpenMPWorksharingDirective(CurrDir) &&
4978 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004979 DVar = DSAStack->getImplicitDSA(VD, true);
4980 if (DVar.CKind != OMPC_shared &&
4981 (isOpenMPParallelDirective(DVar.DKind) ||
4982 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00004983 Diag(ELoc, diag::err_omp_required_access)
4984 << getOpenMPClauseName(OMPC_firstprivate)
4985 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004986 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004987 continue;
4988 }
4989 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004990 // OpenMP [2.9.3.4, Restrictions, p.3]
4991 // A list item that appears in a reduction clause of a parallel construct
4992 // must not appear in a firstprivate clause on a worksharing or task
4993 // construct if any of the worksharing or task regions arising from the
4994 // worksharing or task construct ever bind to any of the parallel regions
4995 // arising from the parallel construct.
4996 // OpenMP [2.9.3.4, Restrictions, p.4]
4997 // A list item that appears in a reduction clause in worksharing
4998 // construct must not appear in a firstprivate clause in a task construct
4999 // encountered during execution of any of the worksharing regions arising
5000 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005001 if (CurrDir == OMPD_task) {
5002 DVar =
5003 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
5004 [](OpenMPDirectiveKind K) -> bool {
5005 return isOpenMPParallelDirective(K) ||
5006 isOpenMPWorksharingDirective(K);
5007 },
5008 false);
5009 if (DVar.CKind == OMPC_reduction &&
5010 (isOpenMPParallelDirective(DVar.DKind) ||
5011 isOpenMPWorksharingDirective(DVar.DKind))) {
5012 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
5013 << getOpenMPDirectiveName(DVar.DKind);
5014 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5015 continue;
5016 }
5017 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005018 }
5019
Alexey Bataev39f915b82015-05-08 10:41:21 +00005020 auto VDPrivate = buildVarDecl(
5021 *this, ELoc, VD->getType().getUnqualifiedType(), VD->getName());
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005022 // Generate helper private variable and initialize it with the value of the
5023 // original variable. The address of the original variable is replaced by
5024 // the address of the new private variable in the CodeGen. This new variable
5025 // is not added to IdResolver, so the code in the OpenMP region uses
5026 // original variable for proper diagnostics and variable capturing.
5027 Expr *VDInitRefExpr = nullptr;
5028 // For arrays generate initializer for single element and replace it by the
5029 // original array element in CodeGen.
5030 if (DE->getType()->isArrayType()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +00005031 auto VDInit = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName());
5032 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, Type, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005033 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataev69c62a92015-04-15 04:52:20 +00005034 auto *VDInitTemp =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005035 buildVarDecl(*this, DE->getLocStart(), Type.getUnqualifiedType(),
Alexey Bataev69c62a92015-04-15 04:52:20 +00005036 ".firstprivate.temp");
5037 InitializedEntity Entity =
5038 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005039 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
5040
5041 InitializationSequence InitSeq(*this, Entity, Kind, Init);
5042 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
5043 if (Result.isInvalid())
5044 VDPrivate->setInvalidDecl();
5045 else
5046 VDPrivate->setInit(Result.getAs<Expr>());
5047 } else {
Alexey Bataev69c62a92015-04-15 04:52:20 +00005048 auto *VDInit =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005049 buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
5050 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, Type, DE->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00005051 AddInitializerToDecl(VDPrivate,
5052 DefaultLvalueConversion(VDInitRefExpr).get(),
5053 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005054 }
5055 if (VDPrivate->isInvalidDecl()) {
5056 if (IsImplicitClause) {
5057 Diag(DE->getExprLoc(),
5058 diag::note_omp_task_predetermined_firstprivate_here);
5059 }
5060 continue;
5061 }
5062 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005063 auto VDPrivateRefExpr = buildDeclRefExpr(
5064 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005065 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
5066 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005067 PrivateCopies.push_back(VDPrivateRefExpr);
5068 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005069 }
5070
Alexey Bataeved09d242014-05-28 05:53:51 +00005071 if (Vars.empty())
5072 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005073
5074 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005075 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005076}
5077
Alexander Musman1bb328c2014-06-04 13:06:39 +00005078OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
5079 SourceLocation StartLoc,
5080 SourceLocation LParenLoc,
5081 SourceLocation EndLoc) {
5082 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00005083 SmallVector<Expr *, 8> SrcExprs;
5084 SmallVector<Expr *, 8> DstExprs;
5085 SmallVector<Expr *, 8> AssignmentOps;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005086 for (auto &RefExpr : VarList) {
5087 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
5088 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5089 // It will be analyzed later.
5090 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00005091 SrcExprs.push_back(nullptr);
5092 DstExprs.push_back(nullptr);
5093 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005094 continue;
5095 }
5096
5097 SourceLocation ELoc = RefExpr->getExprLoc();
5098 // OpenMP [2.1, C/C++]
5099 // A list item is a variable name.
5100 // OpenMP [2.14.3.5, Restrictions, p.1]
5101 // A variable that is part of another variable (as an array or structure
5102 // element) cannot appear in a lastprivate clause.
5103 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5104 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5105 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5106 continue;
5107 }
5108 Decl *D = DE->getDecl();
5109 VarDecl *VD = cast<VarDecl>(D);
5110
5111 QualType Type = VD->getType();
5112 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5113 // It will be analyzed later.
5114 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005115 SrcExprs.push_back(nullptr);
5116 DstExprs.push_back(nullptr);
5117 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005118 continue;
5119 }
5120
5121 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
5122 // A variable that appears in a lastprivate clause must not have an
5123 // incomplete type or a reference type.
5124 if (RequireCompleteType(ELoc, Type,
5125 diag::err_omp_lastprivate_incomplete_type)) {
5126 continue;
5127 }
5128 if (Type->isReferenceType()) {
5129 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5130 << getOpenMPClauseName(OMPC_lastprivate) << Type;
5131 bool IsDecl =
5132 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5133 Diag(VD->getLocation(),
5134 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5135 << VD;
5136 continue;
5137 }
5138
5139 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5140 // in a Construct]
5141 // Variables with the predetermined data-sharing attributes may not be
5142 // listed in data-sharing attributes clauses, except for the cases
5143 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005144 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005145 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
5146 DVar.CKind != OMPC_firstprivate &&
5147 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5148 Diag(ELoc, diag::err_omp_wrong_dsa)
5149 << getOpenMPClauseName(DVar.CKind)
5150 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005151 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005152 continue;
5153 }
5154
Alexey Bataevf29276e2014-06-18 04:14:57 +00005155 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5156 // OpenMP [2.14.3.5, Restrictions, p.2]
5157 // A list item that is private within a parallel region, or that appears in
5158 // the reduction clause of a parallel construct, must not appear in a
5159 // lastprivate clause on a worksharing construct if any of the corresponding
5160 // worksharing regions ever binds to any of the corresponding parallel
5161 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005162 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00005163 if (isOpenMPWorksharingDirective(CurrDir) &&
5164 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005165 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005166 if (DVar.CKind != OMPC_shared) {
5167 Diag(ELoc, diag::err_omp_required_access)
5168 << getOpenMPClauseName(OMPC_lastprivate)
5169 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005170 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005171 continue;
5172 }
5173 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00005174 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00005175 // A variable of class type (or array thereof) that appears in a
5176 // lastprivate clause requires an accessible, unambiguous default
5177 // constructor for the class type, unless the list item is also specified
5178 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00005179 // A variable of class type (or array thereof) that appears in a
5180 // lastprivate clause requires an accessible, unambiguous copy assignment
5181 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00005182 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00005183 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
Alexey Bataev38e89532015-04-16 04:54:05 +00005184 Type.getUnqualifiedType(), ".lastprivate.src");
Alexey Bataev39f915b82015-05-08 10:41:21 +00005185 auto *PseudoSrcExpr = buildDeclRefExpr(
5186 *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00005187 auto *DstVD =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005188 buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst");
Alexey Bataev38e89532015-04-16 04:54:05 +00005189 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005190 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00005191 // For arrays generate assignment operation for single element and replace
5192 // it by the original array element in CodeGen.
5193 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
5194 PseudoDstExpr, PseudoSrcExpr);
5195 if (AssignmentOp.isInvalid())
5196 continue;
5197 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
5198 /*DiscardedValue=*/true);
5199 if (AssignmentOp.isInvalid())
5200 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005201
Alexey Bataev39f915b82015-05-08 10:41:21 +00005202 if (TopDVar.CKind != OMPC_firstprivate)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005203 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005204 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005205 SrcExprs.push_back(PseudoSrcExpr);
5206 DstExprs.push_back(PseudoDstExpr);
5207 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00005208 }
5209
5210 if (Vars.empty())
5211 return nullptr;
5212
5213 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00005214 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005215}
5216
Alexey Bataev758e55e2013-09-06 18:03:48 +00005217OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
5218 SourceLocation StartLoc,
5219 SourceLocation LParenLoc,
5220 SourceLocation EndLoc) {
5221 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00005222 for (auto &RefExpr : VarList) {
5223 assert(RefExpr && "NULL expr in OpenMP shared clause.");
5224 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00005225 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005226 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005227 continue;
5228 }
5229
Alexey Bataeved09d242014-05-28 05:53:51 +00005230 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005231 // OpenMP [2.1, C/C++]
5232 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00005233 // OpenMP [2.14.3.2, Restrictions, p.1]
5234 // A variable that is part of another variable (as an array or structure
5235 // element) cannot appear in a shared unless it is a static data member
5236 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00005237 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005238 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005239 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005240 continue;
5241 }
5242 Decl *D = DE->getDecl();
5243 VarDecl *VD = cast<VarDecl>(D);
5244
5245 QualType Type = VD->getType();
5246 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5247 // It will be analyzed later.
5248 Vars.push_back(DE);
5249 continue;
5250 }
5251
5252 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5253 // in a Construct]
5254 // Variables with the predetermined data-sharing attributes may not be
5255 // listed in data-sharing attributes clauses, except for the cases
5256 // listed below. For these exceptions only, listing a predetermined
5257 // variable in a data-sharing attribute clause is allowed and overrides
5258 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005259 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00005260 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
5261 DVar.RefExpr) {
5262 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5263 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005264 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005265 continue;
5266 }
5267
5268 DSAStack->addDSA(VD, DE, OMPC_shared);
5269 Vars.push_back(DE);
5270 }
5271
Alexey Bataeved09d242014-05-28 05:53:51 +00005272 if (Vars.empty())
5273 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00005274
5275 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5276}
5277
Alexey Bataevc5e02582014-06-16 07:08:35 +00005278namespace {
5279class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
5280 DSAStackTy *Stack;
5281
5282public:
5283 bool VisitDeclRefExpr(DeclRefExpr *E) {
5284 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005285 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005286 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
5287 return false;
5288 if (DVar.CKind != OMPC_unknown)
5289 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00005290 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005291 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005292 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00005293 return true;
5294 return false;
5295 }
5296 return false;
5297 }
5298 bool VisitStmt(Stmt *S) {
5299 for (auto Child : S->children()) {
5300 if (Child && Visit(Child))
5301 return true;
5302 }
5303 return false;
5304 }
Alexey Bataev23b69422014-06-18 07:08:49 +00005305 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00005306};
Alexey Bataev23b69422014-06-18 07:08:49 +00005307} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00005308
5309OMPClause *Sema::ActOnOpenMPReductionClause(
5310 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
5311 SourceLocation ColonLoc, SourceLocation EndLoc,
5312 CXXScopeSpec &ReductionIdScopeSpec,
5313 const DeclarationNameInfo &ReductionId) {
5314 // TODO: Allow scope specification search when 'declare reduction' is
5315 // supported.
5316 assert(ReductionIdScopeSpec.isEmpty() &&
5317 "No support for scoped reduction identifiers yet.");
5318
5319 auto DN = ReductionId.getName();
5320 auto OOK = DN.getCXXOverloadedOperator();
5321 BinaryOperatorKind BOK = BO_Comma;
5322
5323 // OpenMP [2.14.3.6, reduction clause]
5324 // C
5325 // reduction-identifier is either an identifier or one of the following
5326 // operators: +, -, *, &, |, ^, && and ||
5327 // C++
5328 // reduction-identifier is either an id-expression or one of the following
5329 // operators: +, -, *, &, |, ^, && and ||
5330 // FIXME: Only 'min' and 'max' identifiers are supported for now.
5331 switch (OOK) {
5332 case OO_Plus:
5333 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005334 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005335 break;
5336 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005337 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005338 break;
5339 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005340 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005341 break;
5342 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005343 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005344 break;
5345 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005346 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005347 break;
5348 case OO_AmpAmp:
5349 BOK = BO_LAnd;
5350 break;
5351 case OO_PipePipe:
5352 BOK = BO_LOr;
5353 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005354 case OO_New:
5355 case OO_Delete:
5356 case OO_Array_New:
5357 case OO_Array_Delete:
5358 case OO_Slash:
5359 case OO_Percent:
5360 case OO_Tilde:
5361 case OO_Exclaim:
5362 case OO_Equal:
5363 case OO_Less:
5364 case OO_Greater:
5365 case OO_LessEqual:
5366 case OO_GreaterEqual:
5367 case OO_PlusEqual:
5368 case OO_MinusEqual:
5369 case OO_StarEqual:
5370 case OO_SlashEqual:
5371 case OO_PercentEqual:
5372 case OO_CaretEqual:
5373 case OO_AmpEqual:
5374 case OO_PipeEqual:
5375 case OO_LessLess:
5376 case OO_GreaterGreater:
5377 case OO_LessLessEqual:
5378 case OO_GreaterGreaterEqual:
5379 case OO_EqualEqual:
5380 case OO_ExclaimEqual:
5381 case OO_PlusPlus:
5382 case OO_MinusMinus:
5383 case OO_Comma:
5384 case OO_ArrowStar:
5385 case OO_Arrow:
5386 case OO_Call:
5387 case OO_Subscript:
5388 case OO_Conditional:
5389 case NUM_OVERLOADED_OPERATORS:
5390 llvm_unreachable("Unexpected reduction identifier");
5391 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005392 if (auto II = DN.getAsIdentifierInfo()) {
5393 if (II->isStr("max"))
5394 BOK = BO_GT;
5395 else if (II->isStr("min"))
5396 BOK = BO_LT;
5397 }
5398 break;
5399 }
5400 SourceRange ReductionIdRange;
5401 if (ReductionIdScopeSpec.isValid()) {
5402 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
5403 }
5404 ReductionIdRange.setEnd(ReductionId.getEndLoc());
5405 if (BOK == BO_Comma) {
5406 // Not allowed reduction identifier is found.
5407 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
5408 << ReductionIdRange;
5409 return nullptr;
5410 }
5411
5412 SmallVector<Expr *, 8> Vars;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005413 SmallVector<Expr *, 8> LHSs;
5414 SmallVector<Expr *, 8> RHSs;
5415 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005416 for (auto RefExpr : VarList) {
5417 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
5418 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5419 // It will be analyzed later.
5420 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005421 LHSs.push_back(nullptr);
5422 RHSs.push_back(nullptr);
5423 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005424 continue;
5425 }
5426
5427 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5428 RefExpr->isInstantiationDependent() ||
5429 RefExpr->containsUnexpandedParameterPack()) {
5430 // It will be analyzed later.
5431 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005432 LHSs.push_back(nullptr);
5433 RHSs.push_back(nullptr);
5434 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005435 continue;
5436 }
5437
5438 auto ELoc = RefExpr->getExprLoc();
5439 auto ERange = RefExpr->getSourceRange();
5440 // OpenMP [2.1, C/C++]
5441 // A list item is a variable or array section, subject to the restrictions
5442 // specified in Section 2.4 on page 42 and in each of the sections
5443 // describing clauses and directives for which a list appears.
5444 // OpenMP [2.14.3.3, Restrictions, p.1]
5445 // A variable that is part of another variable (as an array or
5446 // structure element) cannot appear in a private clause.
5447 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
5448 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5449 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
5450 continue;
5451 }
5452 auto D = DE->getDecl();
5453 auto VD = cast<VarDecl>(D);
5454 auto Type = VD->getType();
5455 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5456 // A variable that appears in a private clause must not have an incomplete
5457 // type or a reference type.
5458 if (RequireCompleteType(ELoc, Type,
5459 diag::err_omp_reduction_incomplete_type))
5460 continue;
5461 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5462 // Arrays may not appear in a reduction clause.
5463 if (Type.getNonReferenceType()->isArrayType()) {
5464 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
5465 bool IsDecl =
5466 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5467 Diag(VD->getLocation(),
5468 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5469 << VD;
5470 continue;
5471 }
5472 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5473 // A list item that appears in a reduction clause must not be
5474 // const-qualified.
5475 if (Type.getNonReferenceType().isConstant(Context)) {
5476 Diag(ELoc, diag::err_omp_const_variable)
5477 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
5478 bool IsDecl =
5479 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5480 Diag(VD->getLocation(),
5481 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5482 << VD;
5483 continue;
5484 }
5485 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
5486 // If a list-item is a reference type then it must bind to the same object
5487 // for all threads of the team.
5488 VarDecl *VDDef = VD->getDefinition();
5489 if (Type->isReferenceType() && VDDef) {
5490 DSARefChecker Check(DSAStack);
5491 if (Check.Visit(VDDef->getInit())) {
5492 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
5493 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
5494 continue;
5495 }
5496 }
5497 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5498 // The type of a list item that appears in a reduction clause must be valid
5499 // for the reduction-identifier. For a max or min reduction in C, the type
5500 // of the list item must be an allowed arithmetic data type: char, int,
5501 // float, double, or _Bool, possibly modified with long, short, signed, or
5502 // unsigned. For a max or min reduction in C++, the type of the list item
5503 // must be an allowed arithmetic data type: char, wchar_t, int, float,
5504 // double, or bool, possibly modified with long, short, signed, or unsigned.
5505 if ((BOK == BO_GT || BOK == BO_LT) &&
5506 !(Type->isScalarType() ||
5507 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
5508 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
5509 << getLangOpts().CPlusPlus;
5510 bool IsDecl =
5511 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5512 Diag(VD->getLocation(),
5513 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5514 << VD;
5515 continue;
5516 }
5517 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
5518 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
5519 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
5520 bool IsDecl =
5521 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5522 Diag(VD->getLocation(),
5523 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5524 << VD;
5525 continue;
5526 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00005527 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5528 // in a Construct]
5529 // Variables with the predetermined data-sharing attributes may not be
5530 // listed in data-sharing attributes clauses, except for the cases
5531 // listed below. For these exceptions only, listing a predetermined
5532 // variable in a data-sharing attribute clause is allowed and overrides
5533 // the variable's predetermined data-sharing attributes.
5534 // OpenMP [2.14.3.6, Restrictions, p.3]
5535 // Any number of reduction clauses can be specified on the directive,
5536 // but a list item can appear only once in the reduction clauses for that
5537 // directive.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005538 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005539 if (DVar.CKind == OMPC_reduction) {
5540 Diag(ELoc, diag::err_omp_once_referenced)
5541 << getOpenMPClauseName(OMPC_reduction);
5542 if (DVar.RefExpr) {
5543 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
5544 }
5545 } else if (DVar.CKind != OMPC_unknown) {
5546 Diag(ELoc, diag::err_omp_wrong_dsa)
5547 << getOpenMPClauseName(DVar.CKind)
5548 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005549 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005550 continue;
5551 }
5552
5553 // OpenMP [2.14.3.6, Restrictions, p.1]
5554 // A list item that appears in a reduction clause of a worksharing
5555 // construct must be shared in the parallel regions to which any of the
5556 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf29276e2014-06-18 04:14:57 +00005557 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataev549210e2014-06-24 04:39:47 +00005558 if (isOpenMPWorksharingDirective(CurrDir) &&
5559 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005560 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005561 if (DVar.CKind != OMPC_shared) {
5562 Diag(ELoc, diag::err_omp_required_access)
5563 << getOpenMPClauseName(OMPC_reduction)
5564 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005565 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005566 continue;
5567 }
5568 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005569 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00005570 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs");
5571 auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005572 // Add initializer for private variable.
5573 Expr *Init = nullptr;
5574 switch (BOK) {
5575 case BO_Add:
5576 case BO_Xor:
5577 case BO_Or:
5578 case BO_LOr:
5579 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
5580 if (Type->isScalarType() || Type->isAnyComplexType()) {
5581 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005582 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005583 break;
5584 case BO_Mul:
5585 case BO_LAnd:
5586 if (Type->isScalarType() || Type->isAnyComplexType()) {
5587 // '*' and '&&' reduction ops - initializer is '1'.
5588 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
5589 }
5590 break;
5591 case BO_And: {
5592 // '&' reduction op - initializer is '~0'.
5593 QualType OrigType = Type;
5594 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
5595 Type = ComplexTy->getElementType();
5596 }
5597 if (Type->isRealFloatingType()) {
5598 llvm::APFloat InitValue =
5599 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
5600 /*isIEEE=*/true);
5601 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5602 Type, ELoc);
5603 } else if (Type->isScalarType()) {
5604 auto Size = Context.getTypeSize(Type);
5605 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
5606 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
5607 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5608 }
5609 if (Init && OrigType->isAnyComplexType()) {
5610 // Init = 0xFFFF + 0xFFFFi;
5611 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
5612 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
5613 }
5614 Type = OrigType;
5615 break;
5616 }
5617 case BO_LT:
5618 case BO_GT: {
5619 // 'min' reduction op - initializer is 'Largest representable number in
5620 // the reduction list item type'.
5621 // 'max' reduction op - initializer is 'Least representable number in
5622 // the reduction list item type'.
5623 if (Type->isIntegerType() || Type->isPointerType()) {
5624 bool IsSigned = Type->hasSignedIntegerRepresentation();
5625 auto Size = Context.getTypeSize(Type);
5626 QualType IntTy =
5627 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
5628 llvm::APInt InitValue =
5629 (BOK != BO_LT)
5630 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
5631 : llvm::APInt::getMinValue(Size)
5632 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
5633 : llvm::APInt::getMaxValue(Size);
5634 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5635 if (Type->isPointerType()) {
5636 // Cast to pointer type.
5637 auto CastExpr = BuildCStyleCastExpr(
5638 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
5639 SourceLocation(), Init);
5640 if (CastExpr.isInvalid())
5641 continue;
5642 Init = CastExpr.get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005643 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005644 } else if (Type->isRealFloatingType()) {
5645 llvm::APFloat InitValue = llvm::APFloat::getLargest(
5646 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
5647 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5648 Type, ELoc);
5649 }
5650 break;
5651 }
5652 case BO_PtrMemD:
5653 case BO_PtrMemI:
5654 case BO_MulAssign:
5655 case BO_Div:
5656 case BO_Rem:
5657 case BO_Sub:
5658 case BO_Shl:
5659 case BO_Shr:
5660 case BO_LE:
5661 case BO_GE:
5662 case BO_EQ:
5663 case BO_NE:
5664 case BO_AndAssign:
5665 case BO_XorAssign:
5666 case BO_OrAssign:
5667 case BO_Assign:
5668 case BO_AddAssign:
5669 case BO_SubAssign:
5670 case BO_DivAssign:
5671 case BO_RemAssign:
5672 case BO_ShlAssign:
5673 case BO_ShrAssign:
5674 case BO_Comma:
5675 llvm_unreachable("Unexpected reduction operation");
5676 }
5677 if (Init) {
5678 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
5679 /*TypeMayContainAuto=*/false);
5680 } else {
5681 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
5682 }
5683 if (!RHSVD->hasInit()) {
5684 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
5685 << ReductionIdRange;
5686 bool IsDecl =
5687 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5688 Diag(VD->getLocation(),
5689 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5690 << VD;
5691 continue;
5692 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00005693 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
5694 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005695 ExprResult ReductionOp =
5696 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
5697 LHSDRE, RHSDRE);
5698 if (ReductionOp.isUsable()) {
Alexey Bataev69a47792015-05-07 03:54:03 +00005699 if (BOK != BO_LT && BOK != BO_GT) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005700 ReductionOp =
5701 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5702 BO_Assign, LHSDRE, ReductionOp.get());
5703 } else {
5704 auto *ConditionalOp = new (Context) ConditionalOperator(
5705 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
5706 RHSDRE, Type, VK_LValue, OK_Ordinary);
5707 ReductionOp =
5708 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5709 BO_Assign, LHSDRE, ConditionalOp);
5710 }
5711 if (ReductionOp.isUsable()) {
5712 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005713 }
5714 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005715 if (ReductionOp.isInvalid())
5716 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005717
5718 DSAStack->addDSA(VD, DE, OMPC_reduction);
5719 Vars.push_back(DE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005720 LHSs.push_back(LHSDRE);
5721 RHSs.push_back(RHSDRE);
5722 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005723 }
5724
5725 if (Vars.empty())
5726 return nullptr;
5727
5728 return OMPReductionClause::Create(
5729 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005730 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
5731 RHSs, ReductionOps);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005732}
5733
Alexander Musman8dba6642014-04-22 13:09:42 +00005734OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
5735 SourceLocation StartLoc,
5736 SourceLocation LParenLoc,
5737 SourceLocation ColonLoc,
5738 SourceLocation EndLoc) {
5739 SmallVector<Expr *, 8> Vars;
Alexander Musman3276a272015-03-21 10:12:56 +00005740 SmallVector<Expr *, 8> Inits;
Alexey Bataeved09d242014-05-28 05:53:51 +00005741 for (auto &RefExpr : VarList) {
5742 assert(RefExpr && "NULL expr in OpenMP linear clause.");
5743 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00005744 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005745 Vars.push_back(RefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00005746 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005747 continue;
5748 }
5749
5750 // OpenMP [2.14.3.7, linear clause]
5751 // A list item that appears in a linear clause is subject to the private
5752 // clause semantics described in Section 2.14.3.3 on page 159 except as
5753 // noted. In addition, the value of the new list item on each iteration
5754 // of the associated loop(s) corresponds to the value of the original
5755 // list item before entering the construct plus the logical number of
5756 // the iteration times linear-step.
5757
Alexey Bataeved09d242014-05-28 05:53:51 +00005758 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00005759 // OpenMP [2.1, C/C++]
5760 // A list item is a variable name.
5761 // OpenMP [2.14.3.3, Restrictions, p.1]
5762 // A variable that is part of another variable (as an array or
5763 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005764 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005765 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005766 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00005767 continue;
5768 }
5769
5770 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5771
5772 // OpenMP [2.14.3.7, linear clause]
5773 // A list-item cannot appear in more than one linear clause.
5774 // A list-item that appears in a linear clause cannot appear in any
5775 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005776 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00005777 if (DVar.RefExpr) {
5778 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5779 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005780 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00005781 continue;
5782 }
5783
5784 QualType QType = VD->getType();
5785 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
5786 // It will be analyzed later.
5787 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005788 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005789 continue;
5790 }
5791
5792 // A variable must not have an incomplete type or a reference type.
5793 if (RequireCompleteType(ELoc, QType,
5794 diag::err_omp_linear_incomplete_type)) {
5795 continue;
5796 }
5797 if (QType->isReferenceType()) {
5798 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5799 << getOpenMPClauseName(OMPC_linear) << QType;
5800 bool IsDecl =
5801 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5802 Diag(VD->getLocation(),
5803 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5804 << VD;
5805 continue;
5806 }
5807
5808 // A list item must not be const-qualified.
5809 if (QType.isConstant(Context)) {
5810 Diag(ELoc, diag::err_omp_const_variable)
5811 << getOpenMPClauseName(OMPC_linear);
5812 bool IsDecl =
5813 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5814 Diag(VD->getLocation(),
5815 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5816 << VD;
5817 continue;
5818 }
5819
5820 // A list item must be of integral or pointer type.
5821 QType = QType.getUnqualifiedType().getCanonicalType();
5822 const Type *Ty = QType.getTypePtrOrNull();
5823 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
5824 !Ty->isPointerType())) {
5825 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
5826 bool IsDecl =
5827 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5828 Diag(VD->getLocation(),
5829 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5830 << VD;
5831 continue;
5832 }
5833
Alexander Musman3276a272015-03-21 10:12:56 +00005834 // Build var to save initial value.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005835 VarDecl *Init = buildVarDecl(*this, ELoc, DE->getType(), ".linear.start");
Alexander Musman3276a272015-03-21 10:12:56 +00005836 AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
5837 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005838 auto InitRef =
5839 buildDeclRefExpr(*this, Init, DE->getType(), DE->getExprLoc());
Alexander Musman8dba6642014-04-22 13:09:42 +00005840 DSAStack->addDSA(VD, DE, OMPC_linear);
5841 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005842 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00005843 }
5844
5845 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005846 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005847
5848 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00005849 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005850 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5851 !Step->isInstantiationDependent() &&
5852 !Step->containsUnexpandedParameterPack()) {
5853 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005854 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00005855 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005856 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005857 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00005858
Alexander Musman3276a272015-03-21 10:12:56 +00005859 // Build var to save the step value.
5860 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005861 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00005862 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005863 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00005864 ExprResult CalcStep =
5865 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
5866
Alexander Musman8dba6642014-04-22 13:09:42 +00005867 // Warn about zero linear step (it would be probably better specified as
5868 // making corresponding variables 'const').
5869 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00005870 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
5871 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00005872 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
5873 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00005874 if (!IsConstant && CalcStep.isUsable()) {
5875 // Calculate the step beforehand instead of doing this on each iteration.
5876 // (This is not used if the number of iterations may be kfold-ed).
5877 CalcStepExpr = CalcStep.get();
5878 }
Alexander Musman8dba6642014-04-22 13:09:42 +00005879 }
5880
5881 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
Alexander Musman3276a272015-03-21 10:12:56 +00005882 Vars, Inits, StepExpr, CalcStepExpr);
5883}
5884
5885static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
5886 Expr *NumIterations, Sema &SemaRef,
5887 Scope *S) {
5888 // Walk the vars and build update/final expressions for the CodeGen.
5889 SmallVector<Expr *, 8> Updates;
5890 SmallVector<Expr *, 8> Finals;
5891 Expr *Step = Clause.getStep();
5892 Expr *CalcStep = Clause.getCalcStep();
5893 // OpenMP [2.14.3.7, linear clause]
5894 // If linear-step is not specified it is assumed to be 1.
5895 if (Step == nullptr)
5896 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5897 else if (CalcStep)
5898 Step = cast<BinaryOperator>(CalcStep)->getLHS();
5899 bool HasErrors = false;
5900 auto CurInit = Clause.inits().begin();
5901 for (auto &RefExpr : Clause.varlists()) {
5902 Expr *InitExpr = *CurInit;
5903
5904 // Build privatized reference to the current linear var.
5905 auto DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005906 auto PrivateRef =
5907 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), DE->getType(),
5908 DE->getExprLoc(), /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00005909
5910 // Build update: Var = InitExpr + IV * Step
5911 ExprResult Update =
5912 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
5913 InitExpr, IV, Step, /* Subtract */ false);
5914 Update = SemaRef.ActOnFinishFullExpr(Update.get());
5915
5916 // Build final: Var = InitExpr + NumIterations * Step
5917 ExprResult Final =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005918 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
5919 InitExpr, NumIterations, Step, /* Subtract */ false);
Alexander Musman3276a272015-03-21 10:12:56 +00005920 Final = SemaRef.ActOnFinishFullExpr(Final.get());
5921 if (!Update.isUsable() || !Final.isUsable()) {
5922 Updates.push_back(nullptr);
5923 Finals.push_back(nullptr);
5924 HasErrors = true;
5925 } else {
5926 Updates.push_back(Update.get());
5927 Finals.push_back(Final.get());
5928 }
5929 ++CurInit;
5930 }
5931 Clause.setUpdates(Updates);
5932 Clause.setFinals(Finals);
5933 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00005934}
5935
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005936OMPClause *Sema::ActOnOpenMPAlignedClause(
5937 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
5938 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
5939
5940 SmallVector<Expr *, 8> Vars;
5941 for (auto &RefExpr : VarList) {
5942 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
5943 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5944 // It will be analyzed later.
5945 Vars.push_back(RefExpr);
5946 continue;
5947 }
5948
5949 SourceLocation ELoc = RefExpr->getExprLoc();
5950 // OpenMP [2.1, C/C++]
5951 // A list item is a variable name.
5952 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5953 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5954 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5955 continue;
5956 }
5957
5958 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5959
5960 // OpenMP [2.8.1, simd construct, Restrictions]
5961 // The type of list items appearing in the aligned clause must be
5962 // array, pointer, reference to array, or reference to pointer.
5963 QualType QType = DE->getType()
5964 .getNonReferenceType()
5965 .getUnqualifiedType()
5966 .getCanonicalType();
5967 const Type *Ty = QType.getTypePtrOrNull();
5968 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
5969 !Ty->isPointerType())) {
5970 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
5971 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
5972 bool IsDecl =
5973 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5974 Diag(VD->getLocation(),
5975 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5976 << VD;
5977 continue;
5978 }
5979
5980 // OpenMP [2.8.1, simd construct, Restrictions]
5981 // A list-item cannot appear in more than one aligned clause.
5982 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
5983 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
5984 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
5985 << getOpenMPClauseName(OMPC_aligned);
5986 continue;
5987 }
5988
5989 Vars.push_back(DE);
5990 }
5991
5992 // OpenMP [2.8.1, simd construct, Description]
5993 // The parameter of the aligned clause, alignment, must be a constant
5994 // positive integer expression.
5995 // If no optional parameter is specified, implementation-defined default
5996 // alignments for SIMD instructions on the target platforms are assumed.
5997 if (Alignment != nullptr) {
5998 ExprResult AlignResult =
5999 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
6000 if (AlignResult.isInvalid())
6001 return nullptr;
6002 Alignment = AlignResult.get();
6003 }
6004 if (Vars.empty())
6005 return nullptr;
6006
6007 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
6008 EndLoc, Vars, Alignment);
6009}
6010
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006011OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
6012 SourceLocation StartLoc,
6013 SourceLocation LParenLoc,
6014 SourceLocation EndLoc) {
6015 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006016 SmallVector<Expr *, 8> SrcExprs;
6017 SmallVector<Expr *, 8> DstExprs;
6018 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00006019 for (auto &RefExpr : VarList) {
6020 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
6021 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006022 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006023 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006024 SrcExprs.push_back(nullptr);
6025 DstExprs.push_back(nullptr);
6026 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006027 continue;
6028 }
6029
Alexey Bataeved09d242014-05-28 05:53:51 +00006030 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006031 // OpenMP [2.1, C/C++]
6032 // A list item is a variable name.
6033 // OpenMP [2.14.4.1, Restrictions, p.1]
6034 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00006035 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006036 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00006037 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006038 continue;
6039 }
6040
6041 Decl *D = DE->getDecl();
6042 VarDecl *VD = cast<VarDecl>(D);
6043
6044 QualType Type = VD->getType();
6045 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6046 // It will be analyzed later.
6047 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006048 SrcExprs.push_back(nullptr);
6049 DstExprs.push_back(nullptr);
6050 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006051 continue;
6052 }
6053
6054 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
6055 // A list item that appears in a copyin clause must be threadprivate.
6056 if (!DSAStack->isThreadPrivate(VD)) {
6057 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00006058 << getOpenMPClauseName(OMPC_copyin)
6059 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006060 continue;
6061 }
6062
6063 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6064 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00006065 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006066 // operator for the class type.
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006067 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00006068 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006069 Type.getUnqualifiedType(), ".copyin.src");
Alexey Bataev39f915b82015-05-08 10:41:21 +00006070 auto *PseudoSrcExpr = buildDeclRefExpr(
6071 *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
6072 auto *DstVD = buildVarDecl(*this, DE->getLocStart(), Type, ".copyin.dst");
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006073 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006074 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006075 // For arrays generate assignment operation for single element and replace
6076 // it by the original array element in CodeGen.
6077 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6078 PseudoDstExpr, PseudoSrcExpr);
6079 if (AssignmentOp.isInvalid())
6080 continue;
6081 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6082 /*DiscardedValue=*/true);
6083 if (AssignmentOp.isInvalid())
6084 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006085
6086 DSAStack->addDSA(VD, DE, OMPC_copyin);
6087 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006088 SrcExprs.push_back(PseudoSrcExpr);
6089 DstExprs.push_back(PseudoDstExpr);
6090 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006091 }
6092
Alexey Bataeved09d242014-05-28 05:53:51 +00006093 if (Vars.empty())
6094 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006095
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006096 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
6097 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006098}
6099
Alexey Bataevbae9a792014-06-27 10:37:06 +00006100OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
6101 SourceLocation StartLoc,
6102 SourceLocation LParenLoc,
6103 SourceLocation EndLoc) {
6104 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00006105 SmallVector<Expr *, 8> SrcExprs;
6106 SmallVector<Expr *, 8> DstExprs;
6107 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006108 for (auto &RefExpr : VarList) {
6109 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
6110 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6111 // It will be analyzed later.
6112 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006113 SrcExprs.push_back(nullptr);
6114 DstExprs.push_back(nullptr);
6115 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006116 continue;
6117 }
6118
6119 SourceLocation ELoc = RefExpr->getExprLoc();
6120 // OpenMP [2.1, C/C++]
6121 // A list item is a variable name.
6122 // OpenMP [2.14.4.1, Restrictions, p.1]
6123 // A list item that appears in a copyin clause must be threadprivate.
6124 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6125 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6126 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6127 continue;
6128 }
6129
6130 Decl *D = DE->getDecl();
6131 VarDecl *VD = cast<VarDecl>(D);
6132
6133 QualType Type = VD->getType();
6134 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6135 // It will be analyzed later.
6136 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006137 SrcExprs.push_back(nullptr);
6138 DstExprs.push_back(nullptr);
6139 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006140 continue;
6141 }
6142
6143 // OpenMP [2.14.4.2, Restrictions, p.2]
6144 // A list item that appears in a copyprivate clause may not appear in a
6145 // private or firstprivate clause on the single construct.
6146 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006147 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006148 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
6149 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00006150 Diag(ELoc, diag::err_omp_wrong_dsa)
6151 << getOpenMPClauseName(DVar.CKind)
6152 << getOpenMPClauseName(OMPC_copyprivate);
6153 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6154 continue;
6155 }
6156
6157 // OpenMP [2.11.4.2, Restrictions, p.1]
6158 // All list items that appear in a copyprivate clause must be either
6159 // threadprivate or private in the enclosing context.
6160 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006161 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006162 if (DVar.CKind == OMPC_shared) {
6163 Diag(ELoc, diag::err_omp_required_access)
6164 << getOpenMPClauseName(OMPC_copyprivate)
6165 << "threadprivate or private in the enclosing context";
6166 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6167 continue;
6168 }
6169 }
6170 }
6171
6172 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6173 // A variable of class type (or array thereof) that appears in a
6174 // copyin clause requires an accessible, unambiguous copy assignment
6175 // operator for the class type.
Alexey Bataev420d45b2015-04-14 05:11:24 +00006176 Type = Context.getBaseElementType(Type).getUnqualifiedType();
6177 auto *SrcVD =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006178 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src");
Alexey Bataev420d45b2015-04-14 05:11:24 +00006179 auto *PseudoSrcExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006180 buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
Alexey Bataev420d45b2015-04-14 05:11:24 +00006181 auto *DstVD =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006182 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst");
Alexey Bataev420d45b2015-04-14 05:11:24 +00006183 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006184 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataeva63048e2015-03-23 06:18:07 +00006185 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6186 PseudoDstExpr, PseudoSrcExpr);
6187 if (AssignmentOp.isInvalid())
6188 continue;
6189 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6190 /*DiscardedValue=*/true);
6191 if (AssignmentOp.isInvalid())
6192 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006193
6194 // No need to mark vars as copyprivate, they are already threadprivate or
6195 // implicitly private.
6196 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006197 SrcExprs.push_back(PseudoSrcExpr);
6198 DstExprs.push_back(PseudoDstExpr);
6199 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00006200 }
6201
6202 if (Vars.empty())
6203 return nullptr;
6204
Alexey Bataeva63048e2015-03-23 06:18:07 +00006205 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6206 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006207}
6208
Alexey Bataev6125da92014-07-21 11:26:11 +00006209OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
6210 SourceLocation StartLoc,
6211 SourceLocation LParenLoc,
6212 SourceLocation EndLoc) {
6213 if (VarList.empty())
6214 return nullptr;
6215
6216 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
6217}
Alexey Bataevdea47612014-07-23 07:46:59 +00006218