blob: ea619ffb3268fe32cbe93676bea92d40fc9ee6f8 [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 Bataevf120c0d2015-05-19 07:46:42 +0000508 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
509 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000510 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
511 // in a Construct, C/C++, predetermined, p.6]
512 // Variables with const qualified type having no mutable member are
513 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000514 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000515 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000516 if (IsConstant &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000517 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000518 // Variables with const-qualified type having no mutable member may be
519 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000520 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
521 MatchesAlways(), FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000522 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
523 return DVar;
524
Alexey Bataev758e55e2013-09-06 18:03:48 +0000525 DVar.CKind = OMPC_shared;
526 return DVar;
527 }
528
Alexey Bataev758e55e2013-09-06 18:03:48 +0000529 // Explicitly specified attributes and local variables with predetermined
530 // attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000531 auto I = std::prev(StartI);
532 if (I->SharingMap.count(D)) {
533 DVar.RefExpr = I->SharingMap[D].RefExpr;
534 DVar.CKind = I->SharingMap[D].Attributes;
535 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000536 }
537
538 return DVar;
539}
540
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000541DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000542 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000543 auto StartI = Stack.rbegin();
544 auto EndI = std::prev(Stack.rend());
545 if (FromParent && StartI != EndI) {
546 StartI = std::next(StartI);
547 }
548 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000549}
550
Alexey Bataevf29276e2014-06-18 04:14:57 +0000551template <class ClausesPredicate, class DirectivesPredicate>
552DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000553 DirectivesPredicate DPred,
554 bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000555 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000556 auto StartI = std::next(Stack.rbegin());
557 auto EndI = std::prev(Stack.rend());
558 if (FromParent && StartI != EndI) {
559 StartI = std::next(StartI);
560 }
561 for (auto I = StartI, EE = EndI; I != EE; ++I) {
562 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000563 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000564 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000565 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000566 return DVar;
567 }
568 return DSAVarData();
569}
570
Alexey Bataevf29276e2014-06-18 04:14:57 +0000571template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000572DSAStackTy::DSAVarData
573DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
574 DirectivesPredicate DPred, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000575 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000576 auto StartI = std::next(Stack.rbegin());
577 auto EndI = std::prev(Stack.rend());
578 if (FromParent && StartI != EndI) {
579 StartI = std::next(StartI);
580 }
581 for (auto I = StartI, EE = EndI; I != EE; ++I) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000582 if (!DPred(I->Directive))
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000583 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +0000584 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000585 if (CPred(DVar.CKind))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000586 return DVar;
587 return DSAVarData();
588 }
589 return DSAVarData();
590}
591
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000592template <class NamedDirectivesPredicate>
593bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
594 auto StartI = std::next(Stack.rbegin());
595 auto EndI = std::prev(Stack.rend());
596 if (FromParent && StartI != EndI) {
597 StartI = std::next(StartI);
598 }
599 for (auto I = StartI, EE = EndI; I != EE; ++I) {
600 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
601 return true;
602 }
603 return false;
604}
605
Alexey Bataev758e55e2013-09-06 18:03:48 +0000606void Sema::InitDataSharingAttributesStack() {
607 VarDataSharingAttributesStack = new DSAStackTy(*this);
608}
609
610#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
611
Alexey Bataevf841bd92014-12-16 07:00:22 +0000612bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
613 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000614 VD = VD->getCanonicalDecl();
Alexey Bataevf841bd92014-12-16 07:00:22 +0000615 if (DSAStack->getCurrentDirective() != OMPD_unknown) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000616 if (DSAStack->isLoopControlVariable(VD) ||
617 (VD->hasLocalStorage() &&
618 isParallelOrTaskRegion(DSAStack->getCurrentDirective())))
Alexey Bataev9c821032015-04-30 04:23:23 +0000619 return true;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000620 auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isFromParent());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000621 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
622 return true;
623 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000624 DSAStack->isFromParent());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000625 return DVarPrivate.CKind != OMPC_unknown;
626 }
627 return false;
628}
629
Alexey Bataeved09d242014-05-28 05:53:51 +0000630void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000631
632void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
633 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000634 Scope *CurScope, SourceLocation Loc) {
635 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000636 PushExpressionEvaluationContext(PotentiallyEvaluated);
637}
638
Alexey Bataev39f915b82015-05-08 10:41:21 +0000639void Sema::StartOpenMPClauses() {
640 DSAStack->setFromParent(/*Flag=*/true);
641}
642
643void Sema::EndOpenMPClauses() {
644 DSAStack->setFromParent(/*Flag=*/false);
645}
646
Alexey Bataev758e55e2013-09-06 18:03:48 +0000647void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000648 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
649 // A variable of class type (or array thereof) that appears in a lastprivate
650 // clause requires an accessible, unambiguous default constructor for the
651 // class type, unless the list item is also specified in a firstprivate
652 // clause.
653 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000654 for (auto *C : D->clauses()) {
655 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
656 SmallVector<Expr *, 8> PrivateCopies;
657 for (auto *DE : Clause->varlists()) {
658 if (DE->isValueDependent() || DE->isTypeDependent()) {
659 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000660 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +0000661 }
662 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000663 QualType Type = VD->getType();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000664 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000665 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000666 // Generate helper private variable and initialize it with the
667 // default value. The address of the original variable is replaced
668 // by the address of the new private variable in CodeGen. This new
669 // variable is not added to IdResolver, so the code in the OpenMP
670 // region uses original variable for proper diagnostics.
Alexey Bataev39f915b82015-05-08 10:41:21 +0000671 auto *VDPrivate =
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000672 buildVarDecl(*this, DE->getExprLoc(), Type.getUnqualifiedType(),
673 VD->getName());
Alexey Bataev38e89532015-04-16 04:54:05 +0000674 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
675 if (VDPrivate->isInvalidDecl())
676 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000677 PrivateCopies.push_back(buildDeclRefExpr(
678 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +0000679 } else {
680 // The variable is also a firstprivate, so initialization sequence
681 // for private copy is generated already.
682 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000683 }
684 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000685 // Set initializers to private copies if no errors were found.
686 if (PrivateCopies.size() == Clause->varlist_size()) {
687 Clause->setPrivateCopies(PrivateCopies);
688 }
Alexey Bataevf29276e2014-06-18 04:14:57 +0000689 }
690 }
691 }
692
Alexey Bataev758e55e2013-09-06 18:03:48 +0000693 DSAStack->pop();
694 DiscardCleanupsInEvaluationContext();
695 PopExpressionEvaluationContext();
696}
697
Alexander Musman3276a272015-03-21 10:12:56 +0000698static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
699 Expr *NumIterations, Sema &SemaRef,
700 Scope *S);
701
Alexey Bataeva769e072013-03-22 06:34:35 +0000702namespace {
703
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000704class VarDeclFilterCCC : public CorrectionCandidateCallback {
705private:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000706 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +0000707
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000708public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000709 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +0000710 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000711 NamedDecl *ND = Candidate.getCorrectionDecl();
712 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
713 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000714 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
715 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +0000716 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000717 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +0000718 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000719};
Alexey Bataeved09d242014-05-28 05:53:51 +0000720} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000721
722ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
723 CXXScopeSpec &ScopeSpec,
724 const DeclarationNameInfo &Id) {
725 LookupResult Lookup(*this, Id, LookupOrdinaryName);
726 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
727
728 if (Lookup.isAmbiguous())
729 return ExprError();
730
731 VarDecl *VD;
732 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000733 if (TypoCorrection Corrected = CorrectTypo(
734 Id, LookupOrdinaryName, CurScope, nullptr,
735 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000736 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000737 PDiag(Lookup.empty()
738 ? diag::err_undeclared_var_use_suggest
739 : diag::err_omp_expected_var_arg_suggest)
740 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +0000741 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000742 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000743 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
744 : diag::err_omp_expected_var_arg)
745 << Id.getName();
746 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000747 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000748 } else {
749 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000750 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000751 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
752 return ExprError();
753 }
754 }
755 Lookup.suppressDiagnostics();
756
757 // OpenMP [2.9.2, Syntax, C/C++]
758 // Variables must be file-scope, namespace-scope, or static block-scope.
759 if (!VD->hasGlobalStorage()) {
760 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000761 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
762 bool IsDecl =
763 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000764 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +0000765 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
766 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000767 return ExprError();
768 }
769
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000770 VarDecl *CanonicalVD = VD->getCanonicalDecl();
771 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000772 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
773 // A threadprivate directive for file-scope variables must appear outside
774 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000775 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
776 !getCurLexicalContext()->isTranslationUnit()) {
777 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000778 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
779 bool IsDecl =
780 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
781 Diag(VD->getLocation(),
782 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
783 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000784 return ExprError();
785 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000786 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
787 // A threadprivate directive for static class member variables must appear
788 // in the class definition, in the same scope in which the member
789 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000790 if (CanonicalVD->isStaticDataMember() &&
791 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
792 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000793 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
794 bool IsDecl =
795 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
796 Diag(VD->getLocation(),
797 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
798 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000799 return ExprError();
800 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000801 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
802 // A threadprivate directive for namespace-scope variables must appear
803 // outside any definition or declaration other than the namespace
804 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000805 if (CanonicalVD->getDeclContext()->isNamespace() &&
806 (!getCurLexicalContext()->isFileContext() ||
807 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
808 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000809 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
810 bool IsDecl =
811 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
812 Diag(VD->getLocation(),
813 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
814 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000815 return ExprError();
816 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000817 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
818 // A threadprivate directive for static block-scope variables must appear
819 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000820 if (CanonicalVD->isStaticLocal() && CurScope &&
821 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000822 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000823 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
824 bool IsDecl =
825 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
826 Diag(VD->getLocation(),
827 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
828 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000829 return ExprError();
830 }
831
832 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
833 // A threadprivate directive must lexically precede all references to any
834 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000835 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000836 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +0000837 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000838 return ExprError();
839 }
840
841 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +0000842 ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000843 return DE;
844}
845
Alexey Bataeved09d242014-05-28 05:53:51 +0000846Sema::DeclGroupPtrTy
847Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
848 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000849 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000850 CurContext->addDecl(D);
851 return DeclGroupPtrTy::make(DeclGroupRef(D));
852 }
853 return DeclGroupPtrTy();
854}
855
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000856namespace {
857class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
858 Sema &SemaRef;
859
860public:
861 bool VisitDeclRefExpr(const DeclRefExpr *E) {
862 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
863 if (VD->hasLocalStorage()) {
864 SemaRef.Diag(E->getLocStart(),
865 diag::err_omp_local_var_in_threadprivate_init)
866 << E->getSourceRange();
867 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
868 << VD << VD->getSourceRange();
869 return true;
870 }
871 }
872 return false;
873 }
874 bool VisitStmt(const Stmt *S) {
875 for (auto Child : S->children()) {
876 if (Child && Visit(Child))
877 return true;
878 }
879 return false;
880 }
Alexey Bataev23b69422014-06-18 07:08:49 +0000881 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000882};
883} // namespace
884
Alexey Bataeved09d242014-05-28 05:53:51 +0000885OMPThreadPrivateDecl *
886Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000887 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +0000888 for (auto &RefExpr : VarList) {
889 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000890 VarDecl *VD = cast<VarDecl>(DE->getDecl());
891 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +0000892
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000893 QualType QType = VD->getType();
894 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
895 // It will be analyzed later.
896 Vars.push_back(DE);
897 continue;
898 }
899
Alexey Bataeva769e072013-03-22 06:34:35 +0000900 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
901 // A threadprivate variable must not have an incomplete type.
902 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000903 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000904 continue;
905 }
906
907 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
908 // A threadprivate variable must not have a reference type.
909 if (VD->getType()->isReferenceType()) {
910 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000911 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
912 bool IsDecl =
913 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
914 Diag(VD->getLocation(),
915 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
916 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000917 continue;
918 }
919
Richard Smithfd3834f2013-04-13 02:43:54 +0000920 // Check if this is a TLS variable.
Alexey Bataev26a39242015-01-13 03:35:30 +0000921 if (VD->getTLSKind() != VarDecl::TLS_None ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +0000922 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
923 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +0000924 Diag(ILoc, diag::err_omp_var_thread_local)
925 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +0000926 bool IsDecl =
927 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
928 Diag(VD->getLocation(),
929 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
930 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000931 continue;
932 }
933
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000934 // Check if initial value of threadprivate variable reference variable with
935 // local storage (it is not supported by runtime).
936 if (auto Init = VD->getAnyInitializer()) {
937 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000938 if (Checker.Visit(Init))
939 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000940 }
941
Alexey Bataeved09d242014-05-28 05:53:51 +0000942 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +0000943 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +0000944 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
945 Context, SourceRange(Loc, Loc)));
946 if (auto *ML = Context.getASTMutationListener())
947 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +0000948 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000949 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000950 if (!Vars.empty()) {
951 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
952 Vars);
953 D->setAccess(AS_public);
954 }
955 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +0000956}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000957
Alexey Bataev7ff55242014-06-19 09:13:45 +0000958static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
959 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
960 bool IsLoopIterVar = false) {
961 if (DVar.RefExpr) {
962 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
963 << getOpenMPClauseName(DVar.CKind);
964 return;
965 }
966 enum {
967 PDSA_StaticMemberShared,
968 PDSA_StaticLocalVarShared,
969 PDSA_LoopIterVarPrivate,
970 PDSA_LoopIterVarLinear,
971 PDSA_LoopIterVarLastprivate,
972 PDSA_ConstVarShared,
973 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000974 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000975 PDSA_LocalVarPrivate,
976 PDSA_Implicit
977 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000978 bool ReportHint = false;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000979 auto ReportLoc = VD->getLocation();
Alexey Bataev7ff55242014-06-19 09:13:45 +0000980 if (IsLoopIterVar) {
981 if (DVar.CKind == OMPC_private)
982 Reason = PDSA_LoopIterVarPrivate;
983 else if (DVar.CKind == OMPC_lastprivate)
984 Reason = PDSA_LoopIterVarLastprivate;
985 else
986 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000987 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
988 Reason = PDSA_TaskVarFirstprivate;
989 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000990 } else if (VD->isStaticLocal())
991 Reason = PDSA_StaticLocalVarShared;
992 else if (VD->isStaticDataMember())
993 Reason = PDSA_StaticMemberShared;
994 else if (VD->isFileVarDecl())
995 Reason = PDSA_GlobalVarShared;
996 else if (VD->getType().isConstant(SemaRef.getASTContext()))
997 Reason = PDSA_ConstVarShared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000998 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +0000999 ReportHint = true;
1000 Reason = PDSA_LocalVarPrivate;
1001 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001002 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001003 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001004 << Reason << ReportHint
1005 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1006 } else if (DVar.ImplicitDSALoc.isValid()) {
1007 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1008 << getOpenMPClauseName(DVar.CKind);
1009 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001010}
1011
Alexey Bataev758e55e2013-09-06 18:03:48 +00001012namespace {
1013class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1014 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001015 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001016 bool ErrorFound;
1017 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001018 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001019 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001020
Alexey Bataev758e55e2013-09-06 18:03:48 +00001021public:
1022 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001023 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001024 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001025 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1026 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001027
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001028 auto DVar = Stack->getTopDSA(VD, false);
1029 // Check if the variable has explicit DSA set and stop analysis if it so.
1030 if (DVar.RefExpr) return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001031
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001032 auto ELoc = E->getExprLoc();
1033 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001034 // The default(none) clause requires that each variable that is referenced
1035 // in the construct, and does not have a predetermined data-sharing
1036 // attribute, must have its data-sharing attribute explicitly determined
1037 // by being listed in a data-sharing attribute clause.
1038 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001039 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001040 VarsWithInheritedDSA.count(VD) == 0) {
1041 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001042 return;
1043 }
1044
1045 // OpenMP [2.9.3.6, Restrictions, p.2]
1046 // A list item that appears in a reduction clause of the innermost
1047 // enclosing worksharing or parallel construct may not be accessed in an
1048 // explicit task.
Alexey Bataevf29276e2014-06-18 04:14:57 +00001049 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001050 [](OpenMPDirectiveKind K) -> bool {
1051 return isOpenMPParallelDirective(K) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001052 isOpenMPWorksharingDirective(K) ||
1053 isOpenMPTeamsDirective(K);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001054 },
1055 false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001056 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1057 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001058 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1059 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001060 return;
1061 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001062
1063 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001064 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001065 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001066 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001067 }
1068 }
1069 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001070 for (auto *C : S->clauses()) {
1071 // Skip analysis of arguments of implicitly defined firstprivate clause
1072 // for task directives.
1073 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1074 for (auto *CC : C->children()) {
1075 if (CC)
1076 Visit(CC);
1077 }
1078 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001079 }
1080 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001081 for (auto *C : S->children()) {
1082 if (C && !isa<OMPExecutableDirective>(C))
1083 Visit(C);
1084 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001085 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001086
1087 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001088 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001089 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1090 return VarsWithInheritedDSA;
1091 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001092
Alexey Bataev7ff55242014-06-19 09:13:45 +00001093 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1094 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001095};
Alexey Bataeved09d242014-05-28 05:53:51 +00001096} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001097
Alexey Bataevbae9a792014-06-27 10:37:06 +00001098void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001099 switch (DKind) {
1100 case OMPD_parallel: {
1101 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1102 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001103 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001104 std::make_pair(".global_tid.", KmpInt32PtrTy),
1105 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1106 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001107 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001108 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1109 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001110 break;
1111 }
1112 case OMPD_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001113 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001114 std::make_pair(StringRef(), QualType()) // __context with shared vars
1115 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001116 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1117 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001118 break;
1119 }
1120 case OMPD_for: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001121 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001122 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001123 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001124 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1125 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001126 break;
1127 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001128 case OMPD_for_simd: {
1129 Sema::CapturedParamNameType Params[] = {
1130 std::make_pair(StringRef(), QualType()) // __context with shared vars
1131 };
1132 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1133 Params);
1134 break;
1135 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001136 case OMPD_sections: {
1137 Sema::CapturedParamNameType Params[] = {
1138 std::make_pair(StringRef(), QualType()) // __context with shared vars
1139 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001140 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1141 Params);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001142 break;
1143 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001144 case OMPD_section: {
1145 Sema::CapturedParamNameType Params[] = {
1146 std::make_pair(StringRef(), QualType()) // __context with shared vars
1147 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001148 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1149 Params);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001150 break;
1151 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001152 case OMPD_single: {
1153 Sema::CapturedParamNameType Params[] = {
1154 std::make_pair(StringRef(), QualType()) // __context with shared vars
1155 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001156 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1157 Params);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001158 break;
1159 }
Alexander Musman80c22892014-07-17 08:54:58 +00001160 case OMPD_master: {
1161 Sema::CapturedParamNameType Params[] = {
1162 std::make_pair(StringRef(), QualType()) // __context with shared vars
1163 };
1164 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1165 Params);
1166 break;
1167 }
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001168 case OMPD_critical: {
1169 Sema::CapturedParamNameType Params[] = {
1170 std::make_pair(StringRef(), QualType()) // __context with shared vars
1171 };
1172 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1173 Params);
1174 break;
1175 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001176 case OMPD_parallel_for: {
1177 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1178 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1179 Sema::CapturedParamNameType Params[] = {
1180 std::make_pair(".global_tid.", KmpInt32PtrTy),
1181 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1182 std::make_pair(StringRef(), QualType()) // __context with shared vars
1183 };
1184 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1185 Params);
1186 break;
1187 }
Alexander Musmane4e893b2014-09-23 09:33:00 +00001188 case OMPD_parallel_for_simd: {
1189 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1190 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1191 Sema::CapturedParamNameType Params[] = {
1192 std::make_pair(".global_tid.", KmpInt32PtrTy),
1193 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1194 std::make_pair(StringRef(), QualType()) // __context with shared vars
1195 };
1196 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1197 Params);
1198 break;
1199 }
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001200 case OMPD_parallel_sections: {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001201 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1202 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001203 Sema::CapturedParamNameType Params[] = {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001204 std::make_pair(".global_tid.", KmpInt32PtrTy),
1205 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001206 std::make_pair(StringRef(), QualType()) // __context with shared vars
1207 };
1208 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1209 Params);
1210 break;
1211 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001212 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001213 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001214 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1215 FunctionProtoType::ExtProtoInfo EPI;
1216 EPI.Variadic = true;
1217 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001218 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001219 std::make_pair(".global_tid.", KmpInt32Ty),
1220 std::make_pair(".part_id.", KmpInt32Ty),
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001221 std::make_pair(".privates.",
1222 Context.VoidPtrTy.withConst().withRestrict()),
1223 std::make_pair(
1224 ".copy_fn.",
1225 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001226 std::make_pair(StringRef(), QualType()) // __context with shared vars
1227 };
1228 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1229 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001230 // Mark this captured region as inlined, because we don't use outlined
1231 // function directly.
1232 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1233 AlwaysInlineAttr::CreateImplicit(
1234 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001235 break;
1236 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001237 case OMPD_ordered: {
1238 Sema::CapturedParamNameType Params[] = {
1239 std::make_pair(StringRef(), QualType()) // __context with shared vars
1240 };
1241 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1242 Params);
1243 break;
1244 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001245 case OMPD_atomic: {
1246 Sema::CapturedParamNameType Params[] = {
1247 std::make_pair(StringRef(), QualType()) // __context with shared vars
1248 };
1249 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1250 Params);
1251 break;
1252 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001253 case OMPD_target: {
1254 Sema::CapturedParamNameType Params[] = {
1255 std::make_pair(StringRef(), QualType()) // __context with shared vars
1256 };
1257 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1258 Params);
1259 break;
1260 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001261 case OMPD_teams: {
1262 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1263 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1264 Sema::CapturedParamNameType Params[] = {
1265 std::make_pair(".global_tid.", KmpInt32PtrTy),
1266 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1267 std::make_pair(StringRef(), QualType()) // __context with shared vars
1268 };
1269 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1270 Params);
1271 break;
1272 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001273 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001274 case OMPD_taskyield:
1275 case OMPD_barrier:
1276 case OMPD_taskwait:
1277 case OMPD_flush:
Alexey Bataev9959db52014-05-06 10:08:46 +00001278 llvm_unreachable("OpenMP Directive is not allowed");
1279 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001280 llvm_unreachable("Unknown OpenMP directive");
1281 }
1282}
1283
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001284StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1285 ArrayRef<OMPClause *> Clauses) {
1286 if (!S.isUsable()) {
1287 ActOnCapturedRegionError();
1288 return StmtError();
1289 }
Alexey Bataev040d5402015-05-12 08:35:28 +00001290 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001291 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001292 if (isOpenMPPrivate(Clause->getClauseKind()) ||
1293 Clause->getClauseKind() == OMPC_copyprivate) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001294 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001295 for (auto *VarRef : Clause->children()) {
1296 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001297 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001298 }
1299 }
Alexey Bataev040d5402015-05-12 08:35:28 +00001300 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
1301 Clause->getClauseKind() == OMPC_schedule) {
1302 // Mark all variables in private list clauses as used in inner region.
1303 // Required for proper codegen of combined directives.
1304 // TODO: add processing for other clauses.
1305 if (auto *E = cast_or_null<Expr>(
1306 cast<OMPScheduleClause>(Clause)->getHelperChunkSize())) {
1307 MarkDeclarationsReferencedInExpr(E);
1308 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001309 }
1310 }
1311 return ActOnCapturedRegionEnd(S.get());
1312}
1313
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001314static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1315 OpenMPDirectiveKind CurrentRegion,
1316 const DeclarationNameInfo &CurrentName,
1317 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001318 // Allowed nesting of constructs
1319 // +------------------+-----------------+------------------------------------+
1320 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1321 // +------------------+-----------------+------------------------------------+
1322 // | parallel | parallel | * |
1323 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001324 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001325 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001326 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001327 // | parallel | simd | * |
1328 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001329 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001330 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001331 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001332 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001333 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001334 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001335 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001336 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001337 // | parallel | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001338 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001339 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001340 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001341 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001342 // | parallel | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001343 // +------------------+-----------------+------------------------------------+
1344 // | for | parallel | * |
1345 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001346 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001347 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001348 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001349 // | for | simd | * |
1350 // | for | sections | + |
1351 // | for | section | + |
1352 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001353 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001354 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001355 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001356 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001357 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001358 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001359 // | for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001360 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001361 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001362 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001363 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001364 // | for | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001365 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001366 // | master | parallel | * |
1367 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001368 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001369 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001370 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001371 // | master | simd | * |
1372 // | master | sections | + |
1373 // | master | section | + |
1374 // | master | single | + |
1375 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001376 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001377 // | master |parallel sections| * |
1378 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001379 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001380 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001381 // | master | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001382 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001383 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001384 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001385 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001386 // | master | teams | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001387 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001388 // | critical | parallel | * |
1389 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001390 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001391 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001392 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001393 // | critical | simd | * |
1394 // | critical | sections | + |
1395 // | critical | section | + |
1396 // | critical | single | + |
1397 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001398 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001399 // | critical |parallel sections| * |
1400 // | critical | task | * |
1401 // | critical | taskyield | * |
1402 // | critical | barrier | + |
1403 // | critical | taskwait | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001404 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001405 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001406 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001407 // | critical | teams | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001408 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001409 // | simd | parallel | |
1410 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001411 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001412 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001413 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001414 // | simd | simd | |
1415 // | simd | sections | |
1416 // | simd | section | |
1417 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001418 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001419 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001420 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001421 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001422 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001423 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001424 // | simd | taskwait | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001425 // | simd | flush | |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001426 // | simd | ordered | |
Alexey Bataev0162e452014-07-22 10:10:35 +00001427 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001428 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001429 // | simd | teams | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001430 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001431 // | for simd | parallel | |
1432 // | for simd | for | |
1433 // | for simd | for simd | |
1434 // | for simd | master | |
1435 // | for simd | critical | |
1436 // | for simd | simd | |
1437 // | for simd | sections | |
1438 // | for simd | section | |
1439 // | for simd | single | |
1440 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001441 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001442 // | for simd |parallel sections| |
1443 // | for simd | task | |
1444 // | for simd | taskyield | |
1445 // | for simd | barrier | |
1446 // | for simd | taskwait | |
1447 // | for simd | flush | |
1448 // | for simd | ordered | |
1449 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001450 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001451 // | for simd | teams | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001452 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001453 // | parallel for simd| parallel | |
1454 // | parallel for simd| for | |
1455 // | parallel for simd| for simd | |
1456 // | parallel for simd| master | |
1457 // | parallel for simd| critical | |
1458 // | parallel for simd| simd | |
1459 // | parallel for simd| sections | |
1460 // | parallel for simd| section | |
1461 // | parallel for simd| single | |
1462 // | parallel for simd| parallel for | |
1463 // | parallel for simd|parallel for simd| |
1464 // | parallel for simd|parallel sections| |
1465 // | parallel for simd| task | |
1466 // | parallel for simd| taskyield | |
1467 // | parallel for simd| barrier | |
1468 // | parallel for simd| taskwait | |
1469 // | parallel for simd| flush | |
1470 // | parallel for simd| ordered | |
1471 // | parallel for simd| atomic | |
1472 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001473 // | parallel for simd| teams | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001474 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001475 // | sections | parallel | * |
1476 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001477 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001478 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001479 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001480 // | sections | simd | * |
1481 // | sections | sections | + |
1482 // | sections | section | * |
1483 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001484 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001485 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001486 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001487 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001488 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001489 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001490 // | sections | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001491 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001492 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001493 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001494 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001495 // | sections | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001496 // +------------------+-----------------+------------------------------------+
1497 // | section | parallel | * |
1498 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001499 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001500 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001501 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001502 // | section | simd | * |
1503 // | section | sections | + |
1504 // | section | section | + |
1505 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001506 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001507 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001508 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001509 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001510 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001511 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001512 // | section | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001513 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001514 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001515 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001516 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001517 // | section | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001518 // +------------------+-----------------+------------------------------------+
1519 // | single | parallel | * |
1520 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001521 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001522 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001523 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001524 // | single | simd | * |
1525 // | single | sections | + |
1526 // | single | section | + |
1527 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001528 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001529 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001530 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001531 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001532 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001533 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001534 // | single | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001535 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001536 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001537 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001538 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001539 // | single | teams | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001540 // +------------------+-----------------+------------------------------------+
1541 // | parallel for | parallel | * |
1542 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001543 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001544 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001545 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001546 // | parallel for | simd | * |
1547 // | parallel for | sections | + |
1548 // | parallel for | section | + |
1549 // | parallel for | single | + |
1550 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001551 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001552 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001553 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001554 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001555 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001556 // | parallel for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001557 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001558 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001559 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001560 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001561 // | parallel for | teams | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001562 // +------------------+-----------------+------------------------------------+
1563 // | parallel sections| parallel | * |
1564 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001565 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001566 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001567 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001568 // | parallel sections| simd | * |
1569 // | parallel sections| sections | + |
1570 // | parallel sections| section | * |
1571 // | parallel sections| single | + |
1572 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001573 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001574 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001575 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001576 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001577 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001578 // | parallel sections| taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001579 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001580 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001581 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001582 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001583 // | parallel sections| teams | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001584 // +------------------+-----------------+------------------------------------+
1585 // | task | parallel | * |
1586 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001587 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001588 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001589 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001590 // | task | simd | * |
1591 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001592 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001593 // | task | single | + |
1594 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001595 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001596 // | task |parallel sections| * |
1597 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001598 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001599 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001600 // | task | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001601 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001602 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001603 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001604 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001605 // | task | teams | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001606 // +------------------+-----------------+------------------------------------+
1607 // | ordered | parallel | * |
1608 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001609 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001610 // | ordered | master | * |
1611 // | ordered | critical | * |
1612 // | ordered | simd | * |
1613 // | ordered | sections | + |
1614 // | ordered | section | + |
1615 // | ordered | single | + |
1616 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001617 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001618 // | ordered |parallel sections| * |
1619 // | ordered | task | * |
1620 // | ordered | taskyield | * |
1621 // | ordered | barrier | + |
1622 // | ordered | taskwait | * |
1623 // | ordered | flush | * |
1624 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001625 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001626 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001627 // | ordered | teams | + |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001628 // +------------------+-----------------+------------------------------------+
1629 // | atomic | parallel | |
1630 // | atomic | for | |
1631 // | atomic | for simd | |
1632 // | atomic | master | |
1633 // | atomic | critical | |
1634 // | atomic | simd | |
1635 // | atomic | sections | |
1636 // | atomic | section | |
1637 // | atomic | single | |
1638 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001639 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001640 // | atomic |parallel sections| |
1641 // | atomic | task | |
1642 // | atomic | taskyield | |
1643 // | atomic | barrier | |
1644 // | atomic | taskwait | |
1645 // | atomic | flush | |
1646 // | atomic | ordered | |
1647 // | atomic | atomic | |
1648 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001649 // | atomic | teams | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001650 // +------------------+-----------------+------------------------------------+
1651 // | target | parallel | * |
1652 // | target | for | * |
1653 // | target | for simd | * |
1654 // | target | master | * |
1655 // | target | critical | * |
1656 // | target | simd | * |
1657 // | target | sections | * |
1658 // | target | section | * |
1659 // | target | single | * |
1660 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001661 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001662 // | target |parallel sections| * |
1663 // | target | task | * |
1664 // | target | taskyield | * |
1665 // | target | barrier | * |
1666 // | target | taskwait | * |
1667 // | target | flush | * |
1668 // | target | ordered | * |
1669 // | target | atomic | * |
1670 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001671 // | target | teams | * |
1672 // +------------------+-----------------+------------------------------------+
1673 // | teams | parallel | * |
1674 // | teams | for | + |
1675 // | teams | for simd | + |
1676 // | teams | master | + |
1677 // | teams | critical | + |
1678 // | teams | simd | + |
1679 // | teams | sections | + |
1680 // | teams | section | + |
1681 // | teams | single | + |
1682 // | teams | parallel for | * |
1683 // | teams |parallel for simd| * |
1684 // | teams |parallel sections| * |
1685 // | teams | task | + |
1686 // | teams | taskyield | + |
1687 // | teams | barrier | + |
1688 // | teams | taskwait | + |
1689 // | teams | flush | + |
1690 // | teams | ordered | + |
1691 // | teams | atomic | + |
1692 // | teams | target | + |
1693 // | teams | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001694 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00001695 if (Stack->getCurScope()) {
1696 auto ParentRegion = Stack->getParentDirective();
1697 bool NestingProhibited = false;
1698 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001699 enum {
1700 NoRecommend,
1701 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001702 ShouldBeInOrderedRegion,
1703 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001704 } Recommend = NoRecommend;
Alexey Bataev549210e2014-06-24 04:39:47 +00001705 if (isOpenMPSimdDirective(ParentRegion)) {
1706 // OpenMP [2.16, Nesting of Regions]
1707 // OpenMP constructs may not be nested inside a simd region.
1708 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1709 return true;
1710 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001711 if (ParentRegion == OMPD_atomic) {
1712 // OpenMP [2.16, Nesting of Regions]
1713 // OpenMP constructs may not be nested inside an atomic region.
1714 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1715 return true;
1716 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001717 if (CurrentRegion == OMPD_section) {
1718 // OpenMP [2.7.2, sections Construct, Restrictions]
1719 // Orphaned section directives are prohibited. That is, the section
1720 // directives must appear within the sections construct and must not be
1721 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001722 if (ParentRegion != OMPD_sections &&
1723 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001724 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1725 << (ParentRegion != OMPD_unknown)
1726 << getOpenMPDirectiveName(ParentRegion);
1727 return true;
1728 }
1729 return false;
1730 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001731 // Allow some constructs to be orphaned (they could be used in functions,
1732 // called from OpenMP regions with the required preconditions).
1733 if (ParentRegion == OMPD_unknown)
1734 return false;
Alexander Musman80c22892014-07-17 08:54:58 +00001735 if (CurrentRegion == OMPD_master) {
1736 // OpenMP [2.16, Nesting of Regions]
1737 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001738 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001739 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1740 ParentRegion == OMPD_task;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001741 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1742 // OpenMP [2.16, Nesting of Regions]
1743 // A critical region may not be nested (closely or otherwise) inside a
1744 // critical region with the same name. Note that this restriction is not
1745 // sufficient to prevent deadlock.
1746 SourceLocation PreviousCriticalLoc;
1747 bool DeadLock =
1748 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1749 OpenMPDirectiveKind K,
1750 const DeclarationNameInfo &DNI,
1751 SourceLocation Loc)
1752 ->bool {
1753 if (K == OMPD_critical &&
1754 DNI.getName() == CurrentName.getName()) {
1755 PreviousCriticalLoc = Loc;
1756 return true;
1757 } else
1758 return false;
1759 },
1760 false /* skip top directive */);
1761 if (DeadLock) {
1762 SemaRef.Diag(StartLoc,
1763 diag::err_omp_prohibited_region_critical_same_name)
1764 << CurrentName.getName();
1765 if (PreviousCriticalLoc.isValid())
1766 SemaRef.Diag(PreviousCriticalLoc,
1767 diag::note_omp_previous_critical_region);
1768 return true;
1769 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001770 } else if (CurrentRegion == OMPD_barrier) {
1771 // OpenMP [2.16, Nesting of Regions]
1772 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001773 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001774 NestingProhibited =
1775 isOpenMPWorksharingDirective(ParentRegion) ||
1776 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1777 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001778 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00001779 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001780 // OpenMP [2.16, Nesting of Regions]
1781 // A worksharing region may not be closely nested inside a worksharing,
1782 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001783 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00001784 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001785 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1786 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1787 Recommend = ShouldBeInParallelRegion;
1788 } else if (CurrentRegion == OMPD_ordered) {
1789 // OpenMP [2.16, Nesting of Regions]
1790 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00001791 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001792 // An ordered region must be closely nested inside a loop region (or
1793 // parallel loop region) with an ordered clause.
1794 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00001795 ParentRegion == OMPD_task ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001796 !Stack->isParentOrderedRegion();
1797 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001798 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1799 // OpenMP [2.16, Nesting of Regions]
1800 // If specified, a teams construct must be contained within a target
1801 // construct.
1802 NestingProhibited = ParentRegion != OMPD_target;
1803 Recommend = ShouldBeInTargetRegion;
1804 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1805 }
1806 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1807 // OpenMP [2.16, Nesting of Regions]
1808 // distribute, parallel, parallel sections, parallel workshare, and the
1809 // parallel loop and parallel loop SIMD constructs are the only OpenMP
1810 // constructs that can be closely nested in the teams region.
1811 // TODO: add distribute directive.
1812 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1813 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001814 }
1815 if (NestingProhibited) {
1816 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001817 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1818 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00001819 return true;
1820 }
1821 }
1822 return false;
1823}
1824
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001825StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001826 const DeclarationNameInfo &DirName,
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001827 ArrayRef<OMPClause *> Clauses,
1828 Stmt *AStmt,
1829 SourceLocation StartLoc,
1830 SourceLocation EndLoc) {
1831 StmtResult Res = StmtError();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001832 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00001833 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001834
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001835 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00001836 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001837 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00001838 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00001839 if (AStmt) {
1840 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1841
1842 // Check default data sharing attributes for referenced variables.
1843 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1844 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1845 if (DSAChecker.isErrorFound())
1846 return StmtError();
1847 // Generate list of implicitly defined firstprivate variables.
1848 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00001849
1850 if (!DSAChecker.getImplicitFirstprivate().empty()) {
1851 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1852 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1853 SourceLocation(), SourceLocation())) {
1854 ClausesWithImplicit.push_back(Implicit);
1855 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1856 DSAChecker.getImplicitFirstprivate().size();
1857 } else
1858 ErrorFound = true;
1859 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001860 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001861
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001862 switch (Kind) {
1863 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00001864 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1865 EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001866 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001867 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001868 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1869 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001870 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00001871 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001872 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1873 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001874 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00001875 case OMPD_for_simd:
1876 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
1877 EndLoc, VarsWithInheritedDSA);
1878 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001879 case OMPD_sections:
1880 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1881 EndLoc);
1882 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001883 case OMPD_section:
1884 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00001885 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001886 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1887 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001888 case OMPD_single:
1889 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1890 EndLoc);
1891 break;
Alexander Musman80c22892014-07-17 08:54:58 +00001892 case OMPD_master:
1893 assert(ClausesWithImplicit.empty() &&
1894 "No clauses are allowed for 'omp master' directive");
1895 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1896 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001897 case OMPD_critical:
1898 assert(ClausesWithImplicit.empty() &&
1899 "No clauses are allowed for 'omp critical' directive");
1900 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1901 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001902 case OMPD_parallel_for:
1903 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1904 EndLoc, VarsWithInheritedDSA);
1905 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00001906 case OMPD_parallel_for_simd:
1907 Res = ActOnOpenMPParallelForSimdDirective(
1908 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
1909 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001910 case OMPD_parallel_sections:
1911 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1912 StartLoc, EndLoc);
1913 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001914 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001915 Res =
1916 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1917 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00001918 case OMPD_taskyield:
1919 assert(ClausesWithImplicit.empty() &&
1920 "No clauses are allowed for 'omp taskyield' directive");
1921 assert(AStmt == nullptr &&
1922 "No associated statement allowed for 'omp taskyield' directive");
1923 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1924 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001925 case OMPD_barrier:
1926 assert(ClausesWithImplicit.empty() &&
1927 "No clauses are allowed for 'omp barrier' directive");
1928 assert(AStmt == nullptr &&
1929 "No associated statement allowed for 'omp barrier' directive");
1930 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1931 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00001932 case OMPD_taskwait:
1933 assert(ClausesWithImplicit.empty() &&
1934 "No clauses are allowed for 'omp taskwait' directive");
1935 assert(AStmt == nullptr &&
1936 "No associated statement allowed for 'omp taskwait' directive");
1937 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1938 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00001939 case OMPD_flush:
1940 assert(AStmt == nullptr &&
1941 "No associated statement allowed for 'omp flush' directive");
1942 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
1943 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001944 case OMPD_ordered:
1945 assert(ClausesWithImplicit.empty() &&
1946 "No clauses are allowed for 'omp ordered' directive");
1947 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
1948 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00001949 case OMPD_atomic:
1950 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
1951 EndLoc);
1952 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001953 case OMPD_teams:
1954 Res =
1955 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1956 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001957 case OMPD_target:
1958 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
1959 EndLoc);
1960 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001961 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001962 llvm_unreachable("OpenMP Directive is not allowed");
1963 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001964 llvm_unreachable("Unknown OpenMP directive");
1965 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001966
Alexey Bataev4acb8592014-07-07 13:01:15 +00001967 for (auto P : VarsWithInheritedDSA) {
1968 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1969 << P.first << P.second->getSourceRange();
1970 }
1971 if (!VarsWithInheritedDSA.empty())
1972 return StmtError();
1973
Alexey Bataeved09d242014-05-28 05:53:51 +00001974 if (ErrorFound)
1975 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001976 return Res;
1977}
1978
1979StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
1980 Stmt *AStmt,
1981 SourceLocation StartLoc,
1982 SourceLocation EndLoc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001983 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
1984 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
1985 // 1.2.2 OpenMP Language Terminology
1986 // Structured block - An executable statement with a single entry at the
1987 // top and a single exit at the bottom.
1988 // The point of exit cannot be a branch out of the structured block.
1989 // longjmp() and throw() must not violate the entry/exit criteria.
1990 CS->getCapturedDecl()->setNothrow();
1991
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001992 getCurFunction()->setHasBranchProtectedScope();
1993
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001994 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
1995 AStmt);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001996}
1997
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001998namespace {
1999/// \brief Helper class for checking canonical form of the OpenMP loops and
2000/// extracting iteration space of each loop in the loop nest, that will be used
2001/// for IR generation.
2002class OpenMPIterationSpaceChecker {
2003 /// \brief Reference to Sema.
2004 Sema &SemaRef;
2005 /// \brief A location for diagnostics (when there is no some better location).
2006 SourceLocation DefaultLoc;
2007 /// \brief A location for diagnostics (when increment is not compatible).
2008 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002009 /// \brief A source location for referring to loop init later.
2010 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002011 /// \brief A source location for referring to condition later.
2012 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002013 /// \brief A source location for referring to increment later.
2014 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002015 /// \brief Loop variable.
2016 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002017 /// \brief Reference to loop variable.
2018 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002019 /// \brief Lower bound (initializer for the var).
2020 Expr *LB;
2021 /// \brief Upper bound.
2022 Expr *UB;
2023 /// \brief Loop step (increment).
2024 Expr *Step;
2025 /// \brief This flag is true when condition is one of:
2026 /// Var < UB
2027 /// Var <= UB
2028 /// UB > Var
2029 /// UB >= Var
2030 bool TestIsLessOp;
2031 /// \brief This flag is true when condition is strict ( < or > ).
2032 bool TestIsStrictOp;
2033 /// \brief This flag is true when step is subtracted on each iteration.
2034 bool SubtractStep;
2035
2036public:
2037 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2038 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00002039 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
2040 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002041 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
2042 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002043 /// \brief Check init-expr for canonical loop form and save loop counter
2044 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002045 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002046 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2047 /// for less/greater and for strict/non-strict comparison.
2048 bool CheckCond(Expr *S);
2049 /// \brief Check incr-expr for canonical loop form and return true if it
2050 /// does not conform, otherwise save loop step (#Step).
2051 bool CheckInc(Expr *S);
2052 /// \brief Return the loop counter variable.
2053 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002054 /// \brief Return the reference expression to loop counter variable.
2055 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002056 /// \brief Source range of the loop init.
2057 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2058 /// \brief Source range of the loop condition.
2059 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2060 /// \brief Source range of the loop increment.
2061 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2062 /// \brief True if the step should be subtracted.
2063 bool ShouldSubtractStep() const { return SubtractStep; }
2064 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002065 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002066 /// \brief Build the precondition expression for the loops.
2067 Expr *BuildPreCond(Scope *S, Expr *Cond) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002068 /// \brief Build reference expression to the counter be used for codegen.
2069 Expr *BuildCounterVar() const;
2070 /// \brief Build initization of the counter be used for codegen.
2071 Expr *BuildCounterInit() const;
2072 /// \brief Build step of the counter be used for codegen.
2073 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002074 /// \brief Return true if any expression is dependent.
2075 bool Dependent() const;
2076
2077private:
2078 /// \brief Check the right-hand side of an assignment in the increment
2079 /// expression.
2080 bool CheckIncRHS(Expr *RHS);
2081 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002082 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002083 /// \brief Helper to set upper bound.
2084 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
2085 const SourceLocation &SL);
2086 /// \brief Helper to set loop increment.
2087 bool SetStep(Expr *NewStep, bool Subtract);
2088};
2089
2090bool OpenMPIterationSpaceChecker::Dependent() const {
2091 if (!Var) {
2092 assert(!LB && !UB && !Step);
2093 return false;
2094 }
2095 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2096 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2097}
2098
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002099bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2100 DeclRefExpr *NewVarRefExpr,
2101 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002102 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002103 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2104 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002105 if (!NewVar || !NewLB)
2106 return true;
2107 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002108 VarRef = NewVarRefExpr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002109 LB = NewLB;
2110 return false;
2111}
2112
2113bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2114 const SourceRange &SR,
2115 const SourceLocation &SL) {
2116 // State consistency checking to ensure correct usage.
2117 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2118 !TestIsLessOp && !TestIsStrictOp);
2119 if (!NewUB)
2120 return true;
2121 UB = NewUB;
2122 TestIsLessOp = LessOp;
2123 TestIsStrictOp = StrictOp;
2124 ConditionSrcRange = SR;
2125 ConditionLoc = SL;
2126 return false;
2127}
2128
2129bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2130 // State consistency checking to ensure correct usage.
2131 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2132 if (!NewStep)
2133 return true;
2134 if (!NewStep->isValueDependent()) {
2135 // Check that the step is integer expression.
2136 SourceLocation StepLoc = NewStep->getLocStart();
2137 ExprResult Val =
2138 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2139 if (Val.isInvalid())
2140 return true;
2141 NewStep = Val.get();
2142
2143 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2144 // If test-expr is of form var relational-op b and relational-op is < or
2145 // <= then incr-expr must cause var to increase on each iteration of the
2146 // loop. If test-expr is of form var relational-op b and relational-op is
2147 // > or >= then incr-expr must cause var to decrease on each iteration of
2148 // the loop.
2149 // If test-expr is of form b relational-op var and relational-op is < or
2150 // <= then incr-expr must cause var to decrease on each iteration of the
2151 // loop. If test-expr is of form b relational-op var and relational-op is
2152 // > or >= then incr-expr must cause var to increase on each iteration of
2153 // the loop.
2154 llvm::APSInt Result;
2155 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2156 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2157 bool IsConstNeg =
2158 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002159 bool IsConstPos =
2160 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002161 bool IsConstZero = IsConstant && !Result.getBoolValue();
2162 if (UB && (IsConstZero ||
2163 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002164 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002165 SemaRef.Diag(NewStep->getExprLoc(),
2166 diag::err_omp_loop_incr_not_compatible)
2167 << Var << TestIsLessOp << NewStep->getSourceRange();
2168 SemaRef.Diag(ConditionLoc,
2169 diag::note_omp_loop_cond_requres_compatible_incr)
2170 << TestIsLessOp << ConditionSrcRange;
2171 return true;
2172 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002173 if (TestIsLessOp == Subtract) {
2174 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2175 NewStep).get();
2176 Subtract = !Subtract;
2177 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002178 }
2179
2180 Step = NewStep;
2181 SubtractStep = Subtract;
2182 return false;
2183}
2184
Alexey Bataev9c821032015-04-30 04:23:23 +00002185bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002186 // Check init-expr for canonical loop form and save loop counter
2187 // variable - #Var and its initialization value - #LB.
2188 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2189 // var = lb
2190 // integer-type var = lb
2191 // random-access-iterator-type var = lb
2192 // pointer-type var = lb
2193 //
2194 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002195 if (EmitDiags) {
2196 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2197 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002198 return true;
2199 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002200 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002201 if (Expr *E = dyn_cast<Expr>(S))
2202 S = E->IgnoreParens();
2203 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2204 if (BO->getOpcode() == BO_Assign)
2205 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002206 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002207 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002208 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2209 if (DS->isSingleDecl()) {
2210 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2211 if (Var->hasInit()) {
2212 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002213 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002214 SemaRef.Diag(S->getLocStart(),
2215 diag::ext_omp_loop_not_canonical_init)
2216 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002217 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002218 }
2219 }
2220 }
2221 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2222 if (CE->getOperator() == OO_Equal)
2223 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002224 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2225 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002226
Alexey Bataev9c821032015-04-30 04:23:23 +00002227 if (EmitDiags) {
2228 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2229 << S->getSourceRange();
2230 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002231 return true;
2232}
2233
Alexey Bataev23b69422014-06-18 07:08:49 +00002234/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002235/// variable (which may be the loop variable) if possible.
2236static const VarDecl *GetInitVarDecl(const Expr *E) {
2237 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002238 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002239 E = E->IgnoreParenImpCasts();
2240 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2241 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2242 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
2243 CE->getArg(0) != nullptr)
2244 E = CE->getArg(0)->IgnoreParenImpCasts();
2245 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2246 if (!DRE)
2247 return nullptr;
2248 return dyn_cast<VarDecl>(DRE->getDecl());
2249}
2250
2251bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2252 // Check test-expr for canonical form, save upper-bound UB, flags for
2253 // less/greater and for strict/non-strict comparison.
2254 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2255 // var relational-op b
2256 // b relational-op var
2257 //
2258 if (!S) {
2259 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2260 return true;
2261 }
2262 S = S->IgnoreParenImpCasts();
2263 SourceLocation CondLoc = S->getLocStart();
2264 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2265 if (BO->isRelationalOp()) {
2266 if (GetInitVarDecl(BO->getLHS()) == Var)
2267 return SetUB(BO->getRHS(),
2268 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2269 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2270 BO->getSourceRange(), BO->getOperatorLoc());
2271 if (GetInitVarDecl(BO->getRHS()) == Var)
2272 return SetUB(BO->getLHS(),
2273 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2274 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2275 BO->getSourceRange(), BO->getOperatorLoc());
2276 }
2277 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2278 if (CE->getNumArgs() == 2) {
2279 auto Op = CE->getOperator();
2280 switch (Op) {
2281 case OO_Greater:
2282 case OO_GreaterEqual:
2283 case OO_Less:
2284 case OO_LessEqual:
2285 if (GetInitVarDecl(CE->getArg(0)) == Var)
2286 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2287 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2288 CE->getOperatorLoc());
2289 if (GetInitVarDecl(CE->getArg(1)) == Var)
2290 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2291 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2292 CE->getOperatorLoc());
2293 break;
2294 default:
2295 break;
2296 }
2297 }
2298 }
2299 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2300 << S->getSourceRange() << Var;
2301 return true;
2302}
2303
2304bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2305 // RHS of canonical loop form increment can be:
2306 // var + incr
2307 // incr + var
2308 // var - incr
2309 //
2310 RHS = RHS->IgnoreParenImpCasts();
2311 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2312 if (BO->isAdditiveOp()) {
2313 bool IsAdd = BO->getOpcode() == BO_Add;
2314 if (GetInitVarDecl(BO->getLHS()) == Var)
2315 return SetStep(BO->getRHS(), !IsAdd);
2316 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2317 return SetStep(BO->getLHS(), false);
2318 }
2319 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2320 bool IsAdd = CE->getOperator() == OO_Plus;
2321 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2322 if (GetInitVarDecl(CE->getArg(0)) == Var)
2323 return SetStep(CE->getArg(1), !IsAdd);
2324 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2325 return SetStep(CE->getArg(0), false);
2326 }
2327 }
2328 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2329 << RHS->getSourceRange() << Var;
2330 return true;
2331}
2332
2333bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2334 // Check incr-expr for canonical loop form and return true if it
2335 // does not conform.
2336 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2337 // ++var
2338 // var++
2339 // --var
2340 // var--
2341 // var += incr
2342 // var -= incr
2343 // var = var + incr
2344 // var = incr + var
2345 // var = var - incr
2346 //
2347 if (!S) {
2348 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2349 return true;
2350 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002351 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002352 S = S->IgnoreParens();
2353 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2354 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2355 return SetStep(
2356 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2357 (UO->isDecrementOp() ? -1 : 1)).get(),
2358 false);
2359 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2360 switch (BO->getOpcode()) {
2361 case BO_AddAssign:
2362 case BO_SubAssign:
2363 if (GetInitVarDecl(BO->getLHS()) == Var)
2364 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2365 break;
2366 case BO_Assign:
2367 if (GetInitVarDecl(BO->getLHS()) == Var)
2368 return CheckIncRHS(BO->getRHS());
2369 break;
2370 default:
2371 break;
2372 }
2373 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2374 switch (CE->getOperator()) {
2375 case OO_PlusPlus:
2376 case OO_MinusMinus:
2377 if (GetInitVarDecl(CE->getArg(0)) == Var)
2378 return SetStep(
2379 SemaRef.ActOnIntegerConstant(
2380 CE->getLocStart(),
2381 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2382 false);
2383 break;
2384 case OO_PlusEqual:
2385 case OO_MinusEqual:
2386 if (GetInitVarDecl(CE->getArg(0)) == Var)
2387 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2388 break;
2389 case OO_Equal:
2390 if (GetInitVarDecl(CE->getArg(0)) == Var)
2391 return CheckIncRHS(CE->getArg(1));
2392 break;
2393 default:
2394 break;
2395 }
2396 }
2397 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2398 << S->getSourceRange() << Var;
2399 return true;
2400}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002401
2402/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002403Expr *
2404OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2405 const bool LimitedType) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002406 ExprResult Diff;
2407 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2408 SemaRef.getLangOpts().CPlusPlus) {
2409 // Upper - Lower
2410 Expr *Upper = TestIsLessOp ? UB : LB;
2411 Expr *Lower = TestIsLessOp ? LB : UB;
2412
2413 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2414
2415 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2416 // BuildBinOp already emitted error, this one is to point user to upper
2417 // and lower bound, and to tell what is passed to 'operator-'.
2418 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2419 << Upper->getSourceRange() << Lower->getSourceRange();
2420 return nullptr;
2421 }
2422 }
2423
2424 if (!Diff.isUsable())
2425 return nullptr;
2426
2427 // Upper - Lower [- 1]
2428 if (TestIsStrictOp)
2429 Diff = SemaRef.BuildBinOp(
2430 S, DefaultLoc, BO_Sub, Diff.get(),
2431 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2432 if (!Diff.isUsable())
2433 return nullptr;
2434
2435 // Upper - Lower [- 1] + Step
2436 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2437 Step->IgnoreImplicit());
2438 if (!Diff.isUsable())
2439 return nullptr;
2440
2441 // Parentheses (for dumping/debugging purposes only).
2442 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2443 if (!Diff.isUsable())
2444 return nullptr;
2445
2446 // (Upper - Lower [- 1] + Step) / Step
2447 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2448 Step->IgnoreImplicit());
2449 if (!Diff.isUsable())
2450 return nullptr;
2451
Alexander Musman174b3ca2014-10-06 11:16:29 +00002452 // OpenMP runtime requires 32-bit or 64-bit loop variables.
2453 if (LimitedType) {
2454 auto &C = SemaRef.Context;
2455 QualType Type = Diff.get()->getType();
2456 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2457 if (NewSize != C.getTypeSize(Type)) {
2458 if (NewSize < C.getTypeSize(Type)) {
2459 assert(NewSize == 64 && "incorrect loop var size");
2460 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2461 << InitSrcRange << ConditionSrcRange;
2462 }
2463 QualType NewType = C.getIntTypeForBitwidth(
2464 NewSize, Type->hasSignedIntegerRepresentation());
2465 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2466 Sema::AA_Converting, true);
2467 if (!Diff.isUsable())
2468 return nullptr;
2469 }
2470 }
2471
Alexander Musmana5f070a2014-10-01 06:03:56 +00002472 return Diff.get();
2473}
2474
Alexey Bataev62dbb972015-04-22 11:59:37 +00002475Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
2476 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
2477 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
2478 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
2479 auto CondExpr = SemaRef.BuildBinOp(
2480 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
2481 : (TestIsStrictOp ? BO_GT : BO_GE),
2482 LB, UB);
2483 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
2484 // Otherwise use original loop conditon and evaluate it in runtime.
2485 return CondExpr.isUsable() ? CondExpr.get() : Cond;
2486}
2487
Alexander Musmana5f070a2014-10-01 06:03:56 +00002488/// \brief Build reference expression to the counter be used for codegen.
2489Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
Alexey Bataev39f915b82015-05-08 10:41:21 +00002490 return buildDeclRefExpr(SemaRef, Var, Var->getType(), DefaultLoc);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002491}
2492
2493/// \brief Build initization of the counter be used for codegen.
2494Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2495
2496/// \brief Build step of the counter be used for codegen.
2497Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2498
2499/// \brief Iteration space of a single for loop.
2500struct LoopIterationSpace {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002501 /// \brief Condition of the loop.
2502 Expr *PreCond;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002503 /// \brief This expression calculates the number of iterations in the loop.
2504 /// It is always possible to calculate it before starting the loop.
2505 Expr *NumIterations;
2506 /// \brief The loop counter variable.
2507 Expr *CounterVar;
2508 /// \brief This is initializer for the initial value of #CounterVar.
2509 Expr *CounterInit;
2510 /// \brief This is step for the #CounterVar used to generate its update:
2511 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2512 Expr *CounterStep;
2513 /// \brief Should step be subtracted?
2514 bool Subtract;
2515 /// \brief Source range of the loop init.
2516 SourceRange InitSrcRange;
2517 /// \brief Source range of the loop condition.
2518 SourceRange CondSrcRange;
2519 /// \brief Source range of the loop increment.
2520 SourceRange IncSrcRange;
2521};
2522
Alexey Bataev23b69422014-06-18 07:08:49 +00002523} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002524
Alexey Bataev9c821032015-04-30 04:23:23 +00002525void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
2526 assert(getLangOpts().OpenMP && "OpenMP is not active.");
2527 assert(Init && "Expected loop in canonical form.");
2528 unsigned CollapseIteration = DSAStack->getCollapseNumber();
2529 if (CollapseIteration > 0 &&
2530 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2531 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
2532 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
2533 DSAStack->addLoopControlVariable(ISC.GetLoopVar());
2534 }
2535 DSAStack->setCollapseNumber(CollapseIteration - 1);
2536 }
2537}
2538
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002539/// \brief Called on a for stmt to check and extract its iteration space
2540/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00002541static bool CheckOpenMPIterationSpace(
2542 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2543 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2544 Expr *NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002545 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2546 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002547 // OpenMP [2.6, Canonical Loop Form]
2548 // for (init-expr; test-expr; incr-expr) structured-block
2549 auto For = dyn_cast_or_null<ForStmt>(S);
2550 if (!For) {
2551 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002552 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2553 << NestedLoopCount << (CurrentNestedLoopCount > 0)
2554 << CurrentNestedLoopCount;
2555 if (NestedLoopCount > 1)
2556 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2557 diag::note_omp_collapse_expr)
2558 << NestedLoopCountExpr->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002559 return true;
2560 }
2561 assert(For->getBody());
2562
2563 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2564
2565 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002566 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002567 if (ISC.CheckInit(Init)) {
2568 return true;
2569 }
2570
2571 bool HasErrors = false;
2572
2573 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002574 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002575
2576 // OpenMP [2.6, Canonical Loop Form]
2577 // Var is one of the following:
2578 // A variable of signed or unsigned integer type.
2579 // For C++, a variable of a random access iterator type.
2580 // For C, a variable of a pointer type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002581 auto VarType = Var->getType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002582 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2583 !VarType->isPointerType() &&
2584 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2585 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2586 << SemaRef.getLangOpts().CPlusPlus;
2587 HasErrors = true;
2588 }
2589
Alexey Bataev4acb8592014-07-07 13:01:15 +00002590 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2591 // Construct
2592 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2593 // parallel for construct is (are) private.
2594 // The loop iteration variable in the associated for-loop of a simd construct
2595 // with just one associated for-loop is linear with a constant-linear-step
2596 // that is the increment of the associated for-loop.
2597 // Exclude loop var from the list of variables with implicitly defined data
2598 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00002599 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002600
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002601 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2602 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00002603 // The loop iteration variable in the associated for-loop of a simd construct
2604 // with just one associated for-loop may be listed in a linear clause with a
2605 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00002606 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2607 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002608 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002609 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2610 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2611 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002612 auto PredeterminedCKind =
2613 isOpenMPSimdDirective(DKind)
2614 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2615 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002616 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00002617 DVar.CKind != OMPC_threadprivate && DVar.CKind != PredeterminedCKind) ||
Alexander Musmanf82886e2014-09-18 05:12:34 +00002618 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2619 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00002620 DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_threadprivate)) &&
2621 ((DVar.CKind != OMPC_private && DVar.CKind != OMPC_threadprivate) ||
2622 DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002623 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00002624 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2625 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataevf2453a02015-05-06 07:25:08 +00002626 if (DVar.RefExpr == nullptr)
2627 DVar.CKind = PredeterminedCKind;
2628 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002629 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002630 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002631 // Make the loop iteration variable private (for worksharing constructs),
2632 // linear (for simd directives with the only one associated loop) or
2633 // lastprivate (for simd directives with several collapsed loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00002634 if (DVar.CKind == OMPC_unknown)
2635 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2636 /*FromParent=*/false);
Alexey Bataev9c821032015-04-30 04:23:23 +00002637 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002638 }
2639
Alexey Bataev7ff55242014-06-19 09:13:45 +00002640 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00002641
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002642 // Check test-expr.
2643 HasErrors |= ISC.CheckCond(For->getCond());
2644
2645 // Check incr-expr.
2646 HasErrors |= ISC.CheckInc(For->getInc());
2647
Alexander Musmana5f070a2014-10-01 06:03:56 +00002648 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002649 return HasErrors;
2650
Alexander Musmana5f070a2014-10-01 06:03:56 +00002651 // Build the loop's iteration space representation.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002652 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
Alexander Musman174b3ca2014-10-06 11:16:29 +00002653 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2654 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
Alexander Musmana5f070a2014-10-01 06:03:56 +00002655 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2656 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2657 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2658 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2659 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2660 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2661 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2662
Alexey Bataev62dbb972015-04-22 11:59:37 +00002663 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
2664 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00002665 ResultIterSpace.CounterVar == nullptr ||
2666 ResultIterSpace.CounterInit == nullptr ||
2667 ResultIterSpace.CounterStep == nullptr);
2668
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002669 return HasErrors;
2670}
2671
Alexander Musmana5f070a2014-10-01 06:03:56 +00002672/// \brief Build 'VarRef = Start + Iter * Step'.
2673static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2674 SourceLocation Loc, ExprResult VarRef,
2675 ExprResult Start, ExprResult Iter,
2676 ExprResult Step, bool Subtract) {
2677 // Add parentheses (for debugging purposes only).
2678 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2679 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2680 !Step.isUsable())
2681 return ExprError();
2682
2683 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2684 Step.get()->IgnoreImplicit());
2685 if (!Update.isUsable())
2686 return ExprError();
2687
2688 // Build 'VarRef = Start + Iter * Step'.
2689 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2690 Start.get()->IgnoreImplicit(), Update.get());
2691 if (!Update.isUsable())
2692 return ExprError();
2693
2694 Update = SemaRef.PerformImplicitConversion(
2695 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2696 if (!Update.isUsable())
2697 return ExprError();
2698
2699 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2700 return Update;
2701}
2702
2703/// \brief Convert integer expression \a E to make it have at least \a Bits
2704/// bits.
2705static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2706 Sema &SemaRef) {
2707 if (E == nullptr)
2708 return ExprError();
2709 auto &C = SemaRef.Context;
2710 QualType OldType = E->getType();
2711 unsigned HasBits = C.getTypeSize(OldType);
2712 if (HasBits >= Bits)
2713 return ExprResult(E);
2714 // OK to convert to signed, because new type has more bits than old.
2715 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2716 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2717 true);
2718}
2719
2720/// \brief Check if the given expression \a E is a constant integer that fits
2721/// into \a Bits bits.
2722static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2723 if (E == nullptr)
2724 return false;
2725 llvm::APSInt Result;
2726 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2727 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2728 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002729}
2730
2731/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00002732/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2733/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002734static unsigned
2735CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2736 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002737 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00002738 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002739 unsigned NestedLoopCount = 1;
2740 if (NestedLoopCountExpr) {
2741 // Found 'collapse' clause - calculate collapse number.
2742 llvm::APSInt Result;
2743 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2744 NestedLoopCount = Result.getLimitedValue();
2745 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002746 // This is helper routine for loop directives (e.g., 'for', 'simd',
2747 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00002748 SmallVector<LoopIterationSpace, 4> IterSpaces;
2749 IterSpaces.resize(NestedLoopCount);
2750 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002751 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002752 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev4acb8592014-07-07 13:01:15 +00002753 NestedLoopCount, NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002754 VarsWithImplicitDSA, IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00002755 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002756 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002757 // OpenMP [2.8.1, simd construct, Restrictions]
2758 // All loops associated with the construct must be perfectly nested; that
2759 // is, there must be no intervening code nor any OpenMP directive between
2760 // any two loops.
2761 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002762 }
2763
Alexander Musmana5f070a2014-10-01 06:03:56 +00002764 Built.clear(/* size */ NestedLoopCount);
2765
2766 if (SemaRef.CurContext->isDependentContext())
2767 return NestedLoopCount;
2768
2769 // An example of what is generated for the following code:
2770 //
2771 // #pragma omp simd collapse(2)
2772 // for (i = 0; i < NI; ++i)
2773 // for (j = J0; j < NJ; j+=2) {
2774 // <loop body>
2775 // }
2776 //
2777 // We generate the code below.
2778 // Note: the loop body may be outlined in CodeGen.
2779 // Note: some counters may be C++ classes, operator- is used to find number of
2780 // iterations and operator+= to calculate counter value.
2781 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2782 // or i64 is currently supported).
2783 //
2784 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2785 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2786 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2787 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2788 // // similar updates for vars in clauses (e.g. 'linear')
2789 // <loop body (using local i and j)>
2790 // }
2791 // i = NI; // assign final values of counters
2792 // j = NJ;
2793 //
2794
2795 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2796 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002797 // Precondition tests if there is at least one iteration (all conditions are
2798 // true).
2799 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002800 auto N0 = IterSpaces[0].NumIterations;
2801 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2802 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2803
2804 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2805 return NestedLoopCount;
2806
2807 auto &C = SemaRef.Context;
2808 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
2809
2810 Scope *CurScope = DSA.getCurScope();
2811 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002812 if (PreCond.isUsable()) {
2813 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
2814 PreCond.get(), IterSpaces[Cnt].PreCond);
2815 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002816 auto N = IterSpaces[Cnt].NumIterations;
2817 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
2818 if (LastIteration32.isUsable())
2819 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2820 LastIteration32.get(), N);
2821 if (LastIteration64.isUsable())
2822 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2823 LastIteration64.get(), N);
2824 }
2825
2826 // Choose either the 32-bit or 64-bit version.
2827 ExprResult LastIteration = LastIteration64;
2828 if (LastIteration32.isUsable() &&
2829 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
2830 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
2831 FitsInto(
2832 32 /* Bits */,
2833 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
2834 LastIteration64.get(), SemaRef)))
2835 LastIteration = LastIteration32;
2836
2837 if (!LastIteration.isUsable())
2838 return 0;
2839
2840 // Save the number of iterations.
2841 ExprResult NumIterations = LastIteration;
2842 {
2843 LastIteration = SemaRef.BuildBinOp(
2844 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
2845 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2846 if (!LastIteration.isUsable())
2847 return 0;
2848 }
2849
2850 // Calculate the last iteration number beforehand instead of doing this on
2851 // each iteration. Do not do this if the number of iterations may be kfold-ed.
2852 llvm::APSInt Result;
2853 bool IsConstant =
2854 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
2855 ExprResult CalcLastIteration;
2856 if (!IsConstant) {
2857 SourceLocation SaveLoc;
2858 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00002859 buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00002860 ".omp.last.iteration");
Alexey Bataev39f915b82015-05-08 10:41:21 +00002861 ExprResult SaveRef = buildDeclRefExpr(
2862 SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002863 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
2864 SaveRef.get(), LastIteration.get());
2865 LastIteration = SaveRef;
2866
2867 // Prepare SaveRef + 1.
2868 NumIterations = SemaRef.BuildBinOp(
2869 CurScope, SaveLoc, BO_Add, SaveRef.get(),
2870 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2871 if (!NumIterations.isUsable())
2872 return 0;
2873 }
2874
2875 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
2876
Alexander Musmanc6388682014-12-15 07:07:06 +00002877 QualType VType = LastIteration.get()->getType();
2878 // Build variables passed into runtime, nesessary for worksharing directives.
2879 ExprResult LB, UB, IL, ST, EUB;
2880 if (isOpenMPWorksharingDirective(DKind)) {
2881 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00002882 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
2883 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002884 SemaRef.AddInitializerToDecl(
2885 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2886 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2887
2888 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00002889 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
2890 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002891 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
2892 /*DirectInit*/ false,
2893 /*TypeMayContainAuto*/ false);
2894
2895 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
2896 // This will be used to implement clause 'lastprivate'.
2897 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002898 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
2899 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002900 SemaRef.AddInitializerToDecl(
2901 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2902 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2903
2904 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev39f915b82015-05-08 10:41:21 +00002905 VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
2906 ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002907 SemaRef.AddInitializerToDecl(
2908 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
2909 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2910
2911 // Build expression: UB = min(UB, LastIteration)
2912 // It is nesessary for CodeGen of directives with static scheduling.
2913 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
2914 UB.get(), LastIteration.get());
2915 ExprResult CondOp = SemaRef.ActOnConditionalOp(
2916 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
2917 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
2918 CondOp.get());
2919 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
2920 }
2921
2922 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002923 ExprResult IV;
2924 ExprResult Init;
2925 {
Alexey Bataev39f915b82015-05-08 10:41:21 +00002926 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
2927 IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002928 Expr *RHS = isOpenMPWorksharingDirective(DKind)
2929 ? LB.get()
2930 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
2931 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
2932 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002933 }
2934
Alexander Musmanc6388682014-12-15 07:07:06 +00002935 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002936 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00002937 ExprResult Cond =
2938 isOpenMPWorksharingDirective(DKind)
2939 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
2940 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
2941 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002942
2943 // Loop increment (IV = IV + 1)
2944 SourceLocation IncLoc;
2945 ExprResult Inc =
2946 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
2947 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
2948 if (!Inc.isUsable())
2949 return 0;
2950 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00002951 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
2952 if (!Inc.isUsable())
2953 return 0;
2954
2955 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
2956 // Used for directives with static scheduling.
2957 ExprResult NextLB, NextUB;
2958 if (isOpenMPWorksharingDirective(DKind)) {
2959 // LB + ST
2960 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
2961 if (!NextLB.isUsable())
2962 return 0;
2963 // LB = LB + ST
2964 NextLB =
2965 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
2966 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
2967 if (!NextLB.isUsable())
2968 return 0;
2969 // UB + ST
2970 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
2971 if (!NextUB.isUsable())
2972 return 0;
2973 // UB = UB + ST
2974 NextUB =
2975 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
2976 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
2977 if (!NextUB.isUsable())
2978 return 0;
2979 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002980
2981 // Build updates and final values of the loop counters.
2982 bool HasErrors = false;
2983 Built.Counters.resize(NestedLoopCount);
2984 Built.Updates.resize(NestedLoopCount);
2985 Built.Finals.resize(NestedLoopCount);
2986 {
2987 ExprResult Div;
2988 // Go from inner nested loop to outer.
2989 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
2990 LoopIterationSpace &IS = IterSpaces[Cnt];
2991 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
2992 // Build: Iter = (IV / Div) % IS.NumIters
2993 // where Div is product of previous iterations' IS.NumIters.
2994 ExprResult Iter;
2995 if (Div.isUsable()) {
2996 Iter =
2997 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
2998 } else {
2999 Iter = IV;
3000 assert((Cnt == (int)NestedLoopCount - 1) &&
3001 "unusable div expected on first iteration only");
3002 }
3003
3004 if (Cnt != 0 && Iter.isUsable())
3005 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
3006 IS.NumIterations);
3007 if (!Iter.isUsable()) {
3008 HasErrors = true;
3009 break;
3010 }
3011
Alexey Bataev39f915b82015-05-08 10:41:21 +00003012 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
3013 auto *CounterVar = buildDeclRefExpr(
3014 SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
3015 IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
3016 /*RefersToCapture=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003017 ExprResult Update =
Alexey Bataev39f915b82015-05-08 10:41:21 +00003018 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003019 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
3020 if (!Update.isUsable()) {
3021 HasErrors = true;
3022 break;
3023 }
3024
3025 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
3026 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00003027 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003028 IS.NumIterations, IS.CounterStep, IS.Subtract);
3029 if (!Final.isUsable()) {
3030 HasErrors = true;
3031 break;
3032 }
3033
3034 // Build Div for the next iteration: Div <- Div * IS.NumIters
3035 if (Cnt != 0) {
3036 if (Div.isUnset())
3037 Div = IS.NumIterations;
3038 else
3039 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
3040 IS.NumIterations);
3041
3042 // Add parentheses (for debugging purposes only).
3043 if (Div.isUsable())
3044 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
3045 if (!Div.isUsable()) {
3046 HasErrors = true;
3047 break;
3048 }
3049 }
3050 if (!Update.isUsable() || !Final.isUsable()) {
3051 HasErrors = true;
3052 break;
3053 }
3054 // Save results
3055 Built.Counters[Cnt] = IS.CounterVar;
3056 Built.Updates[Cnt] = Update.get();
3057 Built.Finals[Cnt] = Final.get();
3058 }
3059 }
3060
3061 if (HasErrors)
3062 return 0;
3063
3064 // Save results
3065 Built.IterationVarRef = IV.get();
3066 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00003067 Built.NumIterations = NumIterations.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003068 Built.CalcLastIteration = CalcLastIteration.get();
3069 Built.PreCond = PreCond.get();
3070 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003071 Built.Init = Init.get();
3072 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00003073 Built.LB = LB.get();
3074 Built.UB = UB.get();
3075 Built.IL = IL.get();
3076 Built.ST = ST.get();
3077 Built.EUB = EUB.get();
3078 Built.NLB = NextLB.get();
3079 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003080
Alexey Bataevabfc0692014-06-25 06:52:00 +00003081 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003082}
3083
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003084static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Alexey Bataevc925aa32015-04-27 08:00:32 +00003085 auto &&CollapseFilter = [](const OMPClause *C) -> bool {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003086 return C->getClauseKind() == OMPC_collapse;
3087 };
3088 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
Alexey Bataevc925aa32015-04-27 08:00:32 +00003089 Clauses, std::move(CollapseFilter));
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003090 if (I)
3091 return cast<OMPCollapseClause>(*I)->getNumForLoops();
3092 return nullptr;
3093}
3094
Alexey Bataev4acb8592014-07-07 13:01:15 +00003095StmtResult Sema::ActOnOpenMPSimdDirective(
3096 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3097 SourceLocation EndLoc,
3098 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003099 OMPLoopDirective::HelperExprs B;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003100 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003101 unsigned NestedLoopCount =
3102 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003103 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003104 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003105 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003106
Alexander Musmana5f070a2014-10-01 06:03:56 +00003107 assert((CurContext->isDependentContext() || B.builtAll()) &&
3108 "omp simd loop exprs were not built");
3109
Alexander Musman3276a272015-03-21 10:12:56 +00003110 if (!CurContext->isDependentContext()) {
3111 // Finalize the clauses that need pre-built expressions for CodeGen.
3112 for (auto C : Clauses) {
3113 if (auto LC = dyn_cast<OMPLinearClause>(C))
3114 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3115 B.NumIterations, *this, CurScope))
3116 return StmtError();
3117 }
3118 }
3119
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003120 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003121 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3122 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003123}
3124
Alexey Bataev4acb8592014-07-07 13:01:15 +00003125StmtResult Sema::ActOnOpenMPForDirective(
3126 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3127 SourceLocation EndLoc,
3128 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003129 OMPLoopDirective::HelperExprs B;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003130 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003131 unsigned NestedLoopCount =
3132 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003133 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003134 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00003135 return StmtError();
3136
Alexander Musmana5f070a2014-10-01 06:03:56 +00003137 assert((CurContext->isDependentContext() || B.builtAll()) &&
3138 "omp for loop exprs were not built");
3139
Alexey Bataevf29276e2014-06-18 04:14:57 +00003140 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003141 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3142 Clauses, AStmt, B);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003143}
3144
Alexander Musmanf82886e2014-09-18 05:12:34 +00003145StmtResult Sema::ActOnOpenMPForSimdDirective(
3146 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3147 SourceLocation EndLoc,
3148 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003149 OMPLoopDirective::HelperExprs B;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003150 // In presence of clause 'collapse', it will define the nested loops number.
3151 unsigned NestedLoopCount =
3152 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003153 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003154 if (NestedLoopCount == 0)
3155 return StmtError();
3156
Alexander Musmanc6388682014-12-15 07:07:06 +00003157 assert((CurContext->isDependentContext() || B.builtAll()) &&
3158 "omp for simd loop exprs were not built");
3159
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00003160 if (!CurContext->isDependentContext()) {
3161 // Finalize the clauses that need pre-built expressions for CodeGen.
3162 for (auto C : Clauses) {
3163 if (auto LC = dyn_cast<OMPLinearClause>(C))
3164 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3165 B.NumIterations, *this, CurScope))
3166 return StmtError();
3167 }
3168 }
3169
Alexander Musmanf82886e2014-09-18 05:12:34 +00003170 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003171 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3172 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003173}
3174
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003175StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3176 Stmt *AStmt,
3177 SourceLocation StartLoc,
3178 SourceLocation EndLoc) {
3179 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3180 auto BaseStmt = AStmt;
3181 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3182 BaseStmt = CS->getCapturedStmt();
3183 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3184 auto S = C->children();
3185 if (!S)
3186 return StmtError();
3187 // All associated statements must be '#pragma omp section' except for
3188 // the first one.
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003189 for (++S; S; ++S) {
3190 auto SectionStmt = *S;
3191 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3192 if (SectionStmt)
3193 Diag(SectionStmt->getLocStart(),
3194 diag::err_omp_sections_substmt_not_section);
3195 return StmtError();
3196 }
3197 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003198 } else {
3199 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3200 return StmtError();
3201 }
3202
3203 getCurFunction()->setHasBranchProtectedScope();
3204
3205 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3206 AStmt);
3207}
3208
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003209StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3210 SourceLocation StartLoc,
3211 SourceLocation EndLoc) {
3212 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3213
3214 getCurFunction()->setHasBranchProtectedScope();
3215
3216 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3217}
3218
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003219StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3220 Stmt *AStmt,
3221 SourceLocation StartLoc,
3222 SourceLocation EndLoc) {
Alexey Bataev74a05c92014-07-15 02:55:09 +00003223 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3224
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003225 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00003226
Alexey Bataev3255bf32015-01-19 05:20:46 +00003227 // OpenMP [2.7.3, single Construct, Restrictions]
3228 // The copyprivate clause must not be used with the nowait clause.
3229 OMPClause *Nowait = nullptr;
3230 OMPClause *Copyprivate = nullptr;
3231 for (auto *Clause : Clauses) {
3232 if (Clause->getClauseKind() == OMPC_nowait)
3233 Nowait = Clause;
3234 else if (Clause->getClauseKind() == OMPC_copyprivate)
3235 Copyprivate = Clause;
3236 if (Copyprivate && Nowait) {
3237 Diag(Copyprivate->getLocStart(),
3238 diag::err_omp_single_copyprivate_with_nowait);
3239 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3240 return StmtError();
3241 }
3242 }
3243
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003244 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3245}
3246
Alexander Musman80c22892014-07-17 08:54:58 +00003247StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3248 SourceLocation StartLoc,
3249 SourceLocation EndLoc) {
3250 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3251
3252 getCurFunction()->setHasBranchProtectedScope();
3253
3254 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3255}
3256
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003257StmtResult
3258Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3259 Stmt *AStmt, SourceLocation StartLoc,
3260 SourceLocation EndLoc) {
3261 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3262
3263 getCurFunction()->setHasBranchProtectedScope();
3264
3265 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3266 AStmt);
3267}
3268
Alexey Bataev4acb8592014-07-07 13:01:15 +00003269StmtResult Sema::ActOnOpenMPParallelForDirective(
3270 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3271 SourceLocation EndLoc,
3272 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3273 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3274 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3275 // 1.2.2 OpenMP Language Terminology
3276 // Structured block - An executable statement with a single entry at the
3277 // top and a single exit at the bottom.
3278 // The point of exit cannot be a branch out of the structured block.
3279 // longjmp() and throw() must not violate the entry/exit criteria.
3280 CS->getCapturedDecl()->setNothrow();
3281
Alexander Musmanc6388682014-12-15 07:07:06 +00003282 OMPLoopDirective::HelperExprs B;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003283 // In presence of clause 'collapse', it will define the nested loops number.
3284 unsigned NestedLoopCount =
3285 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003286 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003287 if (NestedLoopCount == 0)
3288 return StmtError();
3289
Alexander Musmana5f070a2014-10-01 06:03:56 +00003290 assert((CurContext->isDependentContext() || B.builtAll()) &&
3291 "omp parallel for loop exprs were not built");
3292
Alexey Bataev4acb8592014-07-07 13:01:15 +00003293 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003294 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3295 NestedLoopCount, Clauses, AStmt, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003296}
3297
Alexander Musmane4e893b2014-09-23 09:33:00 +00003298StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3299 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3300 SourceLocation EndLoc,
3301 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3302 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3303 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3304 // 1.2.2 OpenMP Language Terminology
3305 // Structured block - An executable statement with a single entry at the
3306 // top and a single exit at the bottom.
3307 // The point of exit cannot be a branch out of the structured block.
3308 // longjmp() and throw() must not violate the entry/exit criteria.
3309 CS->getCapturedDecl()->setNothrow();
3310
Alexander Musmanc6388682014-12-15 07:07:06 +00003311 OMPLoopDirective::HelperExprs B;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003312 // In presence of clause 'collapse', it will define the nested loops number.
3313 unsigned NestedLoopCount =
3314 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003315 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003316 if (NestedLoopCount == 0)
3317 return StmtError();
3318
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00003319 if (!CurContext->isDependentContext()) {
3320 // Finalize the clauses that need pre-built expressions for CodeGen.
3321 for (auto C : Clauses) {
3322 if (auto LC = dyn_cast<OMPLinearClause>(C))
3323 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3324 B.NumIterations, *this, CurScope))
3325 return StmtError();
3326 }
3327 }
3328
Alexander Musmane4e893b2014-09-23 09:33:00 +00003329 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003330 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00003331 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003332}
3333
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003334StmtResult
3335Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3336 Stmt *AStmt, SourceLocation StartLoc,
3337 SourceLocation EndLoc) {
3338 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3339 auto BaseStmt = AStmt;
3340 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3341 BaseStmt = CS->getCapturedStmt();
3342 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3343 auto S = C->children();
3344 if (!S)
3345 return StmtError();
3346 // All associated statements must be '#pragma omp section' except for
3347 // the first one.
3348 for (++S; S; ++S) {
3349 auto SectionStmt = *S;
3350 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3351 if (SectionStmt)
3352 Diag(SectionStmt->getLocStart(),
3353 diag::err_omp_parallel_sections_substmt_not_section);
3354 return StmtError();
3355 }
3356 }
3357 } else {
3358 Diag(AStmt->getLocStart(),
3359 diag::err_omp_parallel_sections_not_compound_stmt);
3360 return StmtError();
3361 }
3362
3363 getCurFunction()->setHasBranchProtectedScope();
3364
3365 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3366 Clauses, AStmt);
3367}
3368
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003369StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3370 Stmt *AStmt, SourceLocation StartLoc,
3371 SourceLocation EndLoc) {
3372 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3373 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3374 // 1.2.2 OpenMP Language Terminology
3375 // Structured block - An executable statement with a single entry at the
3376 // top and a single exit at the bottom.
3377 // The point of exit cannot be a branch out of the structured block.
3378 // longjmp() and throw() must not violate the entry/exit criteria.
3379 CS->getCapturedDecl()->setNothrow();
3380
3381 getCurFunction()->setHasBranchProtectedScope();
3382
3383 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3384}
3385
Alexey Bataev68446b72014-07-18 07:47:19 +00003386StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3387 SourceLocation EndLoc) {
3388 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3389}
3390
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003391StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3392 SourceLocation EndLoc) {
3393 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3394}
3395
Alexey Bataev2df347a2014-07-18 10:17:07 +00003396StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3397 SourceLocation EndLoc) {
3398 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3399}
3400
Alexey Bataev6125da92014-07-21 11:26:11 +00003401StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3402 SourceLocation StartLoc,
3403 SourceLocation EndLoc) {
3404 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3405 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3406}
3407
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003408StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3409 SourceLocation StartLoc,
3410 SourceLocation EndLoc) {
3411 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3412
3413 getCurFunction()->setHasBranchProtectedScope();
3414
3415 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3416}
3417
Alexey Bataev1d160b12015-03-13 12:27:31 +00003418namespace {
3419/// \brief Helper class for checking expression in 'omp atomic [update]'
3420/// construct.
3421class OpenMPAtomicUpdateChecker {
3422 /// \brief Error results for atomic update expressions.
3423 enum ExprAnalysisErrorCode {
3424 /// \brief A statement is not an expression statement.
3425 NotAnExpression,
3426 /// \brief Expression is not builtin binary or unary operation.
3427 NotABinaryOrUnaryExpression,
3428 /// \brief Unary operation is not post-/pre- increment/decrement operation.
3429 NotAnUnaryIncDecExpression,
3430 /// \brief An expression is not of scalar type.
3431 NotAScalarType,
3432 /// \brief A binary operation is not an assignment operation.
3433 NotAnAssignmentOp,
3434 /// \brief RHS part of the binary operation is not a binary expression.
3435 NotABinaryExpression,
3436 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
3437 /// expression.
3438 NotABinaryOperator,
3439 /// \brief RHS binary operation does not have reference to the updated LHS
3440 /// part.
3441 NotAnUpdateExpression,
3442 /// \brief No errors is found.
3443 NoError
3444 };
3445 /// \brief Reference to Sema.
3446 Sema &SemaRef;
3447 /// \brief A location for note diagnostics (when error is found).
3448 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003449 /// \brief 'x' lvalue part of the source atomic expression.
3450 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003451 /// \brief 'expr' rvalue part of the source atomic expression.
3452 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003453 /// \brief Helper expression of the form
3454 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3455 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3456 Expr *UpdateExpr;
3457 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
3458 /// important for non-associative operations.
3459 bool IsXLHSInRHSPart;
3460 BinaryOperatorKind Op;
3461 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003462 /// \brief true if the source expression is a postfix unary operation, false
3463 /// if it is a prefix unary operation.
3464 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003465
3466public:
3467 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00003468 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00003469 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00003470 /// \brief Check specified statement that it is suitable for 'atomic update'
3471 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00003472 /// expression. If DiagId and NoteId == 0, then only check is performed
3473 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00003474 /// \param DiagId Diagnostic which should be emitted if error is found.
3475 /// \param NoteId Diagnostic note for the main error message.
3476 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00003477 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003478 /// \brief Return the 'x' lvalue part of the source atomic expression.
3479 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00003480 /// \brief Return the 'expr' rvalue part of the source atomic expression.
3481 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00003482 /// \brief Return the update expression used in calculation of the updated
3483 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3484 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3485 Expr *getUpdateExpr() const { return UpdateExpr; }
3486 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
3487 /// false otherwise.
3488 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
3489
Alexey Bataevb78ca832015-04-01 03:33:17 +00003490 /// \brief true if the source expression is a postfix unary operation, false
3491 /// if it is a prefix unary operation.
3492 bool isPostfixUpdate() const { return IsPostfixUpdate; }
3493
Alexey Bataev1d160b12015-03-13 12:27:31 +00003494private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00003495 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
3496 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003497};
3498} // namespace
3499
3500bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
3501 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
3502 ExprAnalysisErrorCode ErrorFound = NoError;
3503 SourceLocation ErrorLoc, NoteLoc;
3504 SourceRange ErrorRange, NoteRange;
3505 // Allowed constructs are:
3506 // x = x binop expr;
3507 // x = expr binop x;
3508 if (AtomicBinOp->getOpcode() == BO_Assign) {
3509 X = AtomicBinOp->getLHS();
3510 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
3511 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
3512 if (AtomicInnerBinOp->isMultiplicativeOp() ||
3513 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
3514 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003515 Op = AtomicInnerBinOp->getOpcode();
3516 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003517 auto *LHS = AtomicInnerBinOp->getLHS();
3518 auto *RHS = AtomicInnerBinOp->getRHS();
3519 llvm::FoldingSetNodeID XId, LHSId, RHSId;
3520 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
3521 /*Canonical=*/true);
3522 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
3523 /*Canonical=*/true);
3524 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
3525 /*Canonical=*/true);
3526 if (XId == LHSId) {
3527 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003528 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003529 } else if (XId == RHSId) {
3530 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003531 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003532 } else {
3533 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3534 ErrorRange = AtomicInnerBinOp->getSourceRange();
3535 NoteLoc = X->getExprLoc();
3536 NoteRange = X->getSourceRange();
3537 ErrorFound = NotAnUpdateExpression;
3538 }
3539 } else {
3540 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3541 ErrorRange = AtomicInnerBinOp->getSourceRange();
3542 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
3543 NoteRange = SourceRange(NoteLoc, NoteLoc);
3544 ErrorFound = NotABinaryOperator;
3545 }
3546 } else {
3547 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
3548 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
3549 ErrorFound = NotABinaryExpression;
3550 }
3551 } else {
3552 ErrorLoc = AtomicBinOp->getExprLoc();
3553 ErrorRange = AtomicBinOp->getSourceRange();
3554 NoteLoc = AtomicBinOp->getOperatorLoc();
3555 NoteRange = SourceRange(NoteLoc, NoteLoc);
3556 ErrorFound = NotAnAssignmentOp;
3557 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003558 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003559 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3560 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3561 return true;
3562 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003563 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003564 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003565}
3566
3567bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
3568 unsigned NoteId) {
3569 ExprAnalysisErrorCode ErrorFound = NoError;
3570 SourceLocation ErrorLoc, NoteLoc;
3571 SourceRange ErrorRange, NoteRange;
3572 // Allowed constructs are:
3573 // x++;
3574 // x--;
3575 // ++x;
3576 // --x;
3577 // x binop= expr;
3578 // x = x binop expr;
3579 // x = expr binop x;
3580 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
3581 AtomicBody = AtomicBody->IgnoreParenImpCasts();
3582 if (AtomicBody->getType()->isScalarType() ||
3583 AtomicBody->isInstantiationDependent()) {
3584 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
3585 AtomicBody->IgnoreParenImpCasts())) {
3586 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003587 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00003588 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003589 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003590 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003591 X = AtomicCompAssignOp->getLHS();
3592 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003593 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
3594 AtomicBody->IgnoreParenImpCasts())) {
3595 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003596 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
3597 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003598 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00003599 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
3600 // Check for Unary Operation
3601 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003602 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003603 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
3604 OpLoc = AtomicUnaryOp->getOperatorLoc();
3605 X = AtomicUnaryOp->getSubExpr();
3606 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
3607 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003608 } else {
3609 ErrorFound = NotAnUnaryIncDecExpression;
3610 ErrorLoc = AtomicUnaryOp->getExprLoc();
3611 ErrorRange = AtomicUnaryOp->getSourceRange();
3612 NoteLoc = AtomicUnaryOp->getOperatorLoc();
3613 NoteRange = SourceRange(NoteLoc, NoteLoc);
3614 }
3615 } else {
3616 ErrorFound = NotABinaryOrUnaryExpression;
3617 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
3618 NoteRange = ErrorRange = AtomicBody->getSourceRange();
3619 }
3620 } else {
3621 ErrorFound = NotAScalarType;
3622 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
3623 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3624 }
3625 } else {
3626 ErrorFound = NotAnExpression;
3627 NoteLoc = ErrorLoc = S->getLocStart();
3628 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3629 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003630 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003631 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3632 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3633 return true;
3634 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003635 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003636 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003637 // Build an update expression of form 'OpaqueValueExpr(x) binop
3638 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
3639 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
3640 auto *OVEX = new (SemaRef.getASTContext())
3641 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
3642 auto *OVEExpr = new (SemaRef.getASTContext())
3643 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
3644 auto Update =
3645 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
3646 IsXLHSInRHSPart ? OVEExpr : OVEX);
3647 if (Update.isInvalid())
3648 return true;
3649 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
3650 Sema::AA_Casting);
3651 if (Update.isInvalid())
3652 return true;
3653 UpdateExpr = Update.get();
3654 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003655 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003656}
3657
Alexey Bataev0162e452014-07-22 10:10:35 +00003658StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3659 Stmt *AStmt,
3660 SourceLocation StartLoc,
3661 SourceLocation EndLoc) {
3662 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003663 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00003664 // 1.2.2 OpenMP Language Terminology
3665 // Structured block - An executable statement with a single entry at the
3666 // top and a single exit at the bottom.
3667 // The point of exit cannot be a branch out of the structured block.
3668 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00003669 OpenMPClauseKind AtomicKind = OMPC_unknown;
3670 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003671 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00003672 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00003673 C->getClauseKind() == OMPC_update ||
3674 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00003675 if (AtomicKind != OMPC_unknown) {
3676 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3677 << SourceRange(C->getLocStart(), C->getLocEnd());
3678 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3679 << getOpenMPClauseName(AtomicKind);
3680 } else {
3681 AtomicKind = C->getClauseKind();
3682 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003683 }
3684 }
3685 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003686
Alexey Bataev459dec02014-07-24 06:46:57 +00003687 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00003688 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
3689 Body = EWC->getSubExpr();
3690
Alexey Bataev62cec442014-11-18 10:14:22 +00003691 Expr *X = nullptr;
3692 Expr *V = nullptr;
3693 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003694 Expr *UE = nullptr;
3695 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003696 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00003697 // OpenMP [2.12.6, atomic Construct]
3698 // In the next expressions:
3699 // * x and v (as applicable) are both l-value expressions with scalar type.
3700 // * During the execution of an atomic region, multiple syntactic
3701 // occurrences of x must designate the same storage location.
3702 // * Neither of v and expr (as applicable) may access the storage location
3703 // designated by x.
3704 // * Neither of x and expr (as applicable) may access the storage location
3705 // designated by v.
3706 // * expr is an expression with scalar type.
3707 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3708 // * binop, binop=, ++, and -- are not overloaded operators.
3709 // * The expression x binop expr must be numerically equivalent to x binop
3710 // (expr). This requirement is satisfied if the operators in expr have
3711 // precedence greater than binop, or by using parentheses around expr or
3712 // subexpressions of expr.
3713 // * The expression expr binop x must be numerically equivalent to (expr)
3714 // binop x. This requirement is satisfied if the operators in expr have
3715 // precedence equal to or greater than binop, or by using parentheses around
3716 // expr or subexpressions of expr.
3717 // * For forms that allow multiple occurrences of x, the number of times
3718 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00003719 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003720 enum {
3721 NotAnExpression,
3722 NotAnAssignmentOp,
3723 NotAScalarType,
3724 NotAnLValue,
3725 NoError
3726 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00003727 SourceLocation ErrorLoc, NoteLoc;
3728 SourceRange ErrorRange, NoteRange;
3729 // If clause is read:
3730 // v = x;
3731 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3732 auto AtomicBinOp =
3733 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3734 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3735 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3736 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3737 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3738 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3739 if (!X->isLValue() || !V->isLValue()) {
3740 auto NotLValueExpr = X->isLValue() ? V : X;
3741 ErrorFound = NotAnLValue;
3742 ErrorLoc = AtomicBinOp->getExprLoc();
3743 ErrorRange = AtomicBinOp->getSourceRange();
3744 NoteLoc = NotLValueExpr->getExprLoc();
3745 NoteRange = NotLValueExpr->getSourceRange();
3746 }
3747 } else if (!X->isInstantiationDependent() ||
3748 !V->isInstantiationDependent()) {
3749 auto NotScalarExpr =
3750 (X->isInstantiationDependent() || X->getType()->isScalarType())
3751 ? V
3752 : X;
3753 ErrorFound = NotAScalarType;
3754 ErrorLoc = AtomicBinOp->getExprLoc();
3755 ErrorRange = AtomicBinOp->getSourceRange();
3756 NoteLoc = NotScalarExpr->getExprLoc();
3757 NoteRange = NotScalarExpr->getSourceRange();
3758 }
3759 } else {
3760 ErrorFound = NotAnAssignmentOp;
3761 ErrorLoc = AtomicBody->getExprLoc();
3762 ErrorRange = AtomicBody->getSourceRange();
3763 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3764 : AtomicBody->getExprLoc();
3765 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3766 : AtomicBody->getSourceRange();
3767 }
3768 } else {
3769 ErrorFound = NotAnExpression;
3770 NoteLoc = ErrorLoc = Body->getLocStart();
3771 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003772 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003773 if (ErrorFound != NoError) {
3774 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3775 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003776 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3777 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00003778 return StmtError();
3779 } else if (CurContext->isDependentContext())
3780 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00003781 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003782 enum {
3783 NotAnExpression,
3784 NotAnAssignmentOp,
3785 NotAScalarType,
3786 NotAnLValue,
3787 NoError
3788 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003789 SourceLocation ErrorLoc, NoteLoc;
3790 SourceRange ErrorRange, NoteRange;
3791 // If clause is write:
3792 // x = expr;
3793 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3794 auto AtomicBinOp =
3795 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3796 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00003797 X = AtomicBinOp->getLHS();
3798 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00003799 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3800 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
3801 if (!X->isLValue()) {
3802 ErrorFound = NotAnLValue;
3803 ErrorLoc = AtomicBinOp->getExprLoc();
3804 ErrorRange = AtomicBinOp->getSourceRange();
3805 NoteLoc = X->getExprLoc();
3806 NoteRange = X->getSourceRange();
3807 }
3808 } else if (!X->isInstantiationDependent() ||
3809 !E->isInstantiationDependent()) {
3810 auto NotScalarExpr =
3811 (X->isInstantiationDependent() || X->getType()->isScalarType())
3812 ? E
3813 : X;
3814 ErrorFound = NotAScalarType;
3815 ErrorLoc = AtomicBinOp->getExprLoc();
3816 ErrorRange = AtomicBinOp->getSourceRange();
3817 NoteLoc = NotScalarExpr->getExprLoc();
3818 NoteRange = NotScalarExpr->getSourceRange();
3819 }
3820 } else {
3821 ErrorFound = NotAnAssignmentOp;
3822 ErrorLoc = AtomicBody->getExprLoc();
3823 ErrorRange = AtomicBody->getSourceRange();
3824 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3825 : AtomicBody->getExprLoc();
3826 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3827 : AtomicBody->getSourceRange();
3828 }
3829 } else {
3830 ErrorFound = NotAnExpression;
3831 NoteLoc = ErrorLoc = Body->getLocStart();
3832 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003833 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00003834 if (ErrorFound != NoError) {
3835 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
3836 << ErrorRange;
3837 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3838 << NoteRange;
3839 return StmtError();
3840 } else if (CurContext->isDependentContext())
3841 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00003842 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003843 // If clause is update:
3844 // x++;
3845 // x--;
3846 // ++x;
3847 // --x;
3848 // x binop= expr;
3849 // x = x binop expr;
3850 // x = expr binop x;
3851 OpenMPAtomicUpdateChecker Checker(*this);
3852 if (Checker.checkStatement(
3853 Body, (AtomicKind == OMPC_update)
3854 ? diag::err_omp_atomic_update_not_expression_statement
3855 : diag::err_omp_atomic_not_expression_statement,
3856 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00003857 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003858 if (!CurContext->isDependentContext()) {
3859 E = Checker.getExpr();
3860 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003861 UE = Checker.getUpdateExpr();
3862 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00003863 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003864 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003865 enum {
3866 NotAnAssignmentOp,
3867 NotACompoundStatement,
3868 NotTwoSubstatements,
3869 NotASpecificExpression,
3870 NoError
3871 } ErrorFound = NoError;
3872 SourceLocation ErrorLoc, NoteLoc;
3873 SourceRange ErrorRange, NoteRange;
3874 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
3875 // If clause is a capture:
3876 // v = x++;
3877 // v = x--;
3878 // v = ++x;
3879 // v = --x;
3880 // v = x binop= expr;
3881 // v = x = x binop expr;
3882 // v = x = expr binop x;
3883 auto *AtomicBinOp =
3884 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3885 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3886 V = AtomicBinOp->getLHS();
3887 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3888 OpenMPAtomicUpdateChecker Checker(*this);
3889 if (Checker.checkStatement(
3890 Body, diag::err_omp_atomic_capture_not_expression_statement,
3891 diag::note_omp_atomic_update))
3892 return StmtError();
3893 E = Checker.getExpr();
3894 X = Checker.getX();
3895 UE = Checker.getUpdateExpr();
3896 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3897 IsPostfixUpdate = Checker.isPostfixUpdate();
3898 } else {
3899 ErrorLoc = AtomicBody->getExprLoc();
3900 ErrorRange = AtomicBody->getSourceRange();
3901 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3902 : AtomicBody->getExprLoc();
3903 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3904 : AtomicBody->getSourceRange();
3905 ErrorFound = NotAnAssignmentOp;
3906 }
3907 if (ErrorFound != NoError) {
3908 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
3909 << ErrorRange;
3910 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3911 return StmtError();
3912 } else if (CurContext->isDependentContext()) {
3913 UE = V = E = X = nullptr;
3914 }
3915 } else {
3916 // If clause is a capture:
3917 // { v = x; x = expr; }
3918 // { v = x; x++; }
3919 // { v = x; x--; }
3920 // { v = x; ++x; }
3921 // { v = x; --x; }
3922 // { v = x; x binop= expr; }
3923 // { v = x; x = x binop expr; }
3924 // { v = x; x = expr binop x; }
3925 // { x++; v = x; }
3926 // { x--; v = x; }
3927 // { ++x; v = x; }
3928 // { --x; v = x; }
3929 // { x binop= expr; v = x; }
3930 // { x = x binop expr; v = x; }
3931 // { x = expr binop x; v = x; }
3932 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
3933 // Check that this is { expr1; expr2; }
3934 if (CS->size() == 2) {
3935 auto *First = CS->body_front();
3936 auto *Second = CS->body_back();
3937 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
3938 First = EWC->getSubExpr()->IgnoreParenImpCasts();
3939 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
3940 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
3941 // Need to find what subexpression is 'v' and what is 'x'.
3942 OpenMPAtomicUpdateChecker Checker(*this);
3943 bool IsUpdateExprFound = !Checker.checkStatement(Second);
3944 BinaryOperator *BinOp = nullptr;
3945 if (IsUpdateExprFound) {
3946 BinOp = dyn_cast<BinaryOperator>(First);
3947 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3948 }
3949 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3950 // { v = x; x++; }
3951 // { v = x; x--; }
3952 // { v = x; ++x; }
3953 // { v = x; --x; }
3954 // { v = x; x binop= expr; }
3955 // { v = x; x = x binop expr; }
3956 // { v = x; x = expr binop x; }
3957 // Check that the first expression has form v = x.
3958 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3959 llvm::FoldingSetNodeID XId, PossibleXId;
3960 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3961 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3962 IsUpdateExprFound = XId == PossibleXId;
3963 if (IsUpdateExprFound) {
3964 V = BinOp->getLHS();
3965 X = Checker.getX();
3966 E = Checker.getExpr();
3967 UE = Checker.getUpdateExpr();
3968 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003969 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003970 }
3971 }
3972 if (!IsUpdateExprFound) {
3973 IsUpdateExprFound = !Checker.checkStatement(First);
3974 BinOp = nullptr;
3975 if (IsUpdateExprFound) {
3976 BinOp = dyn_cast<BinaryOperator>(Second);
3977 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3978 }
3979 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3980 // { x++; v = x; }
3981 // { x--; v = x; }
3982 // { ++x; v = x; }
3983 // { --x; v = x; }
3984 // { x binop= expr; v = x; }
3985 // { x = x binop expr; v = x; }
3986 // { x = expr binop x; v = x; }
3987 // Check that the second expression has form v = x.
3988 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3989 llvm::FoldingSetNodeID XId, PossibleXId;
3990 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3991 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3992 IsUpdateExprFound = XId == PossibleXId;
3993 if (IsUpdateExprFound) {
3994 V = BinOp->getLHS();
3995 X = Checker.getX();
3996 E = Checker.getExpr();
3997 UE = Checker.getUpdateExpr();
3998 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003999 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004000 }
4001 }
4002 }
4003 if (!IsUpdateExprFound) {
4004 // { v = x; x = expr; }
4005 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
4006 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
4007 ErrorFound = NotAnAssignmentOp;
4008 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
4009 : First->getLocStart();
4010 NoteRange = ErrorRange = FirstBinOp
4011 ? FirstBinOp->getSourceRange()
4012 : SourceRange(ErrorLoc, ErrorLoc);
4013 } else {
4014 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
4015 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
4016 ErrorFound = NotAnAssignmentOp;
4017 NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
4018 : Second->getLocStart();
4019 NoteRange = ErrorRange = SecondBinOp
4020 ? SecondBinOp->getSourceRange()
4021 : SourceRange(ErrorLoc, ErrorLoc);
4022 } else {
4023 auto *PossibleXRHSInFirst =
4024 FirstBinOp->getRHS()->IgnoreParenImpCasts();
4025 auto *PossibleXLHSInSecond =
4026 SecondBinOp->getLHS()->IgnoreParenImpCasts();
4027 llvm::FoldingSetNodeID X1Id, X2Id;
4028 PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
4029 PossibleXLHSInSecond->Profile(X2Id, Context,
4030 /*Canonical=*/true);
4031 IsUpdateExprFound = X1Id == X2Id;
4032 if (IsUpdateExprFound) {
4033 V = FirstBinOp->getLHS();
4034 X = SecondBinOp->getLHS();
4035 E = SecondBinOp->getRHS();
4036 UE = nullptr;
4037 IsXLHSInRHSPart = false;
4038 IsPostfixUpdate = true;
4039 } else {
4040 ErrorFound = NotASpecificExpression;
4041 ErrorLoc = FirstBinOp->getExprLoc();
4042 ErrorRange = FirstBinOp->getSourceRange();
4043 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
4044 NoteRange = SecondBinOp->getRHS()->getSourceRange();
4045 }
4046 }
4047 }
4048 }
4049 } else {
4050 NoteLoc = ErrorLoc = Body->getLocStart();
4051 NoteRange = ErrorRange =
4052 SourceRange(Body->getLocStart(), Body->getLocStart());
4053 ErrorFound = NotTwoSubstatements;
4054 }
4055 } else {
4056 NoteLoc = ErrorLoc = Body->getLocStart();
4057 NoteRange = ErrorRange =
4058 SourceRange(Body->getLocStart(), Body->getLocStart());
4059 ErrorFound = NotACompoundStatement;
4060 }
4061 if (ErrorFound != NoError) {
4062 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
4063 << ErrorRange;
4064 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4065 return StmtError();
4066 } else if (CurContext->isDependentContext()) {
4067 UE = V = E = X = nullptr;
4068 }
Alexey Bataev459dec02014-07-24 06:46:57 +00004069 }
Alexey Bataevdea47612014-07-23 07:46:59 +00004070 }
Alexey Bataev0162e452014-07-22 10:10:35 +00004071
4072 getCurFunction()->setHasBranchProtectedScope();
4073
Alexey Bataev62cec442014-11-18 10:14:22 +00004074 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00004075 X, V, E, UE, IsXLHSInRHSPart,
4076 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00004077}
4078
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004079StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
4080 Stmt *AStmt,
4081 SourceLocation StartLoc,
4082 SourceLocation EndLoc) {
4083 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4084
Alexey Bataev13314bf2014-10-09 04:18:56 +00004085 // OpenMP [2.16, Nesting of Regions]
4086 // If specified, a teams construct must be contained within a target
4087 // construct. That target construct must contain no statements or directives
4088 // outside of the teams construct.
4089 if (DSAStack->hasInnerTeamsRegion()) {
4090 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
4091 bool OMPTeamsFound = true;
4092 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
4093 auto I = CS->body_begin();
4094 while (I != CS->body_end()) {
4095 auto OED = dyn_cast<OMPExecutableDirective>(*I);
4096 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
4097 OMPTeamsFound = false;
4098 break;
4099 }
4100 ++I;
4101 }
4102 assert(I != CS->body_end() && "Not found statement");
4103 S = *I;
4104 }
4105 if (!OMPTeamsFound) {
4106 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
4107 Diag(DSAStack->getInnerTeamsRegionLoc(),
4108 diag::note_omp_nested_teams_construct_here);
4109 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
4110 << isa<OMPExecutableDirective>(S);
4111 return StmtError();
4112 }
4113 }
4114
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004115 getCurFunction()->setHasBranchProtectedScope();
4116
4117 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4118}
4119
Alexey Bataev13314bf2014-10-09 04:18:56 +00004120StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
4121 Stmt *AStmt, SourceLocation StartLoc,
4122 SourceLocation EndLoc) {
4123 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4124 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4125 // 1.2.2 OpenMP Language Terminology
4126 // Structured block - An executable statement with a single entry at the
4127 // top and a single exit at the bottom.
4128 // The point of exit cannot be a branch out of the structured block.
4129 // longjmp() and throw() must not violate the entry/exit criteria.
4130 CS->getCapturedDecl()->setNothrow();
4131
4132 getCurFunction()->setHasBranchProtectedScope();
4133
4134 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4135}
4136
Alexey Bataeved09d242014-05-28 05:53:51 +00004137OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004138 SourceLocation StartLoc,
4139 SourceLocation LParenLoc,
4140 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004141 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004142 switch (Kind) {
4143 case OMPC_if:
4144 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
4145 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00004146 case OMPC_final:
4147 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
4148 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00004149 case OMPC_num_threads:
4150 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
4151 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004152 case OMPC_safelen:
4153 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
4154 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00004155 case OMPC_collapse:
4156 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
4157 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004158 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004159 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004160 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004161 case OMPC_private:
4162 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004163 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004164 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004165 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004166 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004167 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004168 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004169 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004170 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004171 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004172 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004173 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004174 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004175 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004176 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004177 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004178 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004179 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004180 case OMPC_seq_cst:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004181 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004182 llvm_unreachable("Clause is not allowed.");
4183 }
4184 return Res;
4185}
4186
Alexey Bataeved09d242014-05-28 05:53:51 +00004187OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004188 SourceLocation LParenLoc,
4189 SourceLocation EndLoc) {
4190 Expr *ValExpr = Condition;
4191 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4192 !Condition->isInstantiationDependent() &&
4193 !Condition->containsUnexpandedParameterPack()) {
4194 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00004195 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004196 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004197 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004198
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004199 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004200 }
4201
4202 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4203}
4204
Alexey Bataev3778b602014-07-17 07:32:53 +00004205OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
4206 SourceLocation StartLoc,
4207 SourceLocation LParenLoc,
4208 SourceLocation EndLoc) {
4209 Expr *ValExpr = Condition;
4210 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4211 !Condition->isInstantiationDependent() &&
4212 !Condition->containsUnexpandedParameterPack()) {
4213 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4214 Condition->getExprLoc(), Condition);
4215 if (Val.isInvalid())
4216 return nullptr;
4217
4218 ValExpr = Val.get();
4219 }
4220
4221 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4222}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004223ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
4224 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004225 if (!Op)
4226 return ExprError();
4227
4228 class IntConvertDiagnoser : public ICEConvertDiagnoser {
4229 public:
4230 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00004231 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00004232 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
4233 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004234 return S.Diag(Loc, diag::err_omp_not_integral) << T;
4235 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004236 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4237 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004238 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
4239 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004240 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4241 QualType T,
4242 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004243 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
4244 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004245 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4246 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004247 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004248 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004249 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004250 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4251 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004252 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
4253 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004254 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4255 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004256 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004257 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004258 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004259 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
4260 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004261 llvm_unreachable("conversion functions are permitted");
4262 }
4263 } ConvertDiagnoser;
4264 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
4265}
4266
4267OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
4268 SourceLocation StartLoc,
4269 SourceLocation LParenLoc,
4270 SourceLocation EndLoc) {
4271 Expr *ValExpr = NumThreads;
4272 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
Alexey Bataev568a8332014-03-06 06:15:19 +00004273 !NumThreads->containsUnexpandedParameterPack()) {
4274 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
4275 ExprResult Val =
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004276 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
Alexey Bataev568a8332014-03-06 06:15:19 +00004277 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004278 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004279
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004280 ValExpr = Val.get();
Alexey Bataev568a8332014-03-06 06:15:19 +00004281
4282 // OpenMP [2.5, Restrictions]
4283 // The num_threads expression must evaluate to a positive integer value.
4284 llvm::APSInt Result;
Alexey Bataeved09d242014-05-28 05:53:51 +00004285 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
4286 !Result.isStrictlyPositive()) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004287 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
4288 << "num_threads" << NumThreads->getSourceRange();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004289 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004290 }
4291 }
4292
Alexey Bataeved09d242014-05-28 05:53:51 +00004293 return new (Context)
4294 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00004295}
4296
Alexey Bataev62c87d22014-03-21 04:51:18 +00004297ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
4298 OpenMPClauseKind CKind) {
4299 if (!E)
4300 return ExprError();
4301 if (E->isValueDependent() || E->isTypeDependent() ||
4302 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004303 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004304 llvm::APSInt Result;
4305 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
4306 if (ICE.isInvalid())
4307 return ExprError();
4308 if (!Result.isStrictlyPositive()) {
4309 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
4310 << getOpenMPClauseName(CKind) << E->getSourceRange();
4311 return ExprError();
4312 }
Alexander Musman09184fe2014-09-30 05:29:28 +00004313 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
4314 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
4315 << E->getSourceRange();
4316 return ExprError();
4317 }
Alexey Bataev9c821032015-04-30 04:23:23 +00004318 if (CKind == OMPC_collapse) {
4319 DSAStack->setCollapseNumber(Result.getExtValue());
4320 }
Alexey Bataev62c87d22014-03-21 04:51:18 +00004321 return ICE;
4322}
4323
4324OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
4325 SourceLocation LParenLoc,
4326 SourceLocation EndLoc) {
4327 // OpenMP [2.8.1, simd construct, Description]
4328 // The parameter of the safelen clause must be a constant
4329 // positive integer expression.
4330 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
4331 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004332 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004333 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004334 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00004335}
4336
Alexander Musman64d33f12014-06-04 07:53:32 +00004337OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
4338 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00004339 SourceLocation LParenLoc,
4340 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00004341 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004342 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00004343 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004344 // The parameter of the collapse clause must be a constant
4345 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00004346 ExprResult NumForLoopsResult =
4347 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
4348 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00004349 return nullptr;
4350 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00004351 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00004352}
4353
Alexey Bataeved09d242014-05-28 05:53:51 +00004354OMPClause *Sema::ActOnOpenMPSimpleClause(
4355 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
4356 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004357 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004358 switch (Kind) {
4359 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004360 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00004361 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
4362 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004363 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004364 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00004365 Res = ActOnOpenMPProcBindClause(
4366 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
4367 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004368 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004369 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004370 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004371 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004372 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004373 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004374 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004375 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004376 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004377 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004378 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004379 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004380 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004381 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004382 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004383 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004384 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004385 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004386 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004387 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004388 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004389 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004390 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004391 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004392 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004393 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004394 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004395 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004396 llvm_unreachable("Clause is not allowed.");
4397 }
4398 return Res;
4399}
4400
4401OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
4402 SourceLocation KindKwLoc,
4403 SourceLocation StartLoc,
4404 SourceLocation LParenLoc,
4405 SourceLocation EndLoc) {
4406 if (Kind == OMPC_DEFAULT_unknown) {
4407 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004408 static_assert(OMPC_DEFAULT_unknown > 0,
4409 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00004410 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004411 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004412 Values += "'";
4413 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
4414 Values += "'";
4415 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004416 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004417 Values += " or ";
4418 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004419 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004420 break;
4421 default:
4422 Values += Sep;
4423 break;
4424 }
4425 }
4426 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004427 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004428 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004429 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004430 switch (Kind) {
4431 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004432 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004433 break;
4434 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004435 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004436 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004437 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004438 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00004439 break;
4440 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004441 return new (Context)
4442 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004443}
4444
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004445OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
4446 SourceLocation KindKwLoc,
4447 SourceLocation StartLoc,
4448 SourceLocation LParenLoc,
4449 SourceLocation EndLoc) {
4450 if (Kind == OMPC_PROC_BIND_unknown) {
4451 std::string Values;
4452 std::string Sep(", ");
4453 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
4454 Values += "'";
4455 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
4456 Values += "'";
4457 switch (i) {
4458 case OMPC_PROC_BIND_unknown - 2:
4459 Values += " or ";
4460 break;
4461 case OMPC_PROC_BIND_unknown - 1:
4462 break;
4463 default:
4464 Values += Sep;
4465 break;
4466 }
4467 }
4468 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004469 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004470 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004471 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004472 return new (Context)
4473 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004474}
4475
Alexey Bataev56dafe82014-06-20 07:16:17 +00004476OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
4477 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
4478 SourceLocation StartLoc, SourceLocation LParenLoc,
4479 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
4480 SourceLocation EndLoc) {
4481 OMPClause *Res = nullptr;
4482 switch (Kind) {
4483 case OMPC_schedule:
4484 Res = ActOnOpenMPScheduleClause(
4485 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
4486 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
4487 break;
4488 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004489 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004490 case OMPC_num_threads:
4491 case OMPC_safelen:
4492 case OMPC_collapse:
4493 case OMPC_default:
4494 case OMPC_proc_bind:
4495 case OMPC_private:
4496 case OMPC_firstprivate:
4497 case OMPC_lastprivate:
4498 case OMPC_shared:
4499 case OMPC_reduction:
4500 case OMPC_linear:
4501 case OMPC_aligned:
4502 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004503 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004504 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004505 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004506 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004507 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004508 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004509 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004510 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004511 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004512 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004513 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004514 case OMPC_seq_cst:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004515 case OMPC_unknown:
4516 llvm_unreachable("Clause is not allowed.");
4517 }
4518 return Res;
4519}
4520
4521OMPClause *Sema::ActOnOpenMPScheduleClause(
4522 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
4523 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
4524 SourceLocation EndLoc) {
4525 if (Kind == OMPC_SCHEDULE_unknown) {
4526 std::string Values;
4527 std::string Sep(", ");
4528 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
4529 Values += "'";
4530 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
4531 Values += "'";
4532 switch (i) {
4533 case OMPC_SCHEDULE_unknown - 2:
4534 Values += " or ";
4535 break;
4536 case OMPC_SCHEDULE_unknown - 1:
4537 break;
4538 default:
4539 Values += Sep;
4540 break;
4541 }
4542 }
4543 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
4544 << Values << getOpenMPClauseName(OMPC_schedule);
4545 return nullptr;
4546 }
4547 Expr *ValExpr = ChunkSize;
Alexey Bataev040d5402015-05-12 08:35:28 +00004548 Expr *HelperValExpr = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00004549 if (ChunkSize) {
4550 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
4551 !ChunkSize->isInstantiationDependent() &&
4552 !ChunkSize->containsUnexpandedParameterPack()) {
4553 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
4554 ExprResult Val =
4555 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
4556 if (Val.isInvalid())
4557 return nullptr;
4558
4559 ValExpr = Val.get();
4560
4561 // OpenMP [2.7.1, Restrictions]
4562 // chunk_size must be a loop invariant integer expression with a positive
4563 // value.
4564 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00004565 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
4566 if (Result.isSigned() && !Result.isStrictlyPositive()) {
4567 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
4568 << "schedule" << ChunkSize->getSourceRange();
4569 return nullptr;
4570 }
4571 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
4572 auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
4573 ChunkSize->getType(), ".chunk.");
4574 auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
4575 ChunkSize->getExprLoc(),
4576 /*RefersToCapture=*/true);
4577 HelperValExpr = ImpVarRef;
Alexey Bataev56dafe82014-06-20 07:16:17 +00004578 }
4579 }
4580 }
4581
4582 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
Alexey Bataev040d5402015-05-12 08:35:28 +00004583 EndLoc, Kind, ValExpr, HelperValExpr);
Alexey Bataev56dafe82014-06-20 07:16:17 +00004584}
4585
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004586OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
4587 SourceLocation StartLoc,
4588 SourceLocation EndLoc) {
4589 OMPClause *Res = nullptr;
4590 switch (Kind) {
4591 case OMPC_ordered:
4592 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
4593 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00004594 case OMPC_nowait:
4595 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
4596 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004597 case OMPC_untied:
4598 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
4599 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004600 case OMPC_mergeable:
4601 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
4602 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004603 case OMPC_read:
4604 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
4605 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00004606 case OMPC_write:
4607 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
4608 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004609 case OMPC_update:
4610 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
4611 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00004612 case OMPC_capture:
4613 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
4614 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004615 case OMPC_seq_cst:
4616 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
4617 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004618 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004619 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004620 case OMPC_num_threads:
4621 case OMPC_safelen:
4622 case OMPC_collapse:
4623 case OMPC_schedule:
4624 case OMPC_private:
4625 case OMPC_firstprivate:
4626 case OMPC_lastprivate:
4627 case OMPC_shared:
4628 case OMPC_reduction:
4629 case OMPC_linear:
4630 case OMPC_aligned:
4631 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004632 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004633 case OMPC_default:
4634 case OMPC_proc_bind:
4635 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004636 case OMPC_flush:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004637 case OMPC_unknown:
4638 llvm_unreachable("Clause is not allowed.");
4639 }
4640 return Res;
4641}
4642
4643OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
4644 SourceLocation EndLoc) {
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004645 DSAStack->setOrderedRegion();
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004646 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
4647}
4648
Alexey Bataev236070f2014-06-20 11:19:47 +00004649OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
4650 SourceLocation EndLoc) {
4651 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
4652}
4653
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004654OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
4655 SourceLocation EndLoc) {
4656 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
4657}
4658
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004659OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
4660 SourceLocation EndLoc) {
4661 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
4662}
4663
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004664OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
4665 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004666 return new (Context) OMPReadClause(StartLoc, EndLoc);
4667}
4668
Alexey Bataevdea47612014-07-23 07:46:59 +00004669OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
4670 SourceLocation EndLoc) {
4671 return new (Context) OMPWriteClause(StartLoc, EndLoc);
4672}
4673
Alexey Bataev67a4f222014-07-23 10:25:33 +00004674OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
4675 SourceLocation EndLoc) {
4676 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
4677}
4678
Alexey Bataev459dec02014-07-24 06:46:57 +00004679OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
4680 SourceLocation EndLoc) {
4681 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
4682}
4683
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004684OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
4685 SourceLocation EndLoc) {
4686 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
4687}
4688
Alexey Bataevc5e02582014-06-16 07:08:35 +00004689OMPClause *Sema::ActOnOpenMPVarListClause(
4690 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
4691 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
4692 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
4693 const DeclarationNameInfo &ReductionId) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004694 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004695 switch (Kind) {
4696 case OMPC_private:
4697 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4698 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004699 case OMPC_firstprivate:
4700 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4701 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00004702 case OMPC_lastprivate:
4703 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4704 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00004705 case OMPC_shared:
4706 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
4707 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00004708 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00004709 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
4710 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00004711 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00004712 case OMPC_linear:
4713 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
4714 ColonLoc, EndLoc);
4715 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004716 case OMPC_aligned:
4717 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
4718 ColonLoc, EndLoc);
4719 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004720 case OMPC_copyin:
4721 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
4722 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00004723 case OMPC_copyprivate:
4724 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4725 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004726 case OMPC_flush:
4727 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4728 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004729 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004730 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004731 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004732 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004733 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004734 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004735 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004736 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004737 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004738 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004739 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004740 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004741 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004742 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004743 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004744 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004745 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004746 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004747 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004748 llvm_unreachable("Clause is not allowed.");
4749 }
4750 return Res;
4751}
4752
4753OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
4754 SourceLocation StartLoc,
4755 SourceLocation LParenLoc,
4756 SourceLocation EndLoc) {
4757 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00004758 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00004759 for (auto &RefExpr : VarList) {
4760 assert(RefExpr && "NULL expr in OpenMP private clause.");
4761 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004762 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004763 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004764 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004765 continue;
4766 }
4767
Alexey Bataeved09d242014-05-28 05:53:51 +00004768 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004769 // OpenMP [2.1, C/C++]
4770 // A list item is a variable name.
4771 // OpenMP [2.9.3.3, Restrictions, p.1]
4772 // A variable that is part of another variable (as an array or
4773 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004774 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004775 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004776 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004777 continue;
4778 }
4779 Decl *D = DE->getDecl();
4780 VarDecl *VD = cast<VarDecl>(D);
4781
4782 QualType Type = VD->getType();
4783 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4784 // It will be analyzed later.
4785 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004786 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004787 continue;
4788 }
4789
4790 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4791 // A variable that appears in a private clause must not have an incomplete
4792 // type or a reference type.
4793 if (RequireCompleteType(ELoc, Type,
4794 diag::err_omp_private_incomplete_type)) {
4795 continue;
4796 }
4797 if (Type->isReferenceType()) {
4798 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00004799 << getOpenMPClauseName(OMPC_private) << Type;
4800 bool IsDecl =
4801 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4802 Diag(VD->getLocation(),
4803 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4804 << VD;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004805 continue;
4806 }
4807
Alexey Bataev758e55e2013-09-06 18:03:48 +00004808 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4809 // in a Construct]
4810 // Variables with the predetermined data-sharing attributes may not be
4811 // listed in data-sharing attributes clauses, except for the cases
4812 // listed below. For these exceptions only, listing a predetermined
4813 // variable in a data-sharing attribute clause is allowed and overrides
4814 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004815 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004816 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004817 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4818 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004819 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004820 continue;
4821 }
4822
Alexey Bataevccb59ec2015-05-19 08:44:56 +00004823 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00004824 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataevccb59ec2015-05-19 08:44:56 +00004825 DSAStack->getCurrentDirective() == OMPD_task) {
4826 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
4827 << getOpenMPClauseName(OMPC_private) << Type
4828 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4829 bool IsDecl =
4830 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4831 Diag(VD->getLocation(),
4832 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4833 << VD;
4834 continue;
4835 }
4836
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004837 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
4838 // A variable of class type (or array thereof) that appears in a private
4839 // clause requires an accessible, unambiguous default constructor for the
4840 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00004841 // Generate helper private variable and initialize it with the default
4842 // value. The address of the original variable is replaced by the address of
4843 // the new private variable in CodeGen. This new variable is not added to
4844 // IdResolver, so the code in the OpenMP region uses original variable for
4845 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004846 Type = Type.getUnqualifiedType();
4847 auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName());
Alexey Bataev39f915b82015-05-08 10:41:21 +00004848 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004849 if (VDPrivate->isInvalidDecl())
4850 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004851 auto VDPrivateRefExpr = buildDeclRefExpr(
4852 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev03b340a2014-10-21 03:16:40 +00004853
Alexey Bataev758e55e2013-09-06 18:03:48 +00004854 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004855 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004856 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004857 }
4858
Alexey Bataeved09d242014-05-28 05:53:51 +00004859 if (Vars.empty())
4860 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004861
Alexey Bataev03b340a2014-10-21 03:16:40 +00004862 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
4863 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004864}
4865
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004866namespace {
4867class DiagsUninitializedSeveretyRAII {
4868private:
4869 DiagnosticsEngine &Diags;
4870 SourceLocation SavedLoc;
4871 bool IsIgnored;
4872
4873public:
4874 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
4875 bool IsIgnored)
4876 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
4877 if (!IsIgnored) {
4878 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
4879 /*Map*/ diag::Severity::Ignored, Loc);
4880 }
4881 }
4882 ~DiagsUninitializedSeveretyRAII() {
4883 if (!IsIgnored)
4884 Diags.popMappings(SavedLoc);
4885 }
4886};
4887}
4888
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004889OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
4890 SourceLocation StartLoc,
4891 SourceLocation LParenLoc,
4892 SourceLocation EndLoc) {
4893 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004894 SmallVector<Expr *, 8> PrivateCopies;
4895 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004896 bool IsImplicitClause =
4897 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
4898 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
4899
Alexey Bataeved09d242014-05-28 05:53:51 +00004900 for (auto &RefExpr : VarList) {
4901 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
4902 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004903 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004904 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004905 PrivateCopies.push_back(nullptr);
4906 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004907 continue;
4908 }
4909
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004910 SourceLocation ELoc =
4911 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004912 // OpenMP [2.1, C/C++]
4913 // A list item is a variable name.
4914 // OpenMP [2.9.3.3, Restrictions, p.1]
4915 // A variable that is part of another variable (as an array or
4916 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004917 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004918 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004919 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004920 continue;
4921 }
4922 Decl *D = DE->getDecl();
4923 VarDecl *VD = cast<VarDecl>(D);
4924
4925 QualType Type = VD->getType();
4926 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4927 // It will be analyzed later.
4928 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004929 PrivateCopies.push_back(nullptr);
4930 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004931 continue;
4932 }
4933
4934 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4935 // A variable that appears in a private clause must not have an incomplete
4936 // type or a reference type.
4937 if (RequireCompleteType(ELoc, Type,
4938 diag::err_omp_firstprivate_incomplete_type)) {
4939 continue;
4940 }
4941 if (Type->isReferenceType()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004942 if (IsImplicitClause) {
4943 Diag(ImplicitClauseLoc,
4944 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
4945 << Type;
4946 Diag(RefExpr->getExprLoc(), diag::note_used_here);
4947 } else {
4948 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4949 << getOpenMPClauseName(OMPC_firstprivate) << Type;
4950 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004951 bool IsDecl =
4952 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4953 Diag(VD->getLocation(),
4954 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4955 << VD;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004956 continue;
4957 }
4958
4959 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
4960 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004961 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004962 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004963 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004964
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004965 // If an implicit firstprivate variable found it was checked already.
4966 if (!IsImplicitClause) {
4967 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004968 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004969 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
4970 // A list item that specifies a given variable may not appear in more
4971 // than one clause on the same directive, except that a variable may be
4972 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004973 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00004974 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004975 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004976 << getOpenMPClauseName(DVar.CKind)
4977 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004978 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004979 continue;
4980 }
4981
4982 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4983 // in a Construct]
4984 // Variables with the predetermined data-sharing attributes may not be
4985 // listed in data-sharing attributes clauses, except for the cases
4986 // listed below. For these exceptions only, listing a predetermined
4987 // variable in a data-sharing attribute clause is allowed and overrides
4988 // the variable's predetermined data-sharing attributes.
4989 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4990 // in a Construct, C/C++, p.2]
4991 // Variables with const-qualified type having no mutable member may be
4992 // listed in a firstprivate clause, even if they are static data members.
4993 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
4994 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
4995 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004996 << getOpenMPClauseName(DVar.CKind)
4997 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004998 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004999 continue;
5000 }
5001
Alexey Bataevf29276e2014-06-18 04:14:57 +00005002 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005003 // OpenMP [2.9.3.4, Restrictions, p.2]
5004 // A list item that is private within a parallel region must not appear
5005 // in a firstprivate clause on a worksharing construct if any of the
5006 // worksharing regions arising from the worksharing construct ever bind
5007 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00005008 if (isOpenMPWorksharingDirective(CurrDir) &&
5009 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005010 DVar = DSAStack->getImplicitDSA(VD, true);
5011 if (DVar.CKind != OMPC_shared &&
5012 (isOpenMPParallelDirective(DVar.DKind) ||
5013 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00005014 Diag(ELoc, diag::err_omp_required_access)
5015 << getOpenMPClauseName(OMPC_firstprivate)
5016 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005017 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005018 continue;
5019 }
5020 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005021 // OpenMP [2.9.3.4, Restrictions, p.3]
5022 // A list item that appears in a reduction clause of a parallel construct
5023 // must not appear in a firstprivate clause on a worksharing or task
5024 // construct if any of the worksharing or task regions arising from the
5025 // worksharing or task construct ever bind to any of the parallel regions
5026 // arising from the parallel construct.
5027 // OpenMP [2.9.3.4, Restrictions, p.4]
5028 // A list item that appears in a reduction clause in worksharing
5029 // construct must not appear in a firstprivate clause in a task construct
5030 // encountered during execution of any of the worksharing regions arising
5031 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005032 if (CurrDir == OMPD_task) {
5033 DVar =
5034 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
5035 [](OpenMPDirectiveKind K) -> bool {
5036 return isOpenMPParallelDirective(K) ||
5037 isOpenMPWorksharingDirective(K);
5038 },
5039 false);
5040 if (DVar.CKind == OMPC_reduction &&
5041 (isOpenMPParallelDirective(DVar.DKind) ||
5042 isOpenMPWorksharingDirective(DVar.DKind))) {
5043 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
5044 << getOpenMPDirectiveName(DVar.DKind);
5045 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5046 continue;
5047 }
5048 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005049 }
5050
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005051 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00005052 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005053 DSAStack->getCurrentDirective() == OMPD_task) {
5054 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5055 << getOpenMPClauseName(OMPC_firstprivate) << Type
5056 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5057 bool IsDecl =
5058 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5059 Diag(VD->getLocation(),
5060 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5061 << VD;
5062 continue;
5063 }
5064
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005065 Type = Type.getUnqualifiedType();
5066 auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName());
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005067 // Generate helper private variable and initialize it with the value of the
5068 // original variable. The address of the original variable is replaced by
5069 // the address of the new private variable in the CodeGen. This new variable
5070 // is not added to IdResolver, so the code in the OpenMP region uses
5071 // original variable for proper diagnostics and variable capturing.
5072 Expr *VDInitRefExpr = nullptr;
5073 // For arrays generate initializer for single element and replace it by the
5074 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005075 if (Type->isArrayType()) {
5076 auto VDInit =
5077 buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
5078 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005079 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005080 ElemType = ElemType.getUnqualifiedType();
5081 auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
5082 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00005083 InitializedEntity Entity =
5084 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005085 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
5086
5087 InitializationSequence InitSeq(*this, Entity, Kind, Init);
5088 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
5089 if (Result.isInvalid())
5090 VDPrivate->setInvalidDecl();
5091 else
5092 VDPrivate->setInit(Result.getAs<Expr>());
5093 } else {
Alexey Bataev69c62a92015-04-15 04:52:20 +00005094 auto *VDInit =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005095 buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005096 VDInitRefExpr =
5097 buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00005098 AddInitializerToDecl(VDPrivate,
5099 DefaultLvalueConversion(VDInitRefExpr).get(),
5100 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005101 }
5102 if (VDPrivate->isInvalidDecl()) {
5103 if (IsImplicitClause) {
5104 Diag(DE->getExprLoc(),
5105 diag::note_omp_task_predetermined_firstprivate_here);
5106 }
5107 continue;
5108 }
5109 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005110 auto VDPrivateRefExpr = buildDeclRefExpr(
5111 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005112 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
5113 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005114 PrivateCopies.push_back(VDPrivateRefExpr);
5115 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005116 }
5117
Alexey Bataeved09d242014-05-28 05:53:51 +00005118 if (Vars.empty())
5119 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005120
5121 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005122 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005123}
5124
Alexander Musman1bb328c2014-06-04 13:06:39 +00005125OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
5126 SourceLocation StartLoc,
5127 SourceLocation LParenLoc,
5128 SourceLocation EndLoc) {
5129 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00005130 SmallVector<Expr *, 8> SrcExprs;
5131 SmallVector<Expr *, 8> DstExprs;
5132 SmallVector<Expr *, 8> AssignmentOps;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005133 for (auto &RefExpr : VarList) {
5134 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
5135 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5136 // It will be analyzed later.
5137 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00005138 SrcExprs.push_back(nullptr);
5139 DstExprs.push_back(nullptr);
5140 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005141 continue;
5142 }
5143
5144 SourceLocation ELoc = RefExpr->getExprLoc();
5145 // OpenMP [2.1, C/C++]
5146 // A list item is a variable name.
5147 // OpenMP [2.14.3.5, Restrictions, p.1]
5148 // A variable that is part of another variable (as an array or structure
5149 // element) cannot appear in a lastprivate clause.
5150 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5151 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5152 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5153 continue;
5154 }
5155 Decl *D = DE->getDecl();
5156 VarDecl *VD = cast<VarDecl>(D);
5157
5158 QualType Type = VD->getType();
5159 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5160 // It will be analyzed later.
5161 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005162 SrcExprs.push_back(nullptr);
5163 DstExprs.push_back(nullptr);
5164 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005165 continue;
5166 }
5167
5168 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
5169 // A variable that appears in a lastprivate clause must not have an
5170 // incomplete type or a reference type.
5171 if (RequireCompleteType(ELoc, Type,
5172 diag::err_omp_lastprivate_incomplete_type)) {
5173 continue;
5174 }
5175 if (Type->isReferenceType()) {
5176 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5177 << getOpenMPClauseName(OMPC_lastprivate) << Type;
5178 bool IsDecl =
5179 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5180 Diag(VD->getLocation(),
5181 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5182 << VD;
5183 continue;
5184 }
5185
5186 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5187 // in a Construct]
5188 // Variables with the predetermined data-sharing attributes may not be
5189 // listed in data-sharing attributes clauses, except for the cases
5190 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005191 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005192 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
5193 DVar.CKind != OMPC_firstprivate &&
5194 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5195 Diag(ELoc, diag::err_omp_wrong_dsa)
5196 << getOpenMPClauseName(DVar.CKind)
5197 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005198 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005199 continue;
5200 }
5201
Alexey Bataevf29276e2014-06-18 04:14:57 +00005202 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5203 // OpenMP [2.14.3.5, Restrictions, p.2]
5204 // A list item that is private within a parallel region, or that appears in
5205 // the reduction clause of a parallel construct, must not appear in a
5206 // lastprivate clause on a worksharing construct if any of the corresponding
5207 // worksharing regions ever binds to any of the corresponding parallel
5208 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005209 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00005210 if (isOpenMPWorksharingDirective(CurrDir) &&
5211 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005212 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005213 if (DVar.CKind != OMPC_shared) {
5214 Diag(ELoc, diag::err_omp_required_access)
5215 << getOpenMPClauseName(OMPC_lastprivate)
5216 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005217 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005218 continue;
5219 }
5220 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00005221 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00005222 // A variable of class type (or array thereof) that appears in a
5223 // lastprivate clause requires an accessible, unambiguous default
5224 // constructor for the class type, unless the list item is also specified
5225 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00005226 // A variable of class type (or array thereof) that appears in a
5227 // lastprivate clause requires an accessible, unambiguous copy assignment
5228 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00005229 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00005230 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
Alexey Bataev38e89532015-04-16 04:54:05 +00005231 Type.getUnqualifiedType(), ".lastprivate.src");
Alexey Bataev39f915b82015-05-08 10:41:21 +00005232 auto *PseudoSrcExpr = buildDeclRefExpr(
5233 *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00005234 auto *DstVD =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005235 buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst");
Alexey Bataev38e89532015-04-16 04:54:05 +00005236 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005237 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00005238 // For arrays generate assignment operation for single element and replace
5239 // it by the original array element in CodeGen.
5240 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
5241 PseudoDstExpr, PseudoSrcExpr);
5242 if (AssignmentOp.isInvalid())
5243 continue;
5244 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
5245 /*DiscardedValue=*/true);
5246 if (AssignmentOp.isInvalid())
5247 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005248
Alexey Bataev39f915b82015-05-08 10:41:21 +00005249 if (TopDVar.CKind != OMPC_firstprivate)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005250 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005251 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005252 SrcExprs.push_back(PseudoSrcExpr);
5253 DstExprs.push_back(PseudoDstExpr);
5254 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00005255 }
5256
5257 if (Vars.empty())
5258 return nullptr;
5259
5260 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00005261 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005262}
5263
Alexey Bataev758e55e2013-09-06 18:03:48 +00005264OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
5265 SourceLocation StartLoc,
5266 SourceLocation LParenLoc,
5267 SourceLocation EndLoc) {
5268 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00005269 for (auto &RefExpr : VarList) {
5270 assert(RefExpr && "NULL expr in OpenMP shared clause.");
5271 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00005272 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005273 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005274 continue;
5275 }
5276
Alexey Bataeved09d242014-05-28 05:53:51 +00005277 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005278 // OpenMP [2.1, C/C++]
5279 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00005280 // OpenMP [2.14.3.2, Restrictions, p.1]
5281 // A variable that is part of another variable (as an array or structure
5282 // element) cannot appear in a shared unless it is a static data member
5283 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00005284 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005285 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005286 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005287 continue;
5288 }
5289 Decl *D = DE->getDecl();
5290 VarDecl *VD = cast<VarDecl>(D);
5291
5292 QualType Type = VD->getType();
5293 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5294 // It will be analyzed later.
5295 Vars.push_back(DE);
5296 continue;
5297 }
5298
5299 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5300 // in a Construct]
5301 // Variables with the predetermined data-sharing attributes may not be
5302 // listed in data-sharing attributes clauses, except for the cases
5303 // listed below. For these exceptions only, listing a predetermined
5304 // variable in a data-sharing attribute clause is allowed and overrides
5305 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005306 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00005307 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
5308 DVar.RefExpr) {
5309 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5310 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005311 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005312 continue;
5313 }
5314
5315 DSAStack->addDSA(VD, DE, OMPC_shared);
5316 Vars.push_back(DE);
5317 }
5318
Alexey Bataeved09d242014-05-28 05:53:51 +00005319 if (Vars.empty())
5320 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00005321
5322 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5323}
5324
Alexey Bataevc5e02582014-06-16 07:08:35 +00005325namespace {
5326class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
5327 DSAStackTy *Stack;
5328
5329public:
5330 bool VisitDeclRefExpr(DeclRefExpr *E) {
5331 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005332 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005333 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
5334 return false;
5335 if (DVar.CKind != OMPC_unknown)
5336 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00005337 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005338 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005339 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00005340 return true;
5341 return false;
5342 }
5343 return false;
5344 }
5345 bool VisitStmt(Stmt *S) {
5346 for (auto Child : S->children()) {
5347 if (Child && Visit(Child))
5348 return true;
5349 }
5350 return false;
5351 }
Alexey Bataev23b69422014-06-18 07:08:49 +00005352 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00005353};
Alexey Bataev23b69422014-06-18 07:08:49 +00005354} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00005355
5356OMPClause *Sema::ActOnOpenMPReductionClause(
5357 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
5358 SourceLocation ColonLoc, SourceLocation EndLoc,
5359 CXXScopeSpec &ReductionIdScopeSpec,
5360 const DeclarationNameInfo &ReductionId) {
5361 // TODO: Allow scope specification search when 'declare reduction' is
5362 // supported.
5363 assert(ReductionIdScopeSpec.isEmpty() &&
5364 "No support for scoped reduction identifiers yet.");
5365
5366 auto DN = ReductionId.getName();
5367 auto OOK = DN.getCXXOverloadedOperator();
5368 BinaryOperatorKind BOK = BO_Comma;
5369
5370 // OpenMP [2.14.3.6, reduction clause]
5371 // C
5372 // reduction-identifier is either an identifier or one of the following
5373 // operators: +, -, *, &, |, ^, && and ||
5374 // C++
5375 // reduction-identifier is either an id-expression or one of the following
5376 // operators: +, -, *, &, |, ^, && and ||
5377 // FIXME: Only 'min' and 'max' identifiers are supported for now.
5378 switch (OOK) {
5379 case OO_Plus:
5380 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005381 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005382 break;
5383 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005384 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005385 break;
5386 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005387 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005388 break;
5389 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005390 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005391 break;
5392 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005393 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005394 break;
5395 case OO_AmpAmp:
5396 BOK = BO_LAnd;
5397 break;
5398 case OO_PipePipe:
5399 BOK = BO_LOr;
5400 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005401 case OO_New:
5402 case OO_Delete:
5403 case OO_Array_New:
5404 case OO_Array_Delete:
5405 case OO_Slash:
5406 case OO_Percent:
5407 case OO_Tilde:
5408 case OO_Exclaim:
5409 case OO_Equal:
5410 case OO_Less:
5411 case OO_Greater:
5412 case OO_LessEqual:
5413 case OO_GreaterEqual:
5414 case OO_PlusEqual:
5415 case OO_MinusEqual:
5416 case OO_StarEqual:
5417 case OO_SlashEqual:
5418 case OO_PercentEqual:
5419 case OO_CaretEqual:
5420 case OO_AmpEqual:
5421 case OO_PipeEqual:
5422 case OO_LessLess:
5423 case OO_GreaterGreater:
5424 case OO_LessLessEqual:
5425 case OO_GreaterGreaterEqual:
5426 case OO_EqualEqual:
5427 case OO_ExclaimEqual:
5428 case OO_PlusPlus:
5429 case OO_MinusMinus:
5430 case OO_Comma:
5431 case OO_ArrowStar:
5432 case OO_Arrow:
5433 case OO_Call:
5434 case OO_Subscript:
5435 case OO_Conditional:
5436 case NUM_OVERLOADED_OPERATORS:
5437 llvm_unreachable("Unexpected reduction identifier");
5438 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005439 if (auto II = DN.getAsIdentifierInfo()) {
5440 if (II->isStr("max"))
5441 BOK = BO_GT;
5442 else if (II->isStr("min"))
5443 BOK = BO_LT;
5444 }
5445 break;
5446 }
5447 SourceRange ReductionIdRange;
5448 if (ReductionIdScopeSpec.isValid()) {
5449 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
5450 }
5451 ReductionIdRange.setEnd(ReductionId.getEndLoc());
5452 if (BOK == BO_Comma) {
5453 // Not allowed reduction identifier is found.
5454 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
5455 << ReductionIdRange;
5456 return nullptr;
5457 }
5458
5459 SmallVector<Expr *, 8> Vars;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005460 SmallVector<Expr *, 8> LHSs;
5461 SmallVector<Expr *, 8> RHSs;
5462 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005463 for (auto RefExpr : VarList) {
5464 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
5465 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5466 // It will be analyzed later.
5467 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005468 LHSs.push_back(nullptr);
5469 RHSs.push_back(nullptr);
5470 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005471 continue;
5472 }
5473
5474 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5475 RefExpr->isInstantiationDependent() ||
5476 RefExpr->containsUnexpandedParameterPack()) {
5477 // It will be analyzed later.
5478 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005479 LHSs.push_back(nullptr);
5480 RHSs.push_back(nullptr);
5481 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005482 continue;
5483 }
5484
5485 auto ELoc = RefExpr->getExprLoc();
5486 auto ERange = RefExpr->getSourceRange();
5487 // OpenMP [2.1, C/C++]
5488 // A list item is a variable or array section, subject to the restrictions
5489 // specified in Section 2.4 on page 42 and in each of the sections
5490 // describing clauses and directives for which a list appears.
5491 // OpenMP [2.14.3.3, Restrictions, p.1]
5492 // A variable that is part of another variable (as an array or
5493 // structure element) cannot appear in a private clause.
5494 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
5495 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5496 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
5497 continue;
5498 }
5499 auto D = DE->getDecl();
5500 auto VD = cast<VarDecl>(D);
5501 auto Type = VD->getType();
5502 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5503 // A variable that appears in a private clause must not have an incomplete
5504 // type or a reference type.
5505 if (RequireCompleteType(ELoc, Type,
5506 diag::err_omp_reduction_incomplete_type))
5507 continue;
5508 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5509 // Arrays may not appear in a reduction clause.
5510 if (Type.getNonReferenceType()->isArrayType()) {
5511 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
5512 bool IsDecl =
5513 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5514 Diag(VD->getLocation(),
5515 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5516 << VD;
5517 continue;
5518 }
5519 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5520 // A list item that appears in a reduction clause must not be
5521 // const-qualified.
5522 if (Type.getNonReferenceType().isConstant(Context)) {
5523 Diag(ELoc, diag::err_omp_const_variable)
5524 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
5525 bool IsDecl =
5526 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5527 Diag(VD->getLocation(),
5528 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5529 << VD;
5530 continue;
5531 }
5532 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
5533 // If a list-item is a reference type then it must bind to the same object
5534 // for all threads of the team.
5535 VarDecl *VDDef = VD->getDefinition();
5536 if (Type->isReferenceType() && VDDef) {
5537 DSARefChecker Check(DSAStack);
5538 if (Check.Visit(VDDef->getInit())) {
5539 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
5540 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
5541 continue;
5542 }
5543 }
5544 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5545 // The type of a list item that appears in a reduction clause must be valid
5546 // for the reduction-identifier. For a max or min reduction in C, the type
5547 // of the list item must be an allowed arithmetic data type: char, int,
5548 // float, double, or _Bool, possibly modified with long, short, signed, or
5549 // unsigned. For a max or min reduction in C++, the type of the list item
5550 // must be an allowed arithmetic data type: char, wchar_t, int, float,
5551 // double, or bool, possibly modified with long, short, signed, or unsigned.
5552 if ((BOK == BO_GT || BOK == BO_LT) &&
5553 !(Type->isScalarType() ||
5554 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
5555 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
5556 << getLangOpts().CPlusPlus;
5557 bool IsDecl =
5558 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5559 Diag(VD->getLocation(),
5560 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5561 << VD;
5562 continue;
5563 }
5564 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
5565 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
5566 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
5567 bool IsDecl =
5568 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5569 Diag(VD->getLocation(),
5570 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5571 << VD;
5572 continue;
5573 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00005574 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5575 // in a Construct]
5576 // Variables with the predetermined data-sharing attributes may not be
5577 // listed in data-sharing attributes clauses, except for the cases
5578 // listed below. For these exceptions only, listing a predetermined
5579 // variable in a data-sharing attribute clause is allowed and overrides
5580 // the variable's predetermined data-sharing attributes.
5581 // OpenMP [2.14.3.6, Restrictions, p.3]
5582 // Any number of reduction clauses can be specified on the directive,
5583 // but a list item can appear only once in the reduction clauses for that
5584 // directive.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005585 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005586 if (DVar.CKind == OMPC_reduction) {
5587 Diag(ELoc, diag::err_omp_once_referenced)
5588 << getOpenMPClauseName(OMPC_reduction);
5589 if (DVar.RefExpr) {
5590 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
5591 }
5592 } else if (DVar.CKind != OMPC_unknown) {
5593 Diag(ELoc, diag::err_omp_wrong_dsa)
5594 << getOpenMPClauseName(DVar.CKind)
5595 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005596 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005597 continue;
5598 }
5599
5600 // OpenMP [2.14.3.6, Restrictions, p.1]
5601 // A list item that appears in a reduction clause of a worksharing
5602 // construct must be shared in the parallel regions to which any of the
5603 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf29276e2014-06-18 04:14:57 +00005604 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataev549210e2014-06-24 04:39:47 +00005605 if (isOpenMPWorksharingDirective(CurrDir) &&
5606 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005607 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005608 if (DVar.CKind != OMPC_shared) {
5609 Diag(ELoc, diag::err_omp_required_access)
5610 << getOpenMPClauseName(OMPC_reduction)
5611 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005612 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005613 continue;
5614 }
5615 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005616 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00005617 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs");
5618 auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005619 // Add initializer for private variable.
5620 Expr *Init = nullptr;
5621 switch (BOK) {
5622 case BO_Add:
5623 case BO_Xor:
5624 case BO_Or:
5625 case BO_LOr:
5626 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
5627 if (Type->isScalarType() || Type->isAnyComplexType()) {
5628 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005629 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005630 break;
5631 case BO_Mul:
5632 case BO_LAnd:
5633 if (Type->isScalarType() || Type->isAnyComplexType()) {
5634 // '*' and '&&' reduction ops - initializer is '1'.
5635 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
5636 }
5637 break;
5638 case BO_And: {
5639 // '&' reduction op - initializer is '~0'.
5640 QualType OrigType = Type;
5641 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
5642 Type = ComplexTy->getElementType();
5643 }
5644 if (Type->isRealFloatingType()) {
5645 llvm::APFloat InitValue =
5646 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
5647 /*isIEEE=*/true);
5648 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5649 Type, ELoc);
5650 } else if (Type->isScalarType()) {
5651 auto Size = Context.getTypeSize(Type);
5652 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
5653 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
5654 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5655 }
5656 if (Init && OrigType->isAnyComplexType()) {
5657 // Init = 0xFFFF + 0xFFFFi;
5658 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
5659 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
5660 }
5661 Type = OrigType;
5662 break;
5663 }
5664 case BO_LT:
5665 case BO_GT: {
5666 // 'min' reduction op - initializer is 'Largest representable number in
5667 // the reduction list item type'.
5668 // 'max' reduction op - initializer is 'Least representable number in
5669 // the reduction list item type'.
5670 if (Type->isIntegerType() || Type->isPointerType()) {
5671 bool IsSigned = Type->hasSignedIntegerRepresentation();
5672 auto Size = Context.getTypeSize(Type);
5673 QualType IntTy =
5674 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
5675 llvm::APInt InitValue =
5676 (BOK != BO_LT)
5677 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
5678 : llvm::APInt::getMinValue(Size)
5679 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
5680 : llvm::APInt::getMaxValue(Size);
5681 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5682 if (Type->isPointerType()) {
5683 // Cast to pointer type.
5684 auto CastExpr = BuildCStyleCastExpr(
5685 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
5686 SourceLocation(), Init);
5687 if (CastExpr.isInvalid())
5688 continue;
5689 Init = CastExpr.get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005690 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005691 } else if (Type->isRealFloatingType()) {
5692 llvm::APFloat InitValue = llvm::APFloat::getLargest(
5693 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
5694 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5695 Type, ELoc);
5696 }
5697 break;
5698 }
5699 case BO_PtrMemD:
5700 case BO_PtrMemI:
5701 case BO_MulAssign:
5702 case BO_Div:
5703 case BO_Rem:
5704 case BO_Sub:
5705 case BO_Shl:
5706 case BO_Shr:
5707 case BO_LE:
5708 case BO_GE:
5709 case BO_EQ:
5710 case BO_NE:
5711 case BO_AndAssign:
5712 case BO_XorAssign:
5713 case BO_OrAssign:
5714 case BO_Assign:
5715 case BO_AddAssign:
5716 case BO_SubAssign:
5717 case BO_DivAssign:
5718 case BO_RemAssign:
5719 case BO_ShlAssign:
5720 case BO_ShrAssign:
5721 case BO_Comma:
5722 llvm_unreachable("Unexpected reduction operation");
5723 }
5724 if (Init) {
5725 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
5726 /*TypeMayContainAuto=*/false);
5727 } else {
5728 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
5729 }
5730 if (!RHSVD->hasInit()) {
5731 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
5732 << ReductionIdRange;
5733 bool IsDecl =
5734 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5735 Diag(VD->getLocation(),
5736 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5737 << VD;
5738 continue;
5739 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00005740 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
5741 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005742 ExprResult ReductionOp =
5743 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
5744 LHSDRE, RHSDRE);
5745 if (ReductionOp.isUsable()) {
Alexey Bataev69a47792015-05-07 03:54:03 +00005746 if (BOK != BO_LT && BOK != BO_GT) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005747 ReductionOp =
5748 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5749 BO_Assign, LHSDRE, ReductionOp.get());
5750 } else {
5751 auto *ConditionalOp = new (Context) ConditionalOperator(
5752 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
5753 RHSDRE, Type, VK_LValue, OK_Ordinary);
5754 ReductionOp =
5755 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5756 BO_Assign, LHSDRE, ConditionalOp);
5757 }
5758 if (ReductionOp.isUsable()) {
5759 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005760 }
5761 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005762 if (ReductionOp.isInvalid())
5763 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005764
5765 DSAStack->addDSA(VD, DE, OMPC_reduction);
5766 Vars.push_back(DE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005767 LHSs.push_back(LHSDRE);
5768 RHSs.push_back(RHSDRE);
5769 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005770 }
5771
5772 if (Vars.empty())
5773 return nullptr;
5774
5775 return OMPReductionClause::Create(
5776 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005777 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
5778 RHSs, ReductionOps);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005779}
5780
Alexander Musman8dba6642014-04-22 13:09:42 +00005781OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
5782 SourceLocation StartLoc,
5783 SourceLocation LParenLoc,
5784 SourceLocation ColonLoc,
5785 SourceLocation EndLoc) {
5786 SmallVector<Expr *, 8> Vars;
Alexander Musman3276a272015-03-21 10:12:56 +00005787 SmallVector<Expr *, 8> Inits;
Alexey Bataeved09d242014-05-28 05:53:51 +00005788 for (auto &RefExpr : VarList) {
5789 assert(RefExpr && "NULL expr in OpenMP linear clause.");
5790 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00005791 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005792 Vars.push_back(RefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00005793 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005794 continue;
5795 }
5796
5797 // OpenMP [2.14.3.7, linear clause]
5798 // A list item that appears in a linear clause is subject to the private
5799 // clause semantics described in Section 2.14.3.3 on page 159 except as
5800 // noted. In addition, the value of the new list item on each iteration
5801 // of the associated loop(s) corresponds to the value of the original
5802 // list item before entering the construct plus the logical number of
5803 // the iteration times linear-step.
5804
Alexey Bataeved09d242014-05-28 05:53:51 +00005805 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00005806 // OpenMP [2.1, C/C++]
5807 // A list item is a variable name.
5808 // OpenMP [2.14.3.3, Restrictions, p.1]
5809 // A variable that is part of another variable (as an array or
5810 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005811 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005812 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005813 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00005814 continue;
5815 }
5816
5817 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5818
5819 // OpenMP [2.14.3.7, linear clause]
5820 // A list-item cannot appear in more than one linear clause.
5821 // A list-item that appears in a linear clause cannot appear in any
5822 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005823 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00005824 if (DVar.RefExpr) {
5825 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5826 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005827 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00005828 continue;
5829 }
5830
5831 QualType QType = VD->getType();
5832 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
5833 // It will be analyzed later.
5834 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005835 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005836 continue;
5837 }
5838
5839 // A variable must not have an incomplete type or a reference type.
5840 if (RequireCompleteType(ELoc, QType,
5841 diag::err_omp_linear_incomplete_type)) {
5842 continue;
5843 }
5844 if (QType->isReferenceType()) {
5845 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5846 << getOpenMPClauseName(OMPC_linear) << QType;
5847 bool IsDecl =
5848 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5849 Diag(VD->getLocation(),
5850 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5851 << VD;
5852 continue;
5853 }
5854
5855 // A list item must not be const-qualified.
5856 if (QType.isConstant(Context)) {
5857 Diag(ELoc, diag::err_omp_const_variable)
5858 << getOpenMPClauseName(OMPC_linear);
5859 bool IsDecl =
5860 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5861 Diag(VD->getLocation(),
5862 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5863 << VD;
5864 continue;
5865 }
5866
5867 // A list item must be of integral or pointer type.
5868 QType = QType.getUnqualifiedType().getCanonicalType();
5869 const Type *Ty = QType.getTypePtrOrNull();
5870 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
5871 !Ty->isPointerType())) {
5872 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
5873 bool IsDecl =
5874 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5875 Diag(VD->getLocation(),
5876 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5877 << VD;
5878 continue;
5879 }
5880
Alexander Musman3276a272015-03-21 10:12:56 +00005881 // Build var to save initial value.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005882 VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
Alexander Musman3276a272015-03-21 10:12:56 +00005883 AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
5884 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005885 auto InitRef = buildDeclRefExpr(
5886 *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexander Musman8dba6642014-04-22 13:09:42 +00005887 DSAStack->addDSA(VD, DE, OMPC_linear);
5888 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005889 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00005890 }
5891
5892 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005893 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005894
5895 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00005896 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005897 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5898 !Step->isInstantiationDependent() &&
5899 !Step->containsUnexpandedParameterPack()) {
5900 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005901 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00005902 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005903 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005904 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00005905
Alexander Musman3276a272015-03-21 10:12:56 +00005906 // Build var to save the step value.
5907 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005908 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00005909 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005910 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00005911 ExprResult CalcStep =
5912 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
5913
Alexander Musman8dba6642014-04-22 13:09:42 +00005914 // Warn about zero linear step (it would be probably better specified as
5915 // making corresponding variables 'const').
5916 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00005917 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
5918 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00005919 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
5920 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00005921 if (!IsConstant && CalcStep.isUsable()) {
5922 // Calculate the step beforehand instead of doing this on each iteration.
5923 // (This is not used if the number of iterations may be kfold-ed).
5924 CalcStepExpr = CalcStep.get();
5925 }
Alexander Musman8dba6642014-04-22 13:09:42 +00005926 }
5927
5928 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
Alexander Musman3276a272015-03-21 10:12:56 +00005929 Vars, Inits, StepExpr, CalcStepExpr);
5930}
5931
5932static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
5933 Expr *NumIterations, Sema &SemaRef,
5934 Scope *S) {
5935 // Walk the vars and build update/final expressions for the CodeGen.
5936 SmallVector<Expr *, 8> Updates;
5937 SmallVector<Expr *, 8> Finals;
5938 Expr *Step = Clause.getStep();
5939 Expr *CalcStep = Clause.getCalcStep();
5940 // OpenMP [2.14.3.7, linear clause]
5941 // If linear-step is not specified it is assumed to be 1.
5942 if (Step == nullptr)
5943 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5944 else if (CalcStep)
5945 Step = cast<BinaryOperator>(CalcStep)->getLHS();
5946 bool HasErrors = false;
5947 auto CurInit = Clause.inits().begin();
5948 for (auto &RefExpr : Clause.varlists()) {
5949 Expr *InitExpr = *CurInit;
5950
5951 // Build privatized reference to the current linear var.
5952 auto DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005953 auto PrivateRef =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005954 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
5955 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
5956 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00005957
5958 // Build update: Var = InitExpr + IV * Step
5959 ExprResult Update =
5960 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
5961 InitExpr, IV, Step, /* Subtract */ false);
5962 Update = SemaRef.ActOnFinishFullExpr(Update.get());
5963
5964 // Build final: Var = InitExpr + NumIterations * Step
5965 ExprResult Final =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005966 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
5967 InitExpr, NumIterations, Step, /* Subtract */ false);
Alexander Musman3276a272015-03-21 10:12:56 +00005968 Final = SemaRef.ActOnFinishFullExpr(Final.get());
5969 if (!Update.isUsable() || !Final.isUsable()) {
5970 Updates.push_back(nullptr);
5971 Finals.push_back(nullptr);
5972 HasErrors = true;
5973 } else {
5974 Updates.push_back(Update.get());
5975 Finals.push_back(Final.get());
5976 }
5977 ++CurInit;
5978 }
5979 Clause.setUpdates(Updates);
5980 Clause.setFinals(Finals);
5981 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00005982}
5983
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005984OMPClause *Sema::ActOnOpenMPAlignedClause(
5985 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
5986 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
5987
5988 SmallVector<Expr *, 8> Vars;
5989 for (auto &RefExpr : VarList) {
5990 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
5991 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5992 // It will be analyzed later.
5993 Vars.push_back(RefExpr);
5994 continue;
5995 }
5996
5997 SourceLocation ELoc = RefExpr->getExprLoc();
5998 // OpenMP [2.1, C/C++]
5999 // A list item is a variable name.
6000 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6001 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6002 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6003 continue;
6004 }
6005
6006 VarDecl *VD = cast<VarDecl>(DE->getDecl());
6007
6008 // OpenMP [2.8.1, simd construct, Restrictions]
6009 // The type of list items appearing in the aligned clause must be
6010 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006011 QualType QType = VD->getType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006012 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006013 const Type *Ty = QType.getTypePtrOrNull();
6014 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
6015 !Ty->isPointerType())) {
6016 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
6017 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
6018 bool IsDecl =
6019 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6020 Diag(VD->getLocation(),
6021 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6022 << VD;
6023 continue;
6024 }
6025
6026 // OpenMP [2.8.1, simd construct, Restrictions]
6027 // A list-item cannot appear in more than one aligned clause.
6028 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
6029 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
6030 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
6031 << getOpenMPClauseName(OMPC_aligned);
6032 continue;
6033 }
6034
6035 Vars.push_back(DE);
6036 }
6037
6038 // OpenMP [2.8.1, simd construct, Description]
6039 // The parameter of the aligned clause, alignment, must be a constant
6040 // positive integer expression.
6041 // If no optional parameter is specified, implementation-defined default
6042 // alignments for SIMD instructions on the target platforms are assumed.
6043 if (Alignment != nullptr) {
6044 ExprResult AlignResult =
6045 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
6046 if (AlignResult.isInvalid())
6047 return nullptr;
6048 Alignment = AlignResult.get();
6049 }
6050 if (Vars.empty())
6051 return nullptr;
6052
6053 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
6054 EndLoc, Vars, Alignment);
6055}
6056
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006057OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
6058 SourceLocation StartLoc,
6059 SourceLocation LParenLoc,
6060 SourceLocation EndLoc) {
6061 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006062 SmallVector<Expr *, 8> SrcExprs;
6063 SmallVector<Expr *, 8> DstExprs;
6064 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00006065 for (auto &RefExpr : VarList) {
6066 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
6067 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006068 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006069 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006070 SrcExprs.push_back(nullptr);
6071 DstExprs.push_back(nullptr);
6072 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006073 continue;
6074 }
6075
Alexey Bataeved09d242014-05-28 05:53:51 +00006076 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006077 // OpenMP [2.1, C/C++]
6078 // A list item is a variable name.
6079 // OpenMP [2.14.4.1, Restrictions, p.1]
6080 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00006081 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006082 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00006083 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006084 continue;
6085 }
6086
6087 Decl *D = DE->getDecl();
6088 VarDecl *VD = cast<VarDecl>(D);
6089
6090 QualType Type = VD->getType();
6091 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6092 // It will be analyzed later.
6093 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006094 SrcExprs.push_back(nullptr);
6095 DstExprs.push_back(nullptr);
6096 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006097 continue;
6098 }
6099
6100 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
6101 // A list item that appears in a copyin clause must be threadprivate.
6102 if (!DSAStack->isThreadPrivate(VD)) {
6103 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00006104 << getOpenMPClauseName(OMPC_copyin)
6105 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006106 continue;
6107 }
6108
6109 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6110 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00006111 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006112 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006113 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00006114 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006115 ElemType.getUnqualifiedType(), ".copyin.src");
Alexey Bataev39f915b82015-05-08 10:41:21 +00006116 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006117 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
6118 auto *DstVD =
6119 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst");
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006120 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006121 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006122 // For arrays generate assignment operation for single element and replace
6123 // it by the original array element in CodeGen.
6124 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6125 PseudoDstExpr, PseudoSrcExpr);
6126 if (AssignmentOp.isInvalid())
6127 continue;
6128 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6129 /*DiscardedValue=*/true);
6130 if (AssignmentOp.isInvalid())
6131 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006132
6133 DSAStack->addDSA(VD, DE, OMPC_copyin);
6134 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006135 SrcExprs.push_back(PseudoSrcExpr);
6136 DstExprs.push_back(PseudoDstExpr);
6137 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006138 }
6139
Alexey Bataeved09d242014-05-28 05:53:51 +00006140 if (Vars.empty())
6141 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006142
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006143 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
6144 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006145}
6146
Alexey Bataevbae9a792014-06-27 10:37:06 +00006147OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
6148 SourceLocation StartLoc,
6149 SourceLocation LParenLoc,
6150 SourceLocation EndLoc) {
6151 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00006152 SmallVector<Expr *, 8> SrcExprs;
6153 SmallVector<Expr *, 8> DstExprs;
6154 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006155 for (auto &RefExpr : VarList) {
6156 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
6157 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6158 // It will be analyzed later.
6159 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006160 SrcExprs.push_back(nullptr);
6161 DstExprs.push_back(nullptr);
6162 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006163 continue;
6164 }
6165
6166 SourceLocation ELoc = RefExpr->getExprLoc();
6167 // OpenMP [2.1, C/C++]
6168 // A list item is a variable name.
6169 // OpenMP [2.14.4.1, Restrictions, p.1]
6170 // A list item that appears in a copyin clause must be threadprivate.
6171 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6172 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6173 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6174 continue;
6175 }
6176
6177 Decl *D = DE->getDecl();
6178 VarDecl *VD = cast<VarDecl>(D);
6179
6180 QualType Type = VD->getType();
6181 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6182 // It will be analyzed later.
6183 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006184 SrcExprs.push_back(nullptr);
6185 DstExprs.push_back(nullptr);
6186 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006187 continue;
6188 }
6189
6190 // OpenMP [2.14.4.2, Restrictions, p.2]
6191 // A list item that appears in a copyprivate clause may not appear in a
6192 // private or firstprivate clause on the single construct.
6193 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006194 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006195 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
6196 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00006197 Diag(ELoc, diag::err_omp_wrong_dsa)
6198 << getOpenMPClauseName(DVar.CKind)
6199 << getOpenMPClauseName(OMPC_copyprivate);
6200 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6201 continue;
6202 }
6203
6204 // OpenMP [2.11.4.2, Restrictions, p.1]
6205 // All list items that appear in a copyprivate clause must be either
6206 // threadprivate or private in the enclosing context.
6207 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006208 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006209 if (DVar.CKind == OMPC_shared) {
6210 Diag(ELoc, diag::err_omp_required_access)
6211 << getOpenMPClauseName(OMPC_copyprivate)
6212 << "threadprivate or private in the enclosing context";
6213 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6214 continue;
6215 }
6216 }
6217 }
6218
Alexey Bataev7a3e5852015-05-19 08:19:24 +00006219 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00006220 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00006221 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00006222 << getOpenMPClauseName(OMPC_copyprivate) << Type
6223 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00006224 bool IsDecl =
6225 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6226 Diag(VD->getLocation(),
6227 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6228 << VD;
6229 continue;
6230 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00006231
Alexey Bataevbae9a792014-06-27 10:37:06 +00006232 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6233 // A variable of class type (or array thereof) that appears in a
6234 // copyin clause requires an accessible, unambiguous copy assignment
6235 // operator for the class type.
Alexey Bataev420d45b2015-04-14 05:11:24 +00006236 Type = Context.getBaseElementType(Type).getUnqualifiedType();
6237 auto *SrcVD =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006238 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src");
Alexey Bataev420d45b2015-04-14 05:11:24 +00006239 auto *PseudoSrcExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006240 buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
Alexey Bataev420d45b2015-04-14 05:11:24 +00006241 auto *DstVD =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006242 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst");
Alexey Bataev420d45b2015-04-14 05:11:24 +00006243 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006244 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataeva63048e2015-03-23 06:18:07 +00006245 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6246 PseudoDstExpr, PseudoSrcExpr);
6247 if (AssignmentOp.isInvalid())
6248 continue;
6249 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6250 /*DiscardedValue=*/true);
6251 if (AssignmentOp.isInvalid())
6252 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006253
6254 // No need to mark vars as copyprivate, they are already threadprivate or
6255 // implicitly private.
6256 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006257 SrcExprs.push_back(PseudoSrcExpr);
6258 DstExprs.push_back(PseudoDstExpr);
6259 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00006260 }
6261
6262 if (Vars.empty())
6263 return nullptr;
6264
Alexey Bataeva63048e2015-03-23 06:18:07 +00006265 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6266 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006267}
6268
Alexey Bataev6125da92014-07-21 11:26:11 +00006269OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
6270 SourceLocation StartLoc,
6271 SourceLocation LParenLoc,
6272 SourceLocation EndLoc) {
6273 if (VarList.empty())
6274 return nullptr;
6275
6276 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
6277}
Alexey Bataevdea47612014-07-23 07:46:59 +00006278