blob: ef293babb9fe0f205df1aa13129d5669440ffe5a [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 Bataevb08f89f2015-08-14 12:25:37 +000015#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000017#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000018#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000019#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000020#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000021#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtOpenMP.h"
23#include "clang/AST/StmtVisitor.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000024#include "clang/Basic/OpenMPKinds.h"
Samuel Antaof8b50122015-07-13 22:54:53 +000025#include "clang/Basic/TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "clang/Lex/Preprocessor.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000027#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000028#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000029#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000031#include "clang/Sema/SemaInternal.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000032using namespace clang;
33
Alexey Bataev758e55e2013-09-06 18:03:48 +000034//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
38namespace {
39/// \brief Default data sharing attributes, which can be applied to directive.
40enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000041 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
42 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
43 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000044};
Alexey Bataev7ff55242014-06-19 09:13:45 +000045
Alexey Bataevf29276e2014-06-18 04:14:57 +000046template <class T> struct MatchesAny {
Alexey Bataev23b69422014-06-18 07:08:49 +000047 explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
Alexey Bataevf29276e2014-06-18 04:14:57 +000048 bool operator()(T Kind) {
49 for (auto KindEl : Arr)
50 if (KindEl == Kind)
51 return true;
52 return false;
53 }
54
55private:
56 ArrayRef<T> Arr;
57};
Alexey Bataev23b69422014-06-18 07:08:49 +000058struct MatchesAlways {
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000059 MatchesAlways() {}
Alexey Bataev7ff55242014-06-19 09:13:45 +000060 template <class T> bool operator()(T) { return true; }
Alexey Bataevf29276e2014-06-18 04:14:57 +000061};
62
63typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
64typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
Alexey Bataev758e55e2013-09-06 18:03:48 +000065
66/// \brief Stack for tracking declarations used in OpenMP directives and
67/// clauses and their data-sharing attributes.
68class DSAStackTy {
69public:
70 struct DSAVarData {
71 OpenMPDirectiveKind DKind;
72 OpenMPClauseKind CKind;
73 DeclRefExpr *RefExpr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000074 SourceLocation ImplicitDSALoc;
75 DSAVarData()
76 : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
77 ImplicitDSALoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000078 };
Alexey Bataeved09d242014-05-28 05:53:51 +000079
Kelvin Li0bff7af2015-11-23 05:32:03 +000080public:
81 struct MapInfo {
82 Expr *RefExpr;
83 };
84
Alexey Bataev758e55e2013-09-06 18:03:48 +000085private:
86 struct DSAInfo {
87 OpenMPClauseKind Attributes;
88 DeclRefExpr *RefExpr;
89 };
90 typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000091 typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
Alexey Bataev9c821032015-04-30 04:23:23 +000092 typedef llvm::DenseSet<VarDecl *> LoopControlVariablesSetTy;
Kelvin Li0bff7af2015-11-23 05:32:03 +000093 typedef llvm::SmallDenseMap<VarDecl *, MapInfo, 64> MappedDeclsTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000094
95 struct SharingMapTy {
96 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000097 AlignedMapTy AlignedMap;
Kelvin Li0bff7af2015-11-23 05:32:03 +000098 MappedDeclsTy MappedDecls;
Alexey Bataev9c821032015-04-30 04:23:23 +000099 LoopControlVariablesSetTy LCVSet;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000100 DefaultDataSharingAttributes DefaultAttr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000101 SourceLocation DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000102 OpenMPDirectiveKind Directive;
103 DeclarationNameInfo DirectiveName;
104 Scope *CurScope;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000105 SourceLocation ConstructLoc;
Alexey Bataev346265e2015-09-25 10:37:12 +0000106 /// \brief first argument (Expr *) contains optional argument of the
107 /// 'ordered' clause, the second one is true if the regions has 'ordered'
108 /// clause, false otherwise.
109 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000110 bool NowaitRegion;
Alexey Bataev25e5b442015-09-15 12:52:43 +0000111 bool CancelRegion;
Alexey Bataev9c821032015-04-30 04:23:23 +0000112 unsigned CollapseNumber;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000113 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000114 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000115 Scope *CurScope, SourceLocation Loc)
Alexey Bataev9c821032015-04-30 04:23:23 +0000116 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000117 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
Alexey Bataev346265e2015-09-25 10:37:12 +0000118 ConstructLoc(Loc), OrderedRegion(), NowaitRegion(false),
Alexey Bataev25e5b442015-09-15 12:52:43 +0000119 CancelRegion(false), CollapseNumber(1), InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000120 SharingMapTy()
Alexey Bataev9c821032015-04-30 04:23:23 +0000121 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000122 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
Alexey Bataev346265e2015-09-25 10:37:12 +0000123 ConstructLoc(), OrderedRegion(), NowaitRegion(false),
Alexey Bataev25e5b442015-09-15 12:52:43 +0000124 CancelRegion(false), CollapseNumber(1), InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000125 };
126
127 typedef SmallVector<SharingMapTy, 64> StackTy;
128
129 /// \brief Stack of used declaration and their data-sharing attributes.
130 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000131 /// \brief true, if check for DSA must be from parent directive, false, if
132 /// from current directive.
Alexey Bataevaac108a2015-06-23 04:51:00 +0000133 OpenMPClauseKind ClauseKindMode;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000134 Sema &SemaRef;
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000135 bool ForceCapturing;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000136
137 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
138
139 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000140
141 /// \brief Checks if the variable is a local for OpenMP region.
142 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000143
Alexey Bataev758e55e2013-09-06 18:03:48 +0000144public:
Alexey Bataevaac108a2015-06-23 04:51:00 +0000145 explicit DSAStackTy(Sema &S)
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000146 : Stack(1), ClauseKindMode(OMPC_unknown), SemaRef(S),
147 ForceCapturing(false) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000148
Alexey Bataevaac108a2015-06-23 04:51:00 +0000149 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
150 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000151
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000152 bool isForceVarCapturing() const { return ForceCapturing; }
153 void setForceVarCapturing(bool V) { ForceCapturing = V; }
154
Alexey Bataev758e55e2013-09-06 18:03:48 +0000155 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000156 Scope *CurScope, SourceLocation Loc) {
157 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
158 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000159 }
160
161 void pop() {
162 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
163 Stack.pop_back();
164 }
165
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000166 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000167 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000168 /// for diagnostics.
169 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
170
Alexey Bataev9c821032015-04-30 04:23:23 +0000171 /// \brief Register specified variable as loop control variable.
172 void addLoopControlVariable(VarDecl *D);
173 /// \brief Check if the specified variable is a loop control variable for
174 /// current region.
175 bool isLoopControlVariable(VarDecl *D);
176
Alexey Bataev758e55e2013-09-06 18:03:48 +0000177 /// \brief Adds explicit data sharing attribute to the specified declaration.
178 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
179
Alexey Bataev758e55e2013-09-06 18:03:48 +0000180 /// \brief Returns data sharing attributes from top of the stack for the
181 /// specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000182 DSAVarData getTopDSA(VarDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000183 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000184 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000185 /// \brief Checks if the specified variables has data-sharing attributes which
186 /// match specified \a CPred predicate in any directive which matches \a DPred
187 /// predicate.
188 template <class ClausesPredicate, class DirectivesPredicate>
189 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000190 DirectivesPredicate DPred, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000191 /// \brief Checks if the specified variables has data-sharing attributes which
192 /// match specified \a CPred predicate in any innermost directive which
193 /// matches \a DPred predicate.
194 template <class ClausesPredicate, class DirectivesPredicate>
195 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000196 DirectivesPredicate DPred,
197 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000198 /// \brief Checks if the specified variables has explicit data-sharing
199 /// attributes which match specified \a CPred predicate at the specified
200 /// OpenMP region.
201 bool hasExplicitDSA(VarDecl *D,
202 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
203 unsigned Level);
Samuel Antao4be30e92015-10-02 17:14:03 +0000204
205 /// \brief Returns true if the directive at level \Level matches in the
206 /// specified \a DPred predicate.
207 bool hasExplicitDirective(
208 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
209 unsigned Level);
210
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000211 /// \brief Finds a directive which matches specified \a DPred predicate.
212 template <class NamedDirectivesPredicate>
213 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000214
Alexey Bataev758e55e2013-09-06 18:03:48 +0000215 /// \brief Returns currently analyzed directive.
216 OpenMPDirectiveKind getCurrentDirective() const {
217 return Stack.back().Directive;
218 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000219 /// \brief Returns parent directive.
220 OpenMPDirectiveKind getParentDirective() const {
221 if (Stack.size() > 2)
222 return Stack[Stack.size() - 2].Directive;
223 return OMPD_unknown;
224 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000225
226 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000227 void setDefaultDSANone(SourceLocation Loc) {
228 Stack.back().DefaultAttr = DSA_none;
229 Stack.back().DefaultAttrLoc = Loc;
230 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000231 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000232 void setDefaultDSAShared(SourceLocation Loc) {
233 Stack.back().DefaultAttr = DSA_shared;
234 Stack.back().DefaultAttrLoc = Loc;
235 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000236
237 DefaultDataSharingAttributes getDefaultDSA() const {
238 return Stack.back().DefaultAttr;
239 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000240 SourceLocation getDefaultDSALocation() const {
241 return Stack.back().DefaultAttrLoc;
242 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000243
Alexey Bataevf29276e2014-06-18 04:14:57 +0000244 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000245 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000246 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000247 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000248 }
249
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000250 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000251 void setOrderedRegion(bool IsOrdered, Expr *Param) {
252 Stack.back().OrderedRegion.setInt(IsOrdered);
253 Stack.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000254 }
255 /// \brief Returns true, if parent region is ordered (has associated
256 /// 'ordered' clause), false - otherwise.
257 bool isParentOrderedRegion() const {
258 if (Stack.size() > 2)
Alexey Bataev346265e2015-09-25 10:37:12 +0000259 return Stack[Stack.size() - 2].OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000260 return false;
261 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000262 /// \brief Returns optional parameter for the ordered region.
263 Expr *getParentOrderedRegionParam() const {
264 if (Stack.size() > 2)
265 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
266 return nullptr;
267 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000268 /// \brief Marks current region as nowait (it has a 'nowait' clause).
269 void setNowaitRegion(bool IsNowait = true) {
270 Stack.back().NowaitRegion = IsNowait;
271 }
272 /// \brief Returns true, if parent region is nowait (has associated
273 /// 'nowait' clause), false - otherwise.
274 bool isParentNowaitRegion() const {
275 if (Stack.size() > 2)
276 return Stack[Stack.size() - 2].NowaitRegion;
277 return false;
278 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000279 /// \brief Marks parent region as cancel region.
280 void setParentCancelRegion(bool Cancel = true) {
281 if (Stack.size() > 2)
282 Stack[Stack.size() - 2].CancelRegion =
283 Stack[Stack.size() - 2].CancelRegion || Cancel;
284 }
285 /// \brief Return true if current region has inner cancel construct.
286 bool isCancelRegion() const {
287 return Stack.back().CancelRegion;
288 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000289
Alexey Bataev9c821032015-04-30 04:23:23 +0000290 /// \brief Set collapse value for the region.
291 void setCollapseNumber(unsigned Val) { Stack.back().CollapseNumber = Val; }
292 /// \brief Return collapse value for region.
293 unsigned getCollapseNumber() const {
294 return Stack.back().CollapseNumber;
295 }
296
Alexey Bataev13314bf2014-10-09 04:18:56 +0000297 /// \brief Marks current target region as one with closely nested teams
298 /// region.
299 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
300 if (Stack.size() > 2)
301 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
302 }
303 /// \brief Returns true, if current region has closely nested teams region.
304 bool hasInnerTeamsRegion() const {
305 return getInnerTeamsRegionLoc().isValid();
306 }
307 /// \brief Returns location of the nested teams region (if any).
308 SourceLocation getInnerTeamsRegionLoc() const {
309 if (Stack.size() > 1)
310 return Stack.back().InnerTeamsRegionLoc;
311 return SourceLocation();
312 }
313
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000314 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000315 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000316 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000317
318 MapInfo getMapInfoForVar(VarDecl *VD) {
319 MapInfo VarMI = {0};
320 for (auto Cnt = Stack.size() - 1; Cnt > 0; --Cnt) {
321 if (Stack[Cnt].MappedDecls.count(VD)) {
322 VarMI = Stack[Cnt].MappedDecls[VD];
323 break;
324 }
325 }
326 return VarMI;
327 }
328
329 void addMapInfoForVar(VarDecl *VD, MapInfo MI) {
330 if (Stack.size() > 1) {
331 Stack.back().MappedDecls[VD] = MI;
332 }
333 }
334
335 MapInfo IsMappedInCurrentRegion(VarDecl *VD) {
336 assert(Stack.size() > 1 && "Target level is 0");
337 MapInfo VarMI = {0};
338 if (Stack.size() > 1 && Stack.back().MappedDecls.count(VD)) {
339 VarMI = Stack.back().MappedDecls[VD];
340 }
341 return VarMI;
342 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000343};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000344bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
345 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
Alexey Bataev49f6e782015-12-01 04:18:41 +0000346 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown ||
347 DKind == OMPD_taskloop;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000348}
Alexey Bataeved09d242014-05-28 05:53:51 +0000349} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000350
351DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
352 VarDecl *D) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000353 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000354 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000355 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000356 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
357 // in a region but not in construct]
358 // File-scope or namespace-scope variables referenced in called routines
359 // in the region are shared unless they appear in a threadprivate
360 // directive.
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000361 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000362 DVar.CKind = OMPC_shared;
363
364 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
365 // in a region but not in construct]
366 // Variables with static storage duration that are declared in called
367 // routines in the region are shared.
368 if (D->hasGlobalStorage())
369 DVar.CKind = OMPC_shared;
370
Alexey Bataev758e55e2013-09-06 18:03:48 +0000371 return DVar;
372 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000373
Alexey Bataev758e55e2013-09-06 18:03:48 +0000374 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000375 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
376 // in a Construct, C/C++, predetermined, p.1]
377 // Variables with automatic storage duration that are declared in a scope
378 // inside the construct are private.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000379 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
380 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
381 DVar.CKind = OMPC_private;
382 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000383 }
384
Alexey Bataev758e55e2013-09-06 18:03:48 +0000385 // Explicitly specified attributes and local variables with predetermined
386 // attributes.
387 if (Iter->SharingMap.count(D)) {
388 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
389 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000390 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000391 return DVar;
392 }
393
394 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
395 // in a Construct, C/C++, implicitly determined, p.1]
396 // In a parallel or task construct, the data-sharing attributes of these
397 // variables are determined by the default clause, if present.
398 switch (Iter->DefaultAttr) {
399 case DSA_shared:
400 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000401 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000402 return DVar;
403 case DSA_none:
404 return DVar;
405 case DSA_unspecified:
406 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
407 // in a Construct, implicitly determined, p.2]
408 // In a parallel construct, if no default clause is present, these
409 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000410 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000411 if (isOpenMPParallelDirective(DVar.DKind) ||
412 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000413 DVar.CKind = OMPC_shared;
414 return DVar;
415 }
416
417 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
418 // in a Construct, implicitly determined, p.4]
419 // In a task construct, if no default clause is present, a variable that in
420 // the enclosing context is determined to be shared by all implicit tasks
421 // bound to the current team is shared.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000422 if (DVar.DKind == OMPD_task) {
423 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000424 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000425 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000426 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
427 // Referenced
Alexey Bataev758e55e2013-09-06 18:03:48 +0000428 // in a Construct, implicitly determined, p.6]
429 // In a task construct, if no default clause is present, a variable
430 // whose data-sharing attribute is not determined by the rules above is
431 // firstprivate.
432 DVarTemp = getDSA(I, D);
433 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000434 DVar.RefExpr = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000435 DVar.DKind = OMPD_task;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000436 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000437 return DVar;
438 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000439 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000440 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000441 }
442 DVar.DKind = OMPD_task;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000443 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000444 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000445 return DVar;
446 }
447 }
448 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
449 // in a Construct, implicitly determined, p.3]
450 // For constructs other than task, if no default clause is present, these
451 // variables inherit their data-sharing attributes from the enclosing
452 // context.
Benjamin Kramer167e9992014-03-02 12:20:24 +0000453 return getDSA(std::next(Iter), D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000454}
455
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000456DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
457 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000458 D = D->getCanonicalDecl();
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000459 auto It = Stack.back().AlignedMap.find(D);
460 if (It == Stack.back().AlignedMap.end()) {
461 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
462 Stack.back().AlignedMap[D] = NewDE;
463 return nullptr;
464 } else {
465 assert(It->second && "Unexpected nullptr expr in the aligned map");
466 return It->second;
467 }
468 return nullptr;
469}
470
Alexey Bataev9c821032015-04-30 04:23:23 +0000471void DSAStackTy::addLoopControlVariable(VarDecl *D) {
472 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
473 D = D->getCanonicalDecl();
474 Stack.back().LCVSet.insert(D);
475}
476
477bool DSAStackTy::isLoopControlVariable(VarDecl *D) {
478 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
479 D = D->getCanonicalDecl();
480 return Stack.back().LCVSet.count(D) > 0;
481}
482
Alexey Bataev758e55e2013-09-06 18:03:48 +0000483void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000484 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000485 if (A == OMPC_threadprivate) {
486 Stack[0].SharingMap[D].Attributes = A;
487 Stack[0].SharingMap[D].RefExpr = E;
488 } else {
489 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
490 Stack.back().SharingMap[D].Attributes = A;
491 Stack.back().SharingMap[D].RefExpr = E;
492 }
493}
494
Alexey Bataeved09d242014-05-28 05:53:51 +0000495bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000496 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000497 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000498 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000499 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000500 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000501 ++I;
502 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000503 if (I == E)
504 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000505 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000506 Scope *CurScope = getCurScope();
507 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000508 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000509 }
510 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000511 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000512 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000513}
514
Alexey Bataev39f915b82015-05-08 10:41:21 +0000515/// \brief Build a variable declaration for OpenMP loop iteration variable.
516static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000517 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000518 DeclContext *DC = SemaRef.CurContext;
519 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
520 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
521 VarDecl *Decl =
522 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000523 if (Attrs) {
524 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
525 I != E; ++I)
526 Decl->addAttr(*I);
527 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000528 Decl->setImplicit();
529 return Decl;
530}
531
532static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
533 SourceLocation Loc,
534 bool RefersToCapture = false) {
535 D->setReferenced();
536 D->markUsed(S.Context);
537 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
538 SourceLocation(), D, RefersToCapture, Loc, Ty,
539 VK_LValue);
540}
541
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000542DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000543 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000544 DSAVarData DVar;
545
546 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
547 // in a Construct, C/C++, predetermined, p.1]
548 // Variables appearing in threadprivate directives are threadprivate.
Samuel Antaof8b50122015-07-13 22:54:53 +0000549 if ((D->getTLSKind() != VarDecl::TLS_None &&
550 !(D->hasAttr<OMPThreadPrivateDeclAttr>() &&
551 SemaRef.getLangOpts().OpenMPUseTLS &&
552 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +0000553 (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() &&
554 !D->isLocalVarDecl())) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000555 addDSA(D, buildDeclRefExpr(SemaRef, D, D->getType().getNonReferenceType(),
556 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000557 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000558 }
559 if (Stack[0].SharingMap.count(D)) {
560 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
561 DVar.CKind = OMPC_threadprivate;
562 return DVar;
563 }
564
565 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
566 // in a Construct, C/C++, predetermined, p.1]
567 // Variables with automatic storage duration that are declared in a scope
568 // inside the construct are private.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000569 OpenMPDirectiveKind Kind =
570 FromParent ? getParentDirective() : getCurrentDirective();
571 auto StartI = std::next(Stack.rbegin());
572 auto EndI = std::prev(Stack.rend());
573 if (FromParent && StartI != EndI) {
574 StartI = std::next(StartI);
575 }
576 if (!isParallelOrTaskRegion(Kind)) {
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000577 if (isOpenMPLocal(D, StartI) &&
578 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
579 D->getStorageClass() == SC_None)) ||
580 isa<ParmVarDecl>(D))) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000581 DVar.CKind = OMPC_private;
582 return DVar;
Alexander Musman8dba6642014-04-22 13:09:42 +0000583 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000584
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000585 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
586 // in a Construct, C/C++, predetermined, p.4]
587 // Static data members are shared.
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000588 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
589 // in a Construct, C/C++, predetermined, p.7]
590 // Variables with static storage duration that are declared in a scope
591 // inside the construct are shared.
Kelvin Li4eea8c62015-09-15 18:56:58 +0000592 if (D->isStaticDataMember()) {
Alexey Bataev42971a32015-01-20 07:03:46 +0000593 DSAVarData DVarTemp =
594 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
595 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
596 return DVar;
597
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000598 DVar.CKind = OMPC_shared;
599 return DVar;
600 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000601 }
602
603 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000604 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
605 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000606 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
607 // in a Construct, C/C++, predetermined, p.6]
608 // Variables with const qualified type having no mutable member are
609 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000610 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000611 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000612 if (IsConstant &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000613 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000614 // Variables with const-qualified type having no mutable member may be
615 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000616 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
617 MatchesAlways(), FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000618 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
619 return DVar;
620
Alexey Bataev758e55e2013-09-06 18:03:48 +0000621 DVar.CKind = OMPC_shared;
622 return DVar;
623 }
624
Alexey Bataev758e55e2013-09-06 18:03:48 +0000625 // Explicitly specified attributes and local variables with predetermined
626 // attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000627 auto I = std::prev(StartI);
628 if (I->SharingMap.count(D)) {
629 DVar.RefExpr = I->SharingMap[D].RefExpr;
630 DVar.CKind = I->SharingMap[D].Attributes;
631 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000632 }
633
634 return DVar;
635}
636
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000637DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000638 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000639 auto StartI = Stack.rbegin();
640 auto EndI = std::prev(Stack.rend());
641 if (FromParent && StartI != EndI) {
642 StartI = std::next(StartI);
643 }
644 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000645}
646
Alexey Bataevf29276e2014-06-18 04:14:57 +0000647template <class ClausesPredicate, class DirectivesPredicate>
648DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000649 DirectivesPredicate DPred,
650 bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000651 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000652 auto StartI = std::next(Stack.rbegin());
653 auto EndI = std::prev(Stack.rend());
654 if (FromParent && StartI != EndI) {
655 StartI = std::next(StartI);
656 }
657 for (auto I = StartI, EE = EndI; I != EE; ++I) {
658 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000659 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000660 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000661 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000662 return DVar;
663 }
664 return DSAVarData();
665}
666
Alexey Bataevf29276e2014-06-18 04:14:57 +0000667template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000668DSAStackTy::DSAVarData
669DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
670 DirectivesPredicate DPred, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000671 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000672 auto StartI = std::next(Stack.rbegin());
673 auto EndI = std::prev(Stack.rend());
674 if (FromParent && StartI != EndI) {
675 StartI = std::next(StartI);
676 }
677 for (auto I = StartI, EE = EndI; I != EE; ++I) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000678 if (!DPred(I->Directive))
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000679 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +0000680 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000681 if (CPred(DVar.CKind))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000682 return DVar;
683 return DSAVarData();
684 }
685 return DSAVarData();
686}
687
Alexey Bataevaac108a2015-06-23 04:51:00 +0000688bool DSAStackTy::hasExplicitDSA(
689 VarDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
690 unsigned Level) {
691 if (CPred(ClauseKindMode))
692 return true;
693 if (isClauseParsingMode())
694 ++Level;
695 D = D->getCanonicalDecl();
696 auto StartI = Stack.rbegin();
697 auto EndI = std::prev(Stack.rend());
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000698 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000699 return false;
700 std::advance(StartI, Level);
701 return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr &&
702 CPred(StartI->SharingMap[D].Attributes);
703}
704
Samuel Antao4be30e92015-10-02 17:14:03 +0000705bool DSAStackTy::hasExplicitDirective(
706 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
707 unsigned Level) {
708 if (isClauseParsingMode())
709 ++Level;
710 auto StartI = Stack.rbegin();
711 auto EndI = std::prev(Stack.rend());
712 if (std::distance(StartI, EndI) <= (int)Level)
713 return false;
714 std::advance(StartI, Level);
715 return DPred(StartI->Directive);
716}
717
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000718template <class NamedDirectivesPredicate>
719bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
720 auto StartI = std::next(Stack.rbegin());
721 auto EndI = std::prev(Stack.rend());
722 if (FromParent && StartI != EndI) {
723 StartI = std::next(StartI);
724 }
725 for (auto I = StartI, EE = EndI; I != EE; ++I) {
726 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
727 return true;
728 }
729 return false;
730}
731
Alexey Bataev758e55e2013-09-06 18:03:48 +0000732void Sema::InitDataSharingAttributesStack() {
733 VarDataSharingAttributesStack = new DSAStackTy(*this);
734}
735
736#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
737
Alexey Bataevf841bd92014-12-16 07:00:22 +0000738bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
739 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000740 VD = VD->getCanonicalDecl();
Samuel Antao4be30e92015-10-02 17:14:03 +0000741
742 // If we are attempting to capture a global variable in a directive with
743 // 'target' we return true so that this global is also mapped to the device.
744 //
745 // FIXME: If the declaration is enclosed in a 'declare target' directive,
746 // then it should not be captured. Therefore, an extra check has to be
747 // inserted here once support for 'declare target' is added.
748 //
749 if (!VD->hasLocalStorage()) {
750 if (DSAStack->getCurrentDirective() == OMPD_target &&
751 !DSAStack->isClauseParsingMode()) {
752 return true;
753 }
754 if (DSAStack->getCurScope() &&
755 DSAStack->hasDirective(
756 [](OpenMPDirectiveKind K, const DeclarationNameInfo &DNI,
757 SourceLocation Loc) -> bool {
758 return isOpenMPTargetDirective(K);
759 },
760 false)) {
761 return true;
762 }
763 }
764
Alexey Bataev48977c32015-08-04 08:10:48 +0000765 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
766 (!DSAStack->isClauseParsingMode() ||
767 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000768 if (DSAStack->isLoopControlVariable(VD) ||
769 (VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000770 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
771 DSAStack->isForceVarCapturing())
Alexey Bataev9c821032015-04-30 04:23:23 +0000772 return true;
Alexey Bataevaac108a2015-06-23 04:51:00 +0000773 auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000774 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
775 return true;
776 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
Alexey Bataevaac108a2015-06-23 04:51:00 +0000777 DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000778 return DVarPrivate.CKind != OMPC_unknown;
779 }
780 return false;
781}
782
Alexey Bataevaac108a2015-06-23 04:51:00 +0000783bool Sema::isOpenMPPrivateVar(VarDecl *VD, unsigned Level) {
784 assert(LangOpts.OpenMP && "OpenMP is not allowed");
785 return DSAStack->hasExplicitDSA(
786 VD, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
787}
788
Samuel Antao4be30e92015-10-02 17:14:03 +0000789bool Sema::isOpenMPTargetCapturedVar(VarDecl *VD, unsigned Level) {
790 assert(LangOpts.OpenMP && "OpenMP is not allowed");
791 // Return true if the current level is no longer enclosed in a target region.
792
793 return !VD->hasLocalStorage() &&
794 DSAStack->hasExplicitDirective(isOpenMPTargetDirective, Level);
795}
796
Alexey Bataeved09d242014-05-28 05:53:51 +0000797void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000798
799void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
800 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000801 Scope *CurScope, SourceLocation Loc) {
802 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000803 PushExpressionEvaluationContext(PotentiallyEvaluated);
804}
805
Alexey Bataevaac108a2015-06-23 04:51:00 +0000806void Sema::StartOpenMPClause(OpenMPClauseKind K) {
807 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000808}
809
Alexey Bataevaac108a2015-06-23 04:51:00 +0000810void Sema::EndOpenMPClause() {
811 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000812}
813
Alexey Bataev758e55e2013-09-06 18:03:48 +0000814void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000815 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
816 // A variable of class type (or array thereof) that appears in a lastprivate
817 // clause requires an accessible, unambiguous default constructor for the
818 // class type, unless the list item is also specified in a firstprivate
819 // clause.
820 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000821 for (auto *C : D->clauses()) {
822 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
823 SmallVector<Expr *, 8> PrivateCopies;
824 for (auto *DE : Clause->varlists()) {
825 if (DE->isValueDependent() || DE->isTypeDependent()) {
826 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000827 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +0000828 }
829 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000830 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000831 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000832 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000833 // Generate helper private variable and initialize it with the
834 // default value. The address of the original variable is replaced
835 // by the address of the new private variable in CodeGen. This new
836 // variable is not added to IdResolver, so the code in the OpenMP
837 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000838 auto *VDPrivate = buildVarDecl(
839 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
840 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +0000841 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
842 if (VDPrivate->isInvalidDecl())
843 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000844 PrivateCopies.push_back(buildDeclRefExpr(
845 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +0000846 } else {
847 // The variable is also a firstprivate, so initialization sequence
848 // for private copy is generated already.
849 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000850 }
851 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000852 // Set initializers to private copies if no errors were found.
853 if (PrivateCopies.size() == Clause->varlist_size()) {
854 Clause->setPrivateCopies(PrivateCopies);
855 }
Alexey Bataevf29276e2014-06-18 04:14:57 +0000856 }
857 }
858 }
859
Alexey Bataev758e55e2013-09-06 18:03:48 +0000860 DSAStack->pop();
861 DiscardCleanupsInEvaluationContext();
862 PopExpressionEvaluationContext();
863}
864
Alexander Musman3276a272015-03-21 10:12:56 +0000865static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
866 Expr *NumIterations, Sema &SemaRef,
867 Scope *S);
868
Alexey Bataeva769e072013-03-22 06:34:35 +0000869namespace {
870
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000871class VarDeclFilterCCC : public CorrectionCandidateCallback {
872private:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000873 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +0000874
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000875public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000876 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +0000877 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000878 NamedDecl *ND = Candidate.getCorrectionDecl();
879 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
880 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000881 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
882 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +0000883 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000884 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +0000885 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000886};
Alexey Bataeved09d242014-05-28 05:53:51 +0000887} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000888
889ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
890 CXXScopeSpec &ScopeSpec,
891 const DeclarationNameInfo &Id) {
892 LookupResult Lookup(*this, Id, LookupOrdinaryName);
893 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
894
895 if (Lookup.isAmbiguous())
896 return ExprError();
897
898 VarDecl *VD;
899 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000900 if (TypoCorrection Corrected = CorrectTypo(
901 Id, LookupOrdinaryName, CurScope, nullptr,
902 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000903 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000904 PDiag(Lookup.empty()
905 ? diag::err_undeclared_var_use_suggest
906 : diag::err_omp_expected_var_arg_suggest)
907 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +0000908 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000909 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000910 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
911 : diag::err_omp_expected_var_arg)
912 << Id.getName();
913 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000914 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000915 } else {
916 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000917 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000918 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
919 return ExprError();
920 }
921 }
922 Lookup.suppressDiagnostics();
923
924 // OpenMP [2.9.2, Syntax, C/C++]
925 // Variables must be file-scope, namespace-scope, or static block-scope.
926 if (!VD->hasGlobalStorage()) {
927 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000928 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
929 bool IsDecl =
930 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000931 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +0000932 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
933 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000934 return ExprError();
935 }
936
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000937 VarDecl *CanonicalVD = VD->getCanonicalDecl();
938 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000939 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
940 // A threadprivate directive for file-scope variables must appear outside
941 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000942 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
943 !getCurLexicalContext()->isTranslationUnit()) {
944 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000945 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
946 bool IsDecl =
947 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
948 Diag(VD->getLocation(),
949 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
950 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000951 return ExprError();
952 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000953 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
954 // A threadprivate directive for static class member variables must appear
955 // in the class definition, in the same scope in which the member
956 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000957 if (CanonicalVD->isStaticDataMember() &&
958 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
959 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000960 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
961 bool IsDecl =
962 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
963 Diag(VD->getLocation(),
964 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
965 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000966 return ExprError();
967 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000968 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
969 // A threadprivate directive for namespace-scope variables must appear
970 // outside any definition or declaration other than the namespace
971 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000972 if (CanonicalVD->getDeclContext()->isNamespace() &&
973 (!getCurLexicalContext()->isFileContext() ||
974 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
975 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000976 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
977 bool IsDecl =
978 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
979 Diag(VD->getLocation(),
980 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
981 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000982 return ExprError();
983 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000984 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
985 // A threadprivate directive for static block-scope variables must appear
986 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000987 if (CanonicalVD->isStaticLocal() && CurScope &&
988 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000989 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000990 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
991 bool IsDecl =
992 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
993 Diag(VD->getLocation(),
994 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
995 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000996 return ExprError();
997 }
998
999 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1000 // A threadprivate directive must lexically precede all references to any
1001 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001002 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001003 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001004 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001005 return ExprError();
1006 }
1007
1008 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00001009 ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001010 return DE;
1011}
1012
Alexey Bataeved09d242014-05-28 05:53:51 +00001013Sema::DeclGroupPtrTy
1014Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1015 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001016 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001017 CurContext->addDecl(D);
1018 return DeclGroupPtrTy::make(DeclGroupRef(D));
1019 }
1020 return DeclGroupPtrTy();
1021}
1022
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001023namespace {
1024class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1025 Sema &SemaRef;
1026
1027public:
1028 bool VisitDeclRefExpr(const DeclRefExpr *E) {
1029 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
1030 if (VD->hasLocalStorage()) {
1031 SemaRef.Diag(E->getLocStart(),
1032 diag::err_omp_local_var_in_threadprivate_init)
1033 << E->getSourceRange();
1034 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1035 << VD << VD->getSourceRange();
1036 return true;
1037 }
1038 }
1039 return false;
1040 }
1041 bool VisitStmt(const Stmt *S) {
1042 for (auto Child : S->children()) {
1043 if (Child && Visit(Child))
1044 return true;
1045 }
1046 return false;
1047 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001048 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001049};
1050} // namespace
1051
Alexey Bataeved09d242014-05-28 05:53:51 +00001052OMPThreadPrivateDecl *
1053Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001054 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001055 for (auto &RefExpr : VarList) {
1056 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001057 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1058 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001059
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001060 QualType QType = VD->getType();
1061 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1062 // It will be analyzed later.
1063 Vars.push_back(DE);
1064 continue;
1065 }
1066
Alexey Bataeva769e072013-03-22 06:34:35 +00001067 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1068 // A threadprivate variable must not have an incomplete type.
1069 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001070 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001071 continue;
1072 }
1073
1074 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1075 // A threadprivate variable must not have a reference type.
1076 if (VD->getType()->isReferenceType()) {
1077 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001078 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1079 bool IsDecl =
1080 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1081 Diag(VD->getLocation(),
1082 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1083 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001084 continue;
1085 }
1086
Samuel Antaof8b50122015-07-13 22:54:53 +00001087 // Check if this is a TLS variable. If TLS is not being supported, produce
1088 // the corresponding diagnostic.
1089 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1090 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1091 getLangOpts().OpenMPUseTLS &&
1092 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001093 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1094 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001095 Diag(ILoc, diag::err_omp_var_thread_local)
1096 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001097 bool IsDecl =
1098 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1099 Diag(VD->getLocation(),
1100 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1101 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001102 continue;
1103 }
1104
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001105 // Check if initial value of threadprivate variable reference variable with
1106 // local storage (it is not supported by runtime).
1107 if (auto Init = VD->getAnyInitializer()) {
1108 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001109 if (Checker.Visit(Init))
1110 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001111 }
1112
Alexey Bataeved09d242014-05-28 05:53:51 +00001113 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001114 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001115 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1116 Context, SourceRange(Loc, Loc)));
1117 if (auto *ML = Context.getASTMutationListener())
1118 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001119 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001120 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001121 if (!Vars.empty()) {
1122 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1123 Vars);
1124 D->setAccess(AS_public);
1125 }
1126 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001127}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001128
Alexey Bataev7ff55242014-06-19 09:13:45 +00001129static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1130 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
1131 bool IsLoopIterVar = false) {
1132 if (DVar.RefExpr) {
1133 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1134 << getOpenMPClauseName(DVar.CKind);
1135 return;
1136 }
1137 enum {
1138 PDSA_StaticMemberShared,
1139 PDSA_StaticLocalVarShared,
1140 PDSA_LoopIterVarPrivate,
1141 PDSA_LoopIterVarLinear,
1142 PDSA_LoopIterVarLastprivate,
1143 PDSA_ConstVarShared,
1144 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001145 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001146 PDSA_LocalVarPrivate,
1147 PDSA_Implicit
1148 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001149 bool ReportHint = false;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001150 auto ReportLoc = VD->getLocation();
Alexey Bataev7ff55242014-06-19 09:13:45 +00001151 if (IsLoopIterVar) {
1152 if (DVar.CKind == OMPC_private)
1153 Reason = PDSA_LoopIterVarPrivate;
1154 else if (DVar.CKind == OMPC_lastprivate)
1155 Reason = PDSA_LoopIterVarLastprivate;
1156 else
1157 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001158 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
1159 Reason = PDSA_TaskVarFirstprivate;
1160 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001161 } else if (VD->isStaticLocal())
1162 Reason = PDSA_StaticLocalVarShared;
1163 else if (VD->isStaticDataMember())
1164 Reason = PDSA_StaticMemberShared;
1165 else if (VD->isFileVarDecl())
1166 Reason = PDSA_GlobalVarShared;
1167 else if (VD->getType().isConstant(SemaRef.getASTContext()))
1168 Reason = PDSA_ConstVarShared;
Alexey Bataevbae9a792014-06-27 10:37:06 +00001169 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001170 ReportHint = true;
1171 Reason = PDSA_LocalVarPrivate;
1172 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001173 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001174 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001175 << Reason << ReportHint
1176 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1177 } else if (DVar.ImplicitDSALoc.isValid()) {
1178 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1179 << getOpenMPClauseName(DVar.CKind);
1180 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001181}
1182
Alexey Bataev758e55e2013-09-06 18:03:48 +00001183namespace {
1184class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1185 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001186 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001187 bool ErrorFound;
1188 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001189 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001190 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001191
Alexey Bataev758e55e2013-09-06 18:03:48 +00001192public:
1193 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001194 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001195 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001196 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1197 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001198
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001199 auto DVar = Stack->getTopDSA(VD, false);
1200 // Check if the variable has explicit DSA set and stop analysis if it so.
1201 if (DVar.RefExpr) return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001202
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001203 auto ELoc = E->getExprLoc();
1204 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001205 // The default(none) clause requires that each variable that is referenced
1206 // in the construct, and does not have a predetermined data-sharing
1207 // attribute, must have its data-sharing attribute explicitly determined
1208 // by being listed in a data-sharing attribute clause.
1209 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001210 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001211 VarsWithInheritedDSA.count(VD) == 0) {
1212 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001213 return;
1214 }
1215
1216 // OpenMP [2.9.3.6, Restrictions, p.2]
1217 // A list item that appears in a reduction clause of the innermost
1218 // enclosing worksharing or parallel construct may not be accessed in an
1219 // explicit task.
Alexey Bataevf29276e2014-06-18 04:14:57 +00001220 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001221 [](OpenMPDirectiveKind K) -> bool {
1222 return isOpenMPParallelDirective(K) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001223 isOpenMPWorksharingDirective(K) ||
1224 isOpenMPTeamsDirective(K);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001225 },
1226 false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001227 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1228 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001229 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1230 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001231 return;
1232 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001233
1234 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001235 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001236 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001237 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001238 }
1239 }
1240 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001241 for (auto *C : S->clauses()) {
1242 // Skip analysis of arguments of implicitly defined firstprivate clause
1243 // for task directives.
1244 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1245 for (auto *CC : C->children()) {
1246 if (CC)
1247 Visit(CC);
1248 }
1249 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001250 }
1251 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001252 for (auto *C : S->children()) {
1253 if (C && !isa<OMPExecutableDirective>(C))
1254 Visit(C);
1255 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001256 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001257
1258 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001259 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001260 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1261 return VarsWithInheritedDSA;
1262 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001263
Alexey Bataev7ff55242014-06-19 09:13:45 +00001264 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1265 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001266};
Alexey Bataeved09d242014-05-28 05:53:51 +00001267} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001268
Alexey Bataevbae9a792014-06-27 10:37:06 +00001269void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001270 switch (DKind) {
1271 case OMPD_parallel: {
1272 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001273 QualType KmpInt32PtrTy =
1274 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001275 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001276 std::make_pair(".global_tid.", KmpInt32PtrTy),
1277 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1278 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001279 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001280 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1281 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001282 break;
1283 }
1284 case OMPD_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001285 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001286 std::make_pair(StringRef(), QualType()) // __context with shared vars
1287 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001288 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1289 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001290 break;
1291 }
1292 case OMPD_for: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001293 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001294 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001295 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001296 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1297 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001298 break;
1299 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001300 case OMPD_for_simd: {
1301 Sema::CapturedParamNameType Params[] = {
1302 std::make_pair(StringRef(), QualType()) // __context with shared vars
1303 };
1304 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1305 Params);
1306 break;
1307 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001308 case OMPD_sections: {
1309 Sema::CapturedParamNameType Params[] = {
1310 std::make_pair(StringRef(), QualType()) // __context with shared vars
1311 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001312 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1313 Params);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001314 break;
1315 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001316 case OMPD_section: {
1317 Sema::CapturedParamNameType Params[] = {
1318 std::make_pair(StringRef(), QualType()) // __context with shared vars
1319 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001320 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1321 Params);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001322 break;
1323 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001324 case OMPD_single: {
1325 Sema::CapturedParamNameType Params[] = {
1326 std::make_pair(StringRef(), QualType()) // __context with shared vars
1327 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001328 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1329 Params);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001330 break;
1331 }
Alexander Musman80c22892014-07-17 08:54:58 +00001332 case OMPD_master: {
1333 Sema::CapturedParamNameType Params[] = {
1334 std::make_pair(StringRef(), QualType()) // __context with shared vars
1335 };
1336 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1337 Params);
1338 break;
1339 }
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001340 case OMPD_critical: {
1341 Sema::CapturedParamNameType Params[] = {
1342 std::make_pair(StringRef(), QualType()) // __context with shared vars
1343 };
1344 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1345 Params);
1346 break;
1347 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001348 case OMPD_parallel_for: {
1349 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001350 QualType KmpInt32PtrTy =
1351 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataev4acb8592014-07-07 13:01:15 +00001352 Sema::CapturedParamNameType Params[] = {
1353 std::make_pair(".global_tid.", KmpInt32PtrTy),
1354 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1355 std::make_pair(StringRef(), QualType()) // __context with shared vars
1356 };
1357 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1358 Params);
1359 break;
1360 }
Alexander Musmane4e893b2014-09-23 09:33:00 +00001361 case OMPD_parallel_for_simd: {
1362 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001363 QualType KmpInt32PtrTy =
1364 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexander Musmane4e893b2014-09-23 09:33:00 +00001365 Sema::CapturedParamNameType Params[] = {
1366 std::make_pair(".global_tid.", KmpInt32PtrTy),
1367 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1368 std::make_pair(StringRef(), QualType()) // __context with shared vars
1369 };
1370 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1371 Params);
1372 break;
1373 }
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001374 case OMPD_parallel_sections: {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001375 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001376 QualType KmpInt32PtrTy =
1377 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001378 Sema::CapturedParamNameType Params[] = {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001379 std::make_pair(".global_tid.", KmpInt32PtrTy),
1380 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001381 std::make_pair(StringRef(), QualType()) // __context with shared vars
1382 };
1383 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1384 Params);
1385 break;
1386 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001387 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001388 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001389 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1390 FunctionProtoType::ExtProtoInfo EPI;
1391 EPI.Variadic = true;
1392 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001393 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001394 std::make_pair(".global_tid.", KmpInt32Ty),
1395 std::make_pair(".part_id.", KmpInt32Ty),
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001396 std::make_pair(".privates.",
1397 Context.VoidPtrTy.withConst().withRestrict()),
1398 std::make_pair(
1399 ".copy_fn.",
1400 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001401 std::make_pair(StringRef(), QualType()) // __context with shared vars
1402 };
1403 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1404 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001405 // Mark this captured region as inlined, because we don't use outlined
1406 // function directly.
1407 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1408 AlwaysInlineAttr::CreateImplicit(
1409 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001410 break;
1411 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001412 case OMPD_ordered: {
1413 Sema::CapturedParamNameType Params[] = {
1414 std::make_pair(StringRef(), QualType()) // __context with shared vars
1415 };
1416 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1417 Params);
1418 break;
1419 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001420 case OMPD_atomic: {
1421 Sema::CapturedParamNameType Params[] = {
1422 std::make_pair(StringRef(), QualType()) // __context with shared vars
1423 };
1424 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1425 Params);
1426 break;
1427 }
Michael Wong65f367f2015-07-21 13:44:28 +00001428 case OMPD_target_data:
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001429 case OMPD_target: {
1430 Sema::CapturedParamNameType Params[] = {
1431 std::make_pair(StringRef(), QualType()) // __context with shared vars
1432 };
1433 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1434 Params);
1435 break;
1436 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001437 case OMPD_teams: {
1438 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001439 QualType KmpInt32PtrTy =
1440 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataev13314bf2014-10-09 04:18:56 +00001441 Sema::CapturedParamNameType Params[] = {
1442 std::make_pair(".global_tid.", KmpInt32PtrTy),
1443 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1444 std::make_pair(StringRef(), QualType()) // __context with shared vars
1445 };
1446 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1447 Params);
1448 break;
1449 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001450 case OMPD_taskgroup: {
1451 Sema::CapturedParamNameType Params[] = {
1452 std::make_pair(StringRef(), QualType()) // __context with shared vars
1453 };
1454 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1455 Params);
1456 break;
1457 }
Alexey Bataev49f6e782015-12-01 04:18:41 +00001458 case OMPD_taskloop: {
1459 Sema::CapturedParamNameType Params[] = {
1460 std::make_pair(StringRef(), QualType()) // __context with shared vars
1461 };
1462 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1463 Params);
1464 break;
1465 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001466 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001467 case OMPD_taskyield:
1468 case OMPD_barrier:
1469 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001470 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001471 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001472 case OMPD_flush:
Alexey Bataev9959db52014-05-06 10:08:46 +00001473 llvm_unreachable("OpenMP Directive is not allowed");
1474 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001475 llvm_unreachable("Unknown OpenMP directive");
1476 }
1477}
1478
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001479StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1480 ArrayRef<OMPClause *> Clauses) {
1481 if (!S.isUsable()) {
1482 ActOnCapturedRegionError();
1483 return StmtError();
1484 }
Alexey Bataev040d5402015-05-12 08:35:28 +00001485 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001486 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001487 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001488 Clause->getClauseKind() == OMPC_copyprivate ||
1489 (getLangOpts().OpenMPUseTLS &&
1490 getASTContext().getTargetInfo().isTLSSupported() &&
1491 Clause->getClauseKind() == OMPC_copyin)) {
1492 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001493 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001494 for (auto *VarRef : Clause->children()) {
1495 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001496 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001497 }
1498 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001499 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev040d5402015-05-12 08:35:28 +00001500 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
1501 Clause->getClauseKind() == OMPC_schedule) {
1502 // Mark all variables in private list clauses as used in inner region.
1503 // Required for proper codegen of combined directives.
1504 // TODO: add processing for other clauses.
1505 if (auto *E = cast_or_null<Expr>(
1506 cast<OMPScheduleClause>(Clause)->getHelperChunkSize())) {
1507 MarkDeclarationsReferencedInExpr(E);
1508 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001509 }
1510 }
1511 return ActOnCapturedRegionEnd(S.get());
1512}
1513
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001514static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1515 OpenMPDirectiveKind CurrentRegion,
1516 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001517 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001518 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001519 // Allowed nesting of constructs
1520 // +------------------+-----------------+------------------------------------+
1521 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1522 // +------------------+-----------------+------------------------------------+
1523 // | parallel | parallel | * |
1524 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001525 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001526 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001527 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001528 // | parallel | simd | * |
1529 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001530 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001531 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001532 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001533 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001534 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001535 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001536 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001537 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001538 // | parallel | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001539 // | parallel | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001540 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001541 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001542 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001543 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001544 // | parallel | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001545 // | parallel | cancellation | |
1546 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001547 // | parallel | cancel | ! |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001548 // | parallel | taskloop | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001549 // +------------------+-----------------+------------------------------------+
1550 // | for | parallel | * |
1551 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001552 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001553 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001554 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001555 // | for | simd | * |
1556 // | for | sections | + |
1557 // | for | section | + |
1558 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001559 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001560 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001561 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001562 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001563 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001564 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001565 // | for | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001566 // | for | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001567 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001568 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001569 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001570 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001571 // | for | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001572 // | for | cancellation | |
1573 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001574 // | for | cancel | ! |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001575 // | for | taskloop | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001576 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001577 // | master | parallel | * |
1578 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001579 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001580 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001581 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001582 // | master | simd | * |
1583 // | master | sections | + |
1584 // | master | section | + |
1585 // | master | single | + |
1586 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001587 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001588 // | master |parallel sections| * |
1589 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001590 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001591 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001592 // | master | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001593 // | master | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001594 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001595 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001596 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001597 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001598 // | master | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001599 // | master | cancellation | |
1600 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001601 // | master | cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001602 // | master | taskloop | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001603 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001604 // | critical | parallel | * |
1605 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001606 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001607 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001608 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001609 // | critical | simd | * |
1610 // | critical | sections | + |
1611 // | critical | section | + |
1612 // | critical | single | + |
1613 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001614 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001615 // | critical |parallel sections| * |
1616 // | critical | task | * |
1617 // | critical | taskyield | * |
1618 // | critical | barrier | + |
1619 // | critical | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001620 // | critical | taskgroup | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001621 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001622 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001623 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001624 // | critical | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001625 // | critical | cancellation | |
1626 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001627 // | critical | cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001628 // | critical | taskloop | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001629 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001630 // | simd | parallel | |
1631 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001632 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001633 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001634 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001635 // | simd | simd | |
1636 // | simd | sections | |
1637 // | simd | section | |
1638 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001639 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001640 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001641 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001642 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001643 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001644 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001645 // | simd | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001646 // | simd | taskgroup | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001647 // | simd | flush | |
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001648 // | simd | ordered | + (with simd clause) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001649 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001650 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001651 // | simd | teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001652 // | simd | cancellation | |
1653 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001654 // | simd | cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001655 // | simd | taskloop | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001656 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001657 // | for simd | parallel | |
1658 // | for simd | for | |
1659 // | for simd | for simd | |
1660 // | for simd | master | |
1661 // | for simd | critical | |
1662 // | for simd | simd | |
1663 // | for simd | sections | |
1664 // | for simd | section | |
1665 // | for simd | single | |
1666 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001667 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001668 // | for simd |parallel sections| |
1669 // | for simd | task | |
1670 // | for simd | taskyield | |
1671 // | for simd | barrier | |
1672 // | for simd | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001673 // | for simd | taskgroup | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001674 // | for simd | flush | |
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001675 // | for simd | ordered | + (with simd clause) |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001676 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001677 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001678 // | for simd | teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001679 // | for simd | cancellation | |
1680 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001681 // | for simd | cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001682 // | for simd | taskloop | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001683 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001684 // | parallel for simd| parallel | |
1685 // | parallel for simd| for | |
1686 // | parallel for simd| for simd | |
1687 // | parallel for simd| master | |
1688 // | parallel for simd| critical | |
1689 // | parallel for simd| simd | |
1690 // | parallel for simd| sections | |
1691 // | parallel for simd| section | |
1692 // | parallel for simd| single | |
1693 // | parallel for simd| parallel for | |
1694 // | parallel for simd|parallel for simd| |
1695 // | parallel for simd|parallel sections| |
1696 // | parallel for simd| task | |
1697 // | parallel for simd| taskyield | |
1698 // | parallel for simd| barrier | |
1699 // | parallel for simd| taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001700 // | parallel for simd| taskgroup | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001701 // | parallel for simd| flush | |
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001702 // | parallel for simd| ordered | + (with simd clause) |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001703 // | parallel for simd| atomic | |
1704 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001705 // | parallel for simd| teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001706 // | parallel for simd| cancellation | |
1707 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001708 // | parallel for simd| cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001709 // | parallel for simd| taskloop | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001710 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001711 // | sections | parallel | * |
1712 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001713 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001714 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001715 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001716 // | sections | simd | * |
1717 // | sections | sections | + |
1718 // | sections | section | * |
1719 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001720 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001721 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001722 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001723 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001724 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001725 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001726 // | sections | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001727 // | sections | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001728 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001729 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001730 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001731 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001732 // | sections | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001733 // | sections | cancellation | |
1734 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001735 // | sections | cancel | ! |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001736 // | sections | taskloop | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001737 // +------------------+-----------------+------------------------------------+
1738 // | section | parallel | * |
1739 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001740 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001741 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001742 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001743 // | section | simd | * |
1744 // | section | sections | + |
1745 // | section | section | + |
1746 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001747 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001748 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001749 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001750 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001751 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001752 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001753 // | section | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001754 // | section | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001755 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001756 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001757 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001758 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001759 // | section | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001760 // | section | cancellation | |
1761 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001762 // | section | cancel | ! |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001763 // | section | taskloop | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001764 // +------------------+-----------------+------------------------------------+
1765 // | single | parallel | * |
1766 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001767 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001768 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001769 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001770 // | single | simd | * |
1771 // | single | sections | + |
1772 // | single | section | + |
1773 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001774 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001775 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001776 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001777 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001778 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001779 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001780 // | single | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001781 // | single | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001782 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001783 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001784 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001785 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001786 // | single | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001787 // | single | cancellation | |
1788 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001789 // | single | cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001790 // | single | taskloop | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001791 // +------------------+-----------------+------------------------------------+
1792 // | parallel for | parallel | * |
1793 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001794 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001795 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001796 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001797 // | parallel for | simd | * |
1798 // | parallel for | sections | + |
1799 // | parallel for | section | + |
1800 // | parallel for | single | + |
1801 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001802 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001803 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001804 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001805 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001806 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001807 // | parallel for | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001808 // | parallel for | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001809 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001810 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001811 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001812 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001813 // | parallel for | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001814 // | parallel for | cancellation | |
1815 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001816 // | parallel for | cancel | ! |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001817 // | parallel for | taskloop | * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001818 // +------------------+-----------------+------------------------------------+
1819 // | parallel sections| parallel | * |
1820 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001821 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001822 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001823 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001824 // | parallel sections| simd | * |
1825 // | parallel sections| sections | + |
1826 // | parallel sections| section | * |
1827 // | parallel sections| single | + |
1828 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001829 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001830 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001831 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001832 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001833 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001834 // | parallel sections| taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001835 // | parallel sections| taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001836 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001837 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001838 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001839 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001840 // | parallel sections| teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001841 // | parallel sections| cancellation | |
1842 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001843 // | parallel sections| cancel | ! |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001844 // | parallel sections| taskloop | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001845 // +------------------+-----------------+------------------------------------+
1846 // | task | parallel | * |
1847 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001848 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001849 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001850 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001851 // | task | simd | * |
1852 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001853 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001854 // | task | single | + |
1855 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001856 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001857 // | task |parallel sections| * |
1858 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001859 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001860 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001861 // | task | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001862 // | task | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001863 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001864 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001865 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001866 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001867 // | task | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001868 // | task | cancellation | |
Alexey Bataev80909872015-07-02 11:25:17 +00001869 // | | point | ! |
1870 // | task | cancel | ! |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001871 // | task | taskloop | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001872 // +------------------+-----------------+------------------------------------+
1873 // | ordered | parallel | * |
1874 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001875 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001876 // | ordered | master | * |
1877 // | ordered | critical | * |
1878 // | ordered | simd | * |
1879 // | ordered | sections | + |
1880 // | ordered | section | + |
1881 // | ordered | single | + |
1882 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001883 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001884 // | ordered |parallel sections| * |
1885 // | ordered | task | * |
1886 // | ordered | taskyield | * |
1887 // | ordered | barrier | + |
1888 // | ordered | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001889 // | ordered | taskgroup | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001890 // | ordered | flush | * |
1891 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001892 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001893 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001894 // | ordered | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001895 // | ordered | cancellation | |
1896 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001897 // | ordered | cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001898 // | ordered | taskloop | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001899 // +------------------+-----------------+------------------------------------+
1900 // | atomic | parallel | |
1901 // | atomic | for | |
1902 // | atomic | for simd | |
1903 // | atomic | master | |
1904 // | atomic | critical | |
1905 // | atomic | simd | |
1906 // | atomic | sections | |
1907 // | atomic | section | |
1908 // | atomic | single | |
1909 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001910 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001911 // | atomic |parallel sections| |
1912 // | atomic | task | |
1913 // | atomic | taskyield | |
1914 // | atomic | barrier | |
1915 // | atomic | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001916 // | atomic | taskgroup | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001917 // | atomic | flush | |
1918 // | atomic | ordered | |
1919 // | atomic | atomic | |
1920 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001921 // | atomic | teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001922 // | atomic | cancellation | |
1923 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001924 // | atomic | cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001925 // | atomic | taskloop | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001926 // +------------------+-----------------+------------------------------------+
1927 // | target | parallel | * |
1928 // | target | for | * |
1929 // | target | for simd | * |
1930 // | target | master | * |
1931 // | target | critical | * |
1932 // | target | simd | * |
1933 // | target | sections | * |
1934 // | target | section | * |
1935 // | target | single | * |
1936 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001937 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001938 // | target |parallel sections| * |
1939 // | target | task | * |
1940 // | target | taskyield | * |
1941 // | target | barrier | * |
1942 // | target | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001943 // | target | taskgroup | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001944 // | target | flush | * |
1945 // | target | ordered | * |
1946 // | target | atomic | * |
1947 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001948 // | target | teams | * |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001949 // | target | cancellation | |
1950 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001951 // | target | cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001952 // | target | taskloop | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001953 // +------------------+-----------------+------------------------------------+
1954 // | teams | parallel | * |
1955 // | teams | for | + |
1956 // | teams | for simd | + |
1957 // | teams | master | + |
1958 // | teams | critical | + |
1959 // | teams | simd | + |
1960 // | teams | sections | + |
1961 // | teams | section | + |
1962 // | teams | single | + |
1963 // | teams | parallel for | * |
1964 // | teams |parallel for simd| * |
1965 // | teams |parallel sections| * |
1966 // | teams | task | + |
1967 // | teams | taskyield | + |
1968 // | teams | barrier | + |
1969 // | teams | taskwait | + |
Alexey Bataev80909872015-07-02 11:25:17 +00001970 // | teams | taskgroup | + |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001971 // | teams | flush | + |
1972 // | teams | ordered | + |
1973 // | teams | atomic | + |
1974 // | teams | target | + |
1975 // | teams | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001976 // | teams | cancellation | |
1977 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001978 // | teams | cancel | |
Alexey Bataev49f6e782015-12-01 04:18:41 +00001979 // | teams | taskloop | + |
1980 // +------------------+-----------------+------------------------------------+
1981 // | taskloop | parallel | * |
1982 // | taskloop | for | + |
1983 // | taskloop | for simd | + |
1984 // | taskloop | master | + |
1985 // | taskloop | critical | * |
1986 // | taskloop | simd | * |
1987 // | taskloop | sections | + |
1988 // | taskloop | section | + |
1989 // | taskloop | single | + |
1990 // | taskloop | parallel for | * |
1991 // | taskloop |parallel for simd| * |
1992 // | taskloop |parallel sections| * |
1993 // | taskloop | task | * |
1994 // | taskloop | taskyield | * |
1995 // | taskloop | barrier | + |
1996 // | taskloop | taskwait | * |
1997 // | taskloop | taskgroup | * |
1998 // | taskloop | flush | * |
1999 // | taskloop | ordered | + |
2000 // | taskloop | atomic | * |
2001 // | taskloop | target | * |
2002 // | taskloop | teams | + |
2003 // | taskloop | cancellation | |
2004 // | | point | |
2005 // | taskloop | cancel | |
2006 // | taskloop | taskloop | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00002007 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00002008 if (Stack->getCurScope()) {
2009 auto ParentRegion = Stack->getParentDirective();
2010 bool NestingProhibited = false;
2011 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002012 enum {
2013 NoRecommend,
2014 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002015 ShouldBeInOrderedRegion,
2016 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002017 } Recommend = NoRecommend;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002018 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002019 // OpenMP [2.16, Nesting of Regions]
2020 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002021 // OpenMP [2.8.1,simd Construct, Restrictions]
2022 // An ordered construct with the simd clause is the only OpenMP construct
2023 // that can appear in the simd region.
Alexey Bataev549210e2014-06-24 04:39:47 +00002024 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
2025 return true;
2026 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002027 if (ParentRegion == OMPD_atomic) {
2028 // OpenMP [2.16, Nesting of Regions]
2029 // OpenMP constructs may not be nested inside an atomic region.
2030 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2031 return true;
2032 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002033 if (CurrentRegion == OMPD_section) {
2034 // OpenMP [2.7.2, sections Construct, Restrictions]
2035 // Orphaned section directives are prohibited. That is, the section
2036 // directives must appear within the sections construct and must not be
2037 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002038 if (ParentRegion != OMPD_sections &&
2039 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002040 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2041 << (ParentRegion != OMPD_unknown)
2042 << getOpenMPDirectiveName(ParentRegion);
2043 return true;
2044 }
2045 return false;
2046 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002047 // Allow some constructs to be orphaned (they could be used in functions,
2048 // called from OpenMP regions with the required preconditions).
2049 if (ParentRegion == OMPD_unknown)
2050 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002051 if (CurrentRegion == OMPD_cancellation_point ||
2052 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002053 // OpenMP [2.16, Nesting of Regions]
2054 // A cancellation point construct for which construct-type-clause is
2055 // taskgroup must be nested inside a task construct. A cancellation
2056 // point construct for which construct-type-clause is not taskgroup must
2057 // be closely nested inside an OpenMP construct that matches the type
2058 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002059 // A cancel construct for which construct-type-clause is taskgroup must be
2060 // nested inside a task construct. A cancel construct for which
2061 // construct-type-clause is not taskgroup must be closely nested inside an
2062 // OpenMP construct that matches the type specified in
2063 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002064 NestingProhibited =
2065 !((CancelRegion == OMPD_parallel && ParentRegion == OMPD_parallel) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002066 (CancelRegion == OMPD_for &&
2067 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002068 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2069 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002070 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2071 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002072 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002073 // OpenMP [2.16, Nesting of Regions]
2074 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002075 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002076 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev49f6e782015-12-01 04:18:41 +00002077 ParentRegion == OMPD_task ||
2078 ParentRegion == OMPD_taskloop;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002079 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2080 // OpenMP [2.16, Nesting of Regions]
2081 // A critical region may not be nested (closely or otherwise) inside a
2082 // critical region with the same name. Note that this restriction is not
2083 // sufficient to prevent deadlock.
2084 SourceLocation PreviousCriticalLoc;
2085 bool DeadLock =
2086 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
2087 OpenMPDirectiveKind K,
2088 const DeclarationNameInfo &DNI,
2089 SourceLocation Loc)
2090 ->bool {
2091 if (K == OMPD_critical &&
2092 DNI.getName() == CurrentName.getName()) {
2093 PreviousCriticalLoc = Loc;
2094 return true;
2095 } else
2096 return false;
2097 },
2098 false /* skip top directive */);
2099 if (DeadLock) {
2100 SemaRef.Diag(StartLoc,
2101 diag::err_omp_prohibited_region_critical_same_name)
2102 << CurrentName.getName();
2103 if (PreviousCriticalLoc.isValid())
2104 SemaRef.Diag(PreviousCriticalLoc,
2105 diag::note_omp_previous_critical_region);
2106 return true;
2107 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002108 } else if (CurrentRegion == OMPD_barrier) {
2109 // OpenMP [2.16, Nesting of Regions]
2110 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002111 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002112 NestingProhibited =
2113 isOpenMPWorksharingDirective(ParentRegion) ||
2114 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
Alexey Bataev49f6e782015-12-01 04:18:41 +00002115 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered ||
2116 ParentRegion == OMPD_taskloop;
Alexander Musman80c22892014-07-17 08:54:58 +00002117 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00002118 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002119 // OpenMP [2.16, Nesting of Regions]
2120 // A worksharing region may not be closely nested inside a worksharing,
2121 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002122 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00002123 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002124 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
Alexey Bataev49f6e782015-12-01 04:18:41 +00002125 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered ||
2126 ParentRegion == OMPD_taskloop;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002127 Recommend = ShouldBeInParallelRegion;
2128 } else if (CurrentRegion == OMPD_ordered) {
2129 // OpenMP [2.16, Nesting of Regions]
2130 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002131 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002132 // An ordered region must be closely nested inside a loop region (or
2133 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002134 // OpenMP [2.8.1,simd Construct, Restrictions]
2135 // An ordered construct with the simd clause is the only OpenMP construct
2136 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002137 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00002138 ParentRegion == OMPD_task ||
Alexey Bataev49f6e782015-12-01 04:18:41 +00002139 ParentRegion == OMPD_taskloop ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002140 !(isOpenMPSimdDirective(ParentRegion) ||
2141 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002142 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002143 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
2144 // OpenMP [2.16, Nesting of Regions]
2145 // If specified, a teams construct must be contained within a target
2146 // construct.
2147 NestingProhibited = ParentRegion != OMPD_target;
2148 Recommend = ShouldBeInTargetRegion;
2149 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2150 }
2151 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
2152 // OpenMP [2.16, Nesting of Regions]
2153 // distribute, parallel, parallel sections, parallel workshare, and the
2154 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2155 // constructs that can be closely nested in the teams region.
2156 // TODO: add distribute directive.
2157 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
2158 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002159 }
2160 if (NestingProhibited) {
2161 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002162 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
2163 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00002164 return true;
2165 }
2166 }
2167 return false;
2168}
2169
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002170static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2171 ArrayRef<OMPClause *> Clauses,
2172 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2173 bool ErrorFound = false;
2174 unsigned NamedModifiersNumber = 0;
2175 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2176 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002177 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002178 for (const auto *C : Clauses) {
2179 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2180 // At most one if clause without a directive-name-modifier can appear on
2181 // the directive.
2182 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2183 if (FoundNameModifiers[CurNM]) {
2184 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2185 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2186 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2187 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002188 } else if (CurNM != OMPD_unknown) {
2189 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002190 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002191 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002192 FoundNameModifiers[CurNM] = IC;
2193 if (CurNM == OMPD_unknown)
2194 continue;
2195 // Check if the specified name modifier is allowed for the current
2196 // directive.
2197 // At most one if clause with the particular directive-name-modifier can
2198 // appear on the directive.
2199 bool MatchFound = false;
2200 for (auto NM : AllowedNameModifiers) {
2201 if (CurNM == NM) {
2202 MatchFound = true;
2203 break;
2204 }
2205 }
2206 if (!MatchFound) {
2207 S.Diag(IC->getNameModifierLoc(),
2208 diag::err_omp_wrong_if_directive_name_modifier)
2209 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2210 ErrorFound = true;
2211 }
2212 }
2213 }
2214 // If any if clause on the directive includes a directive-name-modifier then
2215 // all if clauses on the directive must include a directive-name-modifier.
2216 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2217 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2218 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2219 diag::err_omp_no_more_if_clause);
2220 } else {
2221 std::string Values;
2222 std::string Sep(", ");
2223 unsigned AllowedCnt = 0;
2224 unsigned TotalAllowedNum =
2225 AllowedNameModifiers.size() - NamedModifiersNumber;
2226 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2227 ++Cnt) {
2228 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2229 if (!FoundNameModifiers[NM]) {
2230 Values += "'";
2231 Values += getOpenMPDirectiveName(NM);
2232 Values += "'";
2233 if (AllowedCnt + 2 == TotalAllowedNum)
2234 Values += " or ";
2235 else if (AllowedCnt + 1 != TotalAllowedNum)
2236 Values += Sep;
2237 ++AllowedCnt;
2238 }
2239 }
2240 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2241 diag::err_omp_unnamed_if_clause)
2242 << (TotalAllowedNum > 1) << Values;
2243 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002244 for (auto Loc : NameModifierLoc) {
2245 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2246 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002247 ErrorFound = true;
2248 }
2249 return ErrorFound;
2250}
2251
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002252StmtResult Sema::ActOnOpenMPExecutableDirective(
2253 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2254 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2255 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002256 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002257 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2258 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002259 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002260
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002261 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00002262 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002263 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002264 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002265 if (AStmt) {
2266 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2267
2268 // Check default data sharing attributes for referenced variables.
2269 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2270 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2271 if (DSAChecker.isErrorFound())
2272 return StmtError();
2273 // Generate list of implicitly defined firstprivate variables.
2274 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002275
2276 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2277 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2278 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2279 SourceLocation(), SourceLocation())) {
2280 ClausesWithImplicit.push_back(Implicit);
2281 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2282 DSAChecker.getImplicitFirstprivate().size();
2283 } else
2284 ErrorFound = true;
2285 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002286 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002287
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002288 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002289 switch (Kind) {
2290 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002291 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2292 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002293 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002294 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002295 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002296 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2297 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002298 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002299 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002300 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2301 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002302 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002303 case OMPD_for_simd:
2304 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2305 EndLoc, VarsWithInheritedDSA);
2306 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002307 case OMPD_sections:
2308 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2309 EndLoc);
2310 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002311 case OMPD_section:
2312 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002313 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002314 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2315 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002316 case OMPD_single:
2317 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2318 EndLoc);
2319 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002320 case OMPD_master:
2321 assert(ClausesWithImplicit.empty() &&
2322 "No clauses are allowed for 'omp master' directive");
2323 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2324 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002325 case OMPD_critical:
2326 assert(ClausesWithImplicit.empty() &&
2327 "No clauses are allowed for 'omp critical' directive");
2328 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
2329 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002330 case OMPD_parallel_for:
2331 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2332 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002333 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002334 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002335 case OMPD_parallel_for_simd:
2336 Res = ActOnOpenMPParallelForSimdDirective(
2337 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002338 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002339 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002340 case OMPD_parallel_sections:
2341 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2342 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002343 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002344 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002345 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002346 Res =
2347 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002348 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002349 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002350 case OMPD_taskyield:
2351 assert(ClausesWithImplicit.empty() &&
2352 "No clauses are allowed for 'omp taskyield' directive");
2353 assert(AStmt == nullptr &&
2354 "No associated statement allowed for 'omp taskyield' directive");
2355 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2356 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002357 case OMPD_barrier:
2358 assert(ClausesWithImplicit.empty() &&
2359 "No clauses are allowed for 'omp barrier' directive");
2360 assert(AStmt == nullptr &&
2361 "No associated statement allowed for 'omp barrier' directive");
2362 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2363 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002364 case OMPD_taskwait:
2365 assert(ClausesWithImplicit.empty() &&
2366 "No clauses are allowed for 'omp taskwait' directive");
2367 assert(AStmt == nullptr &&
2368 "No associated statement allowed for 'omp taskwait' directive");
2369 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2370 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002371 case OMPD_taskgroup:
2372 assert(ClausesWithImplicit.empty() &&
2373 "No clauses are allowed for 'omp taskgroup' directive");
2374 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2375 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002376 case OMPD_flush:
2377 assert(AStmt == nullptr &&
2378 "No associated statement allowed for 'omp flush' directive");
2379 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2380 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002381 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002382 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2383 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002384 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002385 case OMPD_atomic:
2386 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2387 EndLoc);
2388 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002389 case OMPD_teams:
2390 Res =
2391 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2392 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002393 case OMPD_target:
2394 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2395 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002396 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002397 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002398 case OMPD_cancellation_point:
2399 assert(ClausesWithImplicit.empty() &&
2400 "No clauses are allowed for 'omp cancellation point' directive");
2401 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2402 "cancellation point' directive");
2403 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2404 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002405 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002406 assert(AStmt == nullptr &&
2407 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002408 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2409 CancelRegion);
2410 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002411 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002412 case OMPD_target_data:
2413 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2414 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002415 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002416 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002417 case OMPD_taskloop:
2418 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2419 EndLoc, VarsWithInheritedDSA);
2420 AllowedNameModifiers.push_back(OMPD_taskloop);
2421 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002422 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002423 llvm_unreachable("OpenMP Directive is not allowed");
2424 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002425 llvm_unreachable("Unknown OpenMP directive");
2426 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002427
Alexey Bataev4acb8592014-07-07 13:01:15 +00002428 for (auto P : VarsWithInheritedDSA) {
2429 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2430 << P.first << P.second->getSourceRange();
2431 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002432 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2433
2434 if (!AllowedNameModifiers.empty())
2435 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2436 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002437
Alexey Bataeved09d242014-05-28 05:53:51 +00002438 if (ErrorFound)
2439 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002440 return Res;
2441}
2442
2443StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2444 Stmt *AStmt,
2445 SourceLocation StartLoc,
2446 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002447 if (!AStmt)
2448 return StmtError();
2449
Alexey Bataev9959db52014-05-06 10:08:46 +00002450 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2451 // 1.2.2 OpenMP Language Terminology
2452 // Structured block - An executable statement with a single entry at the
2453 // top and a single exit at the bottom.
2454 // The point of exit cannot be a branch out of the structured block.
2455 // longjmp() and throw() must not violate the entry/exit criteria.
2456 CS->getCapturedDecl()->setNothrow();
2457
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002458 getCurFunction()->setHasBranchProtectedScope();
2459
Alexey Bataev25e5b442015-09-15 12:52:43 +00002460 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2461 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002462}
2463
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002464namespace {
2465/// \brief Helper class for checking canonical form of the OpenMP loops and
2466/// extracting iteration space of each loop in the loop nest, that will be used
2467/// for IR generation.
2468class OpenMPIterationSpaceChecker {
2469 /// \brief Reference to Sema.
2470 Sema &SemaRef;
2471 /// \brief A location for diagnostics (when there is no some better location).
2472 SourceLocation DefaultLoc;
2473 /// \brief A location for diagnostics (when increment is not compatible).
2474 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002475 /// \brief A source location for referring to loop init later.
2476 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002477 /// \brief A source location for referring to condition later.
2478 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002479 /// \brief A source location for referring to increment later.
2480 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002481 /// \brief Loop variable.
2482 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002483 /// \brief Reference to loop variable.
2484 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002485 /// \brief Lower bound (initializer for the var).
2486 Expr *LB;
2487 /// \brief Upper bound.
2488 Expr *UB;
2489 /// \brief Loop step (increment).
2490 Expr *Step;
2491 /// \brief This flag is true when condition is one of:
2492 /// Var < UB
2493 /// Var <= UB
2494 /// UB > Var
2495 /// UB >= Var
2496 bool TestIsLessOp;
2497 /// \brief This flag is true when condition is strict ( < or > ).
2498 bool TestIsStrictOp;
2499 /// \brief This flag is true when step is subtracted on each iteration.
2500 bool SubtractStep;
2501
2502public:
2503 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2504 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00002505 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
2506 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002507 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
2508 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002509 /// \brief Check init-expr for canonical loop form and save loop counter
2510 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002511 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002512 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2513 /// for less/greater and for strict/non-strict comparison.
2514 bool CheckCond(Expr *S);
2515 /// \brief Check incr-expr for canonical loop form and return true if it
2516 /// does not conform, otherwise save loop step (#Step).
2517 bool CheckInc(Expr *S);
2518 /// \brief Return the loop counter variable.
2519 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002520 /// \brief Return the reference expression to loop counter variable.
2521 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002522 /// \brief Source range of the loop init.
2523 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2524 /// \brief Source range of the loop condition.
2525 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2526 /// \brief Source range of the loop increment.
2527 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2528 /// \brief True if the step should be subtracted.
2529 bool ShouldSubtractStep() const { return SubtractStep; }
2530 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002531 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002532 /// \brief Build the precondition expression for the loops.
2533 Expr *BuildPreCond(Scope *S, Expr *Cond) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002534 /// \brief Build reference expression to the counter be used for codegen.
2535 Expr *BuildCounterVar() const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002536 /// \brief Build reference expression to the private counter be used for
2537 /// codegen.
2538 Expr *BuildPrivateCounterVar() const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002539 /// \brief Build initization of the counter be used for codegen.
2540 Expr *BuildCounterInit() const;
2541 /// \brief Build step of the counter be used for codegen.
2542 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002543 /// \brief Return true if any expression is dependent.
2544 bool Dependent() const;
2545
2546private:
2547 /// \brief Check the right-hand side of an assignment in the increment
2548 /// expression.
2549 bool CheckIncRHS(Expr *RHS);
2550 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002551 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002552 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002553 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002554 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002555 /// \brief Helper to set loop increment.
2556 bool SetStep(Expr *NewStep, bool Subtract);
2557};
2558
2559bool OpenMPIterationSpaceChecker::Dependent() const {
2560 if (!Var) {
2561 assert(!LB && !UB && !Step);
2562 return false;
2563 }
2564 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2565 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2566}
2567
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002568template <typename T>
2569static T *getExprAsWritten(T *E) {
2570 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2571 E = ExprTemp->getSubExpr();
2572
2573 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2574 E = MTE->GetTemporaryExpr();
2575
2576 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2577 E = Binder->getSubExpr();
2578
2579 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2580 E = ICE->getSubExprAsWritten();
2581 return E->IgnoreParens();
2582}
2583
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002584bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2585 DeclRefExpr *NewVarRefExpr,
2586 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002587 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002588 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2589 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002590 if (!NewVar || !NewLB)
2591 return true;
2592 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002593 VarRef = NewVarRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002594 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2595 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002596 if ((Ctor->isCopyOrMoveConstructor() ||
2597 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2598 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002599 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002600 LB = NewLB;
2601 return false;
2602}
2603
2604bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002605 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002606 // State consistency checking to ensure correct usage.
2607 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2608 !TestIsLessOp && !TestIsStrictOp);
2609 if (!NewUB)
2610 return true;
2611 UB = NewUB;
2612 TestIsLessOp = LessOp;
2613 TestIsStrictOp = StrictOp;
2614 ConditionSrcRange = SR;
2615 ConditionLoc = SL;
2616 return false;
2617}
2618
2619bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2620 // State consistency checking to ensure correct usage.
2621 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2622 if (!NewStep)
2623 return true;
2624 if (!NewStep->isValueDependent()) {
2625 // Check that the step is integer expression.
2626 SourceLocation StepLoc = NewStep->getLocStart();
2627 ExprResult Val =
2628 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2629 if (Val.isInvalid())
2630 return true;
2631 NewStep = Val.get();
2632
2633 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2634 // If test-expr is of form var relational-op b and relational-op is < or
2635 // <= then incr-expr must cause var to increase on each iteration of the
2636 // loop. If test-expr is of form var relational-op b and relational-op is
2637 // > or >= then incr-expr must cause var to decrease on each iteration of
2638 // the loop.
2639 // If test-expr is of form b relational-op var and relational-op is < or
2640 // <= then incr-expr must cause var to decrease on each iteration of the
2641 // loop. If test-expr is of form b relational-op var and relational-op is
2642 // > or >= then incr-expr must cause var to increase on each iteration of
2643 // the loop.
2644 llvm::APSInt Result;
2645 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2646 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2647 bool IsConstNeg =
2648 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002649 bool IsConstPos =
2650 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002651 bool IsConstZero = IsConstant && !Result.getBoolValue();
2652 if (UB && (IsConstZero ||
2653 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002654 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002655 SemaRef.Diag(NewStep->getExprLoc(),
2656 diag::err_omp_loop_incr_not_compatible)
2657 << Var << TestIsLessOp << NewStep->getSourceRange();
2658 SemaRef.Diag(ConditionLoc,
2659 diag::note_omp_loop_cond_requres_compatible_incr)
2660 << TestIsLessOp << ConditionSrcRange;
2661 return true;
2662 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002663 if (TestIsLessOp == Subtract) {
2664 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2665 NewStep).get();
2666 Subtract = !Subtract;
2667 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002668 }
2669
2670 Step = NewStep;
2671 SubtractStep = Subtract;
2672 return false;
2673}
2674
Alexey Bataev9c821032015-04-30 04:23:23 +00002675bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002676 // Check init-expr for canonical loop form and save loop counter
2677 // variable - #Var and its initialization value - #LB.
2678 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2679 // var = lb
2680 // integer-type var = lb
2681 // random-access-iterator-type var = lb
2682 // pointer-type var = lb
2683 //
2684 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002685 if (EmitDiags) {
2686 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2687 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002688 return true;
2689 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002690 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002691 if (Expr *E = dyn_cast<Expr>(S))
2692 S = E->IgnoreParens();
2693 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2694 if (BO->getOpcode() == BO_Assign)
2695 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002696 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002697 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002698 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2699 if (DS->isSingleDecl()) {
2700 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00002701 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002702 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002703 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002704 SemaRef.Diag(S->getLocStart(),
2705 diag::ext_omp_loop_not_canonical_init)
2706 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002707 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002708 }
2709 }
2710 }
2711 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2712 if (CE->getOperator() == OO_Equal)
2713 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002714 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2715 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002716
Alexey Bataev9c821032015-04-30 04:23:23 +00002717 if (EmitDiags) {
2718 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2719 << S->getSourceRange();
2720 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002721 return true;
2722}
2723
Alexey Bataev23b69422014-06-18 07:08:49 +00002724/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002725/// variable (which may be the loop variable) if possible.
2726static const VarDecl *GetInitVarDecl(const Expr *E) {
2727 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002728 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002729 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002730 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2731 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002732 if ((Ctor->isCopyOrMoveConstructor() ||
2733 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2734 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002735 E = CE->getArg(0)->IgnoreParenImpCasts();
2736 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2737 if (!DRE)
2738 return nullptr;
2739 return dyn_cast<VarDecl>(DRE->getDecl());
2740}
2741
2742bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2743 // Check test-expr for canonical form, save upper-bound UB, flags for
2744 // less/greater and for strict/non-strict comparison.
2745 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2746 // var relational-op b
2747 // b relational-op var
2748 //
2749 if (!S) {
2750 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2751 return true;
2752 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002753 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002754 SourceLocation CondLoc = S->getLocStart();
2755 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2756 if (BO->isRelationalOp()) {
2757 if (GetInitVarDecl(BO->getLHS()) == Var)
2758 return SetUB(BO->getRHS(),
2759 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2760 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2761 BO->getSourceRange(), BO->getOperatorLoc());
2762 if (GetInitVarDecl(BO->getRHS()) == Var)
2763 return SetUB(BO->getLHS(),
2764 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2765 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2766 BO->getSourceRange(), BO->getOperatorLoc());
2767 }
2768 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2769 if (CE->getNumArgs() == 2) {
2770 auto Op = CE->getOperator();
2771 switch (Op) {
2772 case OO_Greater:
2773 case OO_GreaterEqual:
2774 case OO_Less:
2775 case OO_LessEqual:
2776 if (GetInitVarDecl(CE->getArg(0)) == Var)
2777 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2778 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2779 CE->getOperatorLoc());
2780 if (GetInitVarDecl(CE->getArg(1)) == Var)
2781 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2782 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2783 CE->getOperatorLoc());
2784 break;
2785 default:
2786 break;
2787 }
2788 }
2789 }
2790 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2791 << S->getSourceRange() << Var;
2792 return true;
2793}
2794
2795bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2796 // RHS of canonical loop form increment can be:
2797 // var + incr
2798 // incr + var
2799 // var - incr
2800 //
2801 RHS = RHS->IgnoreParenImpCasts();
2802 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2803 if (BO->isAdditiveOp()) {
2804 bool IsAdd = BO->getOpcode() == BO_Add;
2805 if (GetInitVarDecl(BO->getLHS()) == Var)
2806 return SetStep(BO->getRHS(), !IsAdd);
2807 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2808 return SetStep(BO->getLHS(), false);
2809 }
2810 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2811 bool IsAdd = CE->getOperator() == OO_Plus;
2812 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2813 if (GetInitVarDecl(CE->getArg(0)) == Var)
2814 return SetStep(CE->getArg(1), !IsAdd);
2815 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2816 return SetStep(CE->getArg(0), false);
2817 }
2818 }
2819 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2820 << RHS->getSourceRange() << Var;
2821 return true;
2822}
2823
2824bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2825 // Check incr-expr for canonical loop form and return true if it
2826 // does not conform.
2827 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2828 // ++var
2829 // var++
2830 // --var
2831 // var--
2832 // var += incr
2833 // var -= incr
2834 // var = var + incr
2835 // var = incr + var
2836 // var = var - incr
2837 //
2838 if (!S) {
2839 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2840 return true;
2841 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002842 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002843 S = S->IgnoreParens();
2844 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2845 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2846 return SetStep(
2847 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2848 (UO->isDecrementOp() ? -1 : 1)).get(),
2849 false);
2850 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2851 switch (BO->getOpcode()) {
2852 case BO_AddAssign:
2853 case BO_SubAssign:
2854 if (GetInitVarDecl(BO->getLHS()) == Var)
2855 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2856 break;
2857 case BO_Assign:
2858 if (GetInitVarDecl(BO->getLHS()) == Var)
2859 return CheckIncRHS(BO->getRHS());
2860 break;
2861 default:
2862 break;
2863 }
2864 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2865 switch (CE->getOperator()) {
2866 case OO_PlusPlus:
2867 case OO_MinusMinus:
2868 if (GetInitVarDecl(CE->getArg(0)) == Var)
2869 return SetStep(
2870 SemaRef.ActOnIntegerConstant(
2871 CE->getLocStart(),
2872 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2873 false);
2874 break;
2875 case OO_PlusEqual:
2876 case OO_MinusEqual:
2877 if (GetInitVarDecl(CE->getArg(0)) == Var)
2878 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2879 break;
2880 case OO_Equal:
2881 if (GetInitVarDecl(CE->getArg(0)) == Var)
2882 return CheckIncRHS(CE->getArg(1));
2883 break;
2884 default:
2885 break;
2886 }
2887 }
2888 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2889 << S->getSourceRange() << Var;
2890 return true;
2891}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002892
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002893namespace {
2894// Transform variables declared in GNU statement expressions to new ones to
2895// avoid crash on codegen.
2896class TransformToNewDefs : public TreeTransform<TransformToNewDefs> {
2897 typedef TreeTransform<TransformToNewDefs> BaseTransform;
2898
2899public:
2900 TransformToNewDefs(Sema &SemaRef) : BaseTransform(SemaRef) {}
2901
2902 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
2903 if (auto *VD = cast<VarDecl>(D))
2904 if (!isa<ParmVarDecl>(D) && !isa<VarTemplateSpecializationDecl>(D) &&
2905 !isa<ImplicitParamDecl>(D)) {
2906 auto *NewVD = VarDecl::Create(
2907 SemaRef.Context, VD->getDeclContext(), VD->getLocStart(),
2908 VD->getLocation(), VD->getIdentifier(), VD->getType(),
2909 VD->getTypeSourceInfo(), VD->getStorageClass());
2910 NewVD->setTSCSpec(VD->getTSCSpec());
2911 NewVD->setInit(VD->getInit());
2912 NewVD->setInitStyle(VD->getInitStyle());
2913 NewVD->setExceptionVariable(VD->isExceptionVariable());
2914 NewVD->setNRVOVariable(VD->isNRVOVariable());
2915 NewVD->setCXXForRangeDecl(VD->isInExternCXXContext());
2916 NewVD->setConstexpr(VD->isConstexpr());
2917 NewVD->setInitCapture(VD->isInitCapture());
2918 NewVD->setPreviousDeclInSameBlockScope(
2919 VD->isPreviousDeclInSameBlockScope());
2920 VD->getDeclContext()->addHiddenDecl(NewVD);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002921 if (VD->hasAttrs())
2922 NewVD->setAttrs(VD->getAttrs());
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002923 transformedLocalDecl(VD, NewVD);
2924 return NewVD;
2925 }
2926 return BaseTransform::TransformDefinition(Loc, D);
2927 }
2928
2929 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
2930 if (auto *NewD = TransformDecl(E->getExprLoc(), E->getDecl()))
2931 if (E->getDecl() != NewD) {
2932 NewD->setReferenced();
2933 NewD->markUsed(SemaRef.Context);
2934 return DeclRefExpr::Create(
2935 SemaRef.Context, E->getQualifierLoc(), E->getTemplateKeywordLoc(),
2936 cast<ValueDecl>(NewD), E->refersToEnclosingVariableOrCapture(),
2937 E->getNameInfo(), E->getType(), E->getValueKind());
2938 }
2939 return BaseTransform::TransformDeclRefExpr(E);
2940 }
2941};
2942}
2943
Alexander Musmana5f070a2014-10-01 06:03:56 +00002944/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002945Expr *
2946OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2947 const bool LimitedType) const {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002948 TransformToNewDefs Transform(SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002949 ExprResult Diff;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002950 auto VarType = Var->getType().getNonReferenceType();
2951 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00002952 SemaRef.getLangOpts().CPlusPlus) {
2953 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002954 auto *UBExpr = TestIsLessOp ? UB : LB;
2955 auto *LBExpr = TestIsLessOp ? LB : UB;
2956 Expr *Upper = Transform.TransformExpr(UBExpr).get();
2957 Expr *Lower = Transform.TransformExpr(LBExpr).get();
2958 if (!Upper || !Lower)
2959 return nullptr;
2960 Upper = SemaRef.PerformImplicitConversion(Upper, UBExpr->getType(),
2961 Sema::AA_Converting,
2962 /*AllowExplicit=*/true)
2963 .get();
2964 Lower = SemaRef.PerformImplicitConversion(Lower, LBExpr->getType(),
2965 Sema::AA_Converting,
2966 /*AllowExplicit=*/true)
2967 .get();
2968 if (!Upper || !Lower)
2969 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002970
2971 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2972
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002973 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002974 // BuildBinOp already emitted error, this one is to point user to upper
2975 // and lower bound, and to tell what is passed to 'operator-'.
2976 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2977 << Upper->getSourceRange() << Lower->getSourceRange();
2978 return nullptr;
2979 }
2980 }
2981
2982 if (!Diff.isUsable())
2983 return nullptr;
2984
2985 // Upper - Lower [- 1]
2986 if (TestIsStrictOp)
2987 Diff = SemaRef.BuildBinOp(
2988 S, DefaultLoc, BO_Sub, Diff.get(),
2989 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2990 if (!Diff.isUsable())
2991 return nullptr;
2992
2993 // Upper - Lower [- 1] + Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002994 auto NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
2995 if (NewStep.isInvalid())
2996 return nullptr;
2997 NewStep = SemaRef.PerformImplicitConversion(
2998 NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
2999 /*AllowExplicit=*/true);
3000 if (NewStep.isInvalid())
3001 return nullptr;
3002 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003003 if (!Diff.isUsable())
3004 return nullptr;
3005
3006 // Parentheses (for dumping/debugging purposes only).
3007 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3008 if (!Diff.isUsable())
3009 return nullptr;
3010
3011 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003012 NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
3013 if (NewStep.isInvalid())
3014 return nullptr;
3015 NewStep = SemaRef.PerformImplicitConversion(
3016 NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
3017 /*AllowExplicit=*/true);
3018 if (NewStep.isInvalid())
3019 return nullptr;
3020 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003021 if (!Diff.isUsable())
3022 return nullptr;
3023
Alexander Musman174b3ca2014-10-06 11:16:29 +00003024 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003025 QualType Type = Diff.get()->getType();
3026 auto &C = SemaRef.Context;
3027 bool UseVarType = VarType->hasIntegerRepresentation() &&
3028 C.getTypeSize(Type) > C.getTypeSize(VarType);
3029 if (!Type->isIntegerType() || UseVarType) {
3030 unsigned NewSize =
3031 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3032 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3033 : Type->hasSignedIntegerRepresentation();
3034 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
3035 Diff = SemaRef.PerformImplicitConversion(
3036 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3037 if (!Diff.isUsable())
3038 return nullptr;
3039 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003040 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003041 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3042 if (NewSize != C.getTypeSize(Type)) {
3043 if (NewSize < C.getTypeSize(Type)) {
3044 assert(NewSize == 64 && "incorrect loop var size");
3045 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3046 << InitSrcRange << ConditionSrcRange;
3047 }
3048 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003049 NewSize, Type->hasSignedIntegerRepresentation() ||
3050 C.getTypeSize(Type) < NewSize);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003051 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3052 Sema::AA_Converting, true);
3053 if (!Diff.isUsable())
3054 return nullptr;
3055 }
3056 }
3057
Alexander Musmana5f070a2014-10-01 06:03:56 +00003058 return Diff.get();
3059}
3060
Alexey Bataev62dbb972015-04-22 11:59:37 +00003061Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
3062 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3063 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3064 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003065 TransformToNewDefs Transform(SemaRef);
3066
3067 auto NewLB = Transform.TransformExpr(LB);
3068 auto NewUB = Transform.TransformExpr(UB);
3069 if (NewLB.isInvalid() || NewUB.isInvalid())
3070 return Cond;
3071 NewLB = SemaRef.PerformImplicitConversion(NewLB.get(), LB->getType(),
3072 Sema::AA_Converting,
3073 /*AllowExplicit=*/true);
3074 NewUB = SemaRef.PerformImplicitConversion(NewUB.get(), UB->getType(),
3075 Sema::AA_Converting,
3076 /*AllowExplicit=*/true);
3077 if (NewLB.isInvalid() || NewUB.isInvalid())
3078 return Cond;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003079 auto CondExpr = SemaRef.BuildBinOp(
3080 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3081 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003082 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003083 if (CondExpr.isUsable()) {
3084 CondExpr = SemaRef.PerformImplicitConversion(
3085 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3086 /*AllowExplicit=*/true);
3087 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003088 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3089 // Otherwise use original loop conditon and evaluate it in runtime.
3090 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3091}
3092
Alexander Musmana5f070a2014-10-01 06:03:56 +00003093/// \brief Build reference expression to the counter be used for codegen.
3094Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
Alexey Bataeva8899172015-08-06 12:30:57 +00003095 return buildDeclRefExpr(SemaRef, Var, Var->getType().getNonReferenceType(),
3096 DefaultLoc);
3097}
3098
3099Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
3100 if (Var && !Var->isInvalidDecl()) {
3101 auto Type = Var->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003102 auto *PrivateVar =
3103 buildVarDecl(SemaRef, DefaultLoc, Type, Var->getName(),
3104 Var->hasAttrs() ? &Var->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003105 if (PrivateVar->isInvalidDecl())
3106 return nullptr;
3107 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3108 }
3109 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003110}
3111
3112/// \brief Build initization of the counter be used for codegen.
3113Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3114
3115/// \brief Build step of the counter be used for codegen.
3116Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3117
3118/// \brief Iteration space of a single for loop.
3119struct LoopIterationSpace {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003120 /// \brief Condition of the loop.
3121 Expr *PreCond;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003122 /// \brief This expression calculates the number of iterations in the loop.
3123 /// It is always possible to calculate it before starting the loop.
3124 Expr *NumIterations;
3125 /// \brief The loop counter variable.
3126 Expr *CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00003127 /// \brief Private loop counter variable.
3128 Expr *PrivateCounterVar;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003129 /// \brief This is initializer for the initial value of #CounterVar.
3130 Expr *CounterInit;
3131 /// \brief This is step for the #CounterVar used to generate its update:
3132 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
3133 Expr *CounterStep;
3134 /// \brief Should step be subtracted?
3135 bool Subtract;
3136 /// \brief Source range of the loop init.
3137 SourceRange InitSrcRange;
3138 /// \brief Source range of the loop condition.
3139 SourceRange CondSrcRange;
3140 /// \brief Source range of the loop increment.
3141 SourceRange IncSrcRange;
3142};
3143
Alexey Bataev23b69422014-06-18 07:08:49 +00003144} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003145
Alexey Bataev9c821032015-04-30 04:23:23 +00003146void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3147 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3148 assert(Init && "Expected loop in canonical form.");
3149 unsigned CollapseIteration = DSAStack->getCollapseNumber();
3150 if (CollapseIteration > 0 &&
3151 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3152 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
3153 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3154 DSAStack->addLoopControlVariable(ISC.GetLoopVar());
3155 }
3156 DSAStack->setCollapseNumber(CollapseIteration - 1);
3157 }
3158}
3159
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003160/// \brief Called on a for stmt to check and extract its iteration space
3161/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003162static bool CheckOpenMPIterationSpace(
3163 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3164 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003165 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003166 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
3167 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003168 // OpenMP [2.6, Canonical Loop Form]
3169 // for (init-expr; test-expr; incr-expr) structured-block
3170 auto For = dyn_cast_or_null<ForStmt>(S);
3171 if (!For) {
3172 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003173 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3174 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3175 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3176 if (NestedLoopCount > 1) {
3177 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3178 SemaRef.Diag(DSA.getConstructLoc(),
3179 diag::note_omp_collapse_ordered_expr)
3180 << 2 << CollapseLoopCountExpr->getSourceRange()
3181 << OrderedLoopCountExpr->getSourceRange();
3182 else if (CollapseLoopCountExpr)
3183 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3184 diag::note_omp_collapse_ordered_expr)
3185 << 0 << CollapseLoopCountExpr->getSourceRange();
3186 else
3187 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3188 diag::note_omp_collapse_ordered_expr)
3189 << 1 << OrderedLoopCountExpr->getSourceRange();
3190 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003191 return true;
3192 }
3193 assert(For->getBody());
3194
3195 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3196
3197 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003198 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003199 if (ISC.CheckInit(Init)) {
3200 return true;
3201 }
3202
3203 bool HasErrors = false;
3204
3205 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003206 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003207
3208 // OpenMP [2.6, Canonical Loop Form]
3209 // Var is one of the following:
3210 // A variable of signed or unsigned integer type.
3211 // For C++, a variable of a random access iterator type.
3212 // For C, a variable of a pointer type.
Alexey Bataeva8899172015-08-06 12:30:57 +00003213 auto VarType = Var->getType().getNonReferenceType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003214 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3215 !VarType->isPointerType() &&
3216 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3217 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3218 << SemaRef.getLangOpts().CPlusPlus;
3219 HasErrors = true;
3220 }
3221
Alexey Bataev4acb8592014-07-07 13:01:15 +00003222 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
3223 // Construct
3224 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3225 // parallel for construct is (are) private.
3226 // The loop iteration variable in the associated for-loop of a simd construct
3227 // with just one associated for-loop is linear with a constant-linear-step
3228 // that is the increment of the associated for-loop.
3229 // Exclude loop var from the list of variables with implicitly defined data
3230 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00003231 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003232
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003233 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
3234 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00003235 // The loop iteration variable in the associated for-loop of a simd construct
3236 // with just one associated for-loop may be listed in a linear clause with a
3237 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00003238 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3239 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003240 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003241 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
3242 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3243 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003244 auto PredeterminedCKind =
3245 isOpenMPSimdDirective(DKind)
3246 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3247 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003248 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00003249 DVar.CKind != OMPC_threadprivate && DVar.CKind != PredeterminedCKind) ||
Alexey Bataev49f6e782015-12-01 04:18:41 +00003250 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop) &&
3251 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3252 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate &&
3253 DVar.CKind != OMPC_threadprivate)) &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00003254 ((DVar.CKind != OMPC_private && DVar.CKind != OMPC_threadprivate) ||
3255 DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003256 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00003257 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3258 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataevf2453a02015-05-06 07:25:08 +00003259 if (DVar.RefExpr == nullptr)
3260 DVar.CKind = PredeterminedCKind;
3261 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003262 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003263 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003264 // Make the loop iteration variable private (for worksharing constructs),
3265 // linear (for simd directives with the only one associated loop) or
Alexey Bataev10e775f2015-07-30 11:36:16 +00003266 // lastprivate (for simd directives with several collapsed or ordered
3267 // loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00003268 if (DVar.CKind == OMPC_unknown)
3269 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
3270 /*FromParent=*/false);
Alexey Bataev9c821032015-04-30 04:23:23 +00003271 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003272 }
3273
Alexey Bataev7ff55242014-06-19 09:13:45 +00003274 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00003275
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003276 // Check test-expr.
3277 HasErrors |= ISC.CheckCond(For->getCond());
3278
3279 // Check incr-expr.
3280 HasErrors |= ISC.CheckInc(For->getInc());
3281
Alexander Musmana5f070a2014-10-01 06:03:56 +00003282 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003283 return HasErrors;
3284
Alexander Musmana5f070a2014-10-01 06:03:56 +00003285 // Build the loop's iteration space representation.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003286 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
Alexander Musman174b3ca2014-10-06 11:16:29 +00003287 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev49f6e782015-12-01 04:18:41 +00003288 DSA.getCurScope(),
3289 (isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop));
Alexander Musmana5f070a2014-10-01 06:03:56 +00003290 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
Alexey Bataeva8899172015-08-06 12:30:57 +00003291 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003292 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3293 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3294 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3295 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3296 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3297 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3298
Alexey Bataev62dbb972015-04-22 11:59:37 +00003299 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3300 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003301 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003302 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003303 ResultIterSpace.CounterInit == nullptr ||
3304 ResultIterSpace.CounterStep == nullptr);
3305
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003306 return HasErrors;
3307}
3308
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003309/// \brief Build 'VarRef = Start.
3310static ExprResult BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc,
3311 ExprResult VarRef, ExprResult Start) {
3312 TransformToNewDefs Transform(SemaRef);
3313 // Build 'VarRef = Start.
3314 auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
3315 if (NewStart.isInvalid())
3316 return ExprError();
3317 NewStart = SemaRef.PerformImplicitConversion(
3318 NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
3319 Sema::AA_Converting,
3320 /*AllowExplicit=*/true);
3321 if (NewStart.isInvalid())
3322 return ExprError();
3323 NewStart = SemaRef.PerformImplicitConversion(
3324 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3325 /*AllowExplicit=*/true);
3326 if (!NewStart.isUsable())
3327 return ExprError();
3328
3329 auto Init =
3330 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3331 return Init;
3332}
3333
Alexander Musmana5f070a2014-10-01 06:03:56 +00003334/// \brief Build 'VarRef = Start + Iter * Step'.
3335static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
3336 SourceLocation Loc, ExprResult VarRef,
3337 ExprResult Start, ExprResult Iter,
3338 ExprResult Step, bool Subtract) {
3339 // Add parentheses (for debugging purposes only).
3340 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3341 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3342 !Step.isUsable())
3343 return ExprError();
3344
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003345 TransformToNewDefs Transform(SemaRef);
3346 auto NewStep = Transform.TransformExpr(Step.get()->IgnoreImplicit());
3347 if (NewStep.isInvalid())
3348 return ExprError();
3349 NewStep = SemaRef.PerformImplicitConversion(
3350 NewStep.get(), Step.get()->IgnoreImplicit()->getType(),
3351 Sema::AA_Converting,
3352 /*AllowExplicit=*/true);
3353 if (NewStep.isInvalid())
3354 return ExprError();
3355 ExprResult Update =
3356 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003357 if (!Update.isUsable())
3358 return ExprError();
3359
3360 // Build 'VarRef = Start + Iter * Step'.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003361 auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
3362 if (NewStart.isInvalid())
3363 return ExprError();
3364 NewStart = SemaRef.PerformImplicitConversion(
3365 NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
3366 Sema::AA_Converting,
3367 /*AllowExplicit=*/true);
3368 if (NewStart.isInvalid())
3369 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003370 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003371 NewStart.get(), Update.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003372 if (!Update.isUsable())
3373 return ExprError();
3374
3375 Update = SemaRef.PerformImplicitConversion(
3376 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3377 if (!Update.isUsable())
3378 return ExprError();
3379
3380 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3381 return Update;
3382}
3383
3384/// \brief Convert integer expression \a E to make it have at least \a Bits
3385/// bits.
3386static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
3387 Sema &SemaRef) {
3388 if (E == nullptr)
3389 return ExprError();
3390 auto &C = SemaRef.Context;
3391 QualType OldType = E->getType();
3392 unsigned HasBits = C.getTypeSize(OldType);
3393 if (HasBits >= Bits)
3394 return ExprResult(E);
3395 // OK to convert to signed, because new type has more bits than old.
3396 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3397 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3398 true);
3399}
3400
3401/// \brief Check if the given expression \a E is a constant integer that fits
3402/// into \a Bits bits.
3403static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3404 if (E == nullptr)
3405 return false;
3406 llvm::APSInt Result;
3407 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3408 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3409 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003410}
3411
3412/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003413/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3414/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003415static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003416CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3417 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3418 DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003419 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003420 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003421 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003422 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003423 // Found 'collapse' clause - calculate collapse number.
3424 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003425 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003426 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003427 }
3428 if (OrderedLoopCountExpr) {
3429 // Found 'ordered' clause - calculate collapse number.
3430 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003431 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3432 if (Result.getLimitedValue() < NestedLoopCount) {
3433 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3434 diag::err_omp_wrong_ordered_loop_count)
3435 << OrderedLoopCountExpr->getSourceRange();
3436 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3437 diag::note_collapse_loop_count)
3438 << CollapseLoopCountExpr->getSourceRange();
3439 }
3440 NestedLoopCount = Result.getLimitedValue();
3441 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003442 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003443 // This is helper routine for loop directives (e.g., 'for', 'simd',
3444 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00003445 SmallVector<LoopIterationSpace, 4> IterSpaces;
3446 IterSpaces.resize(NestedLoopCount);
3447 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003448 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003449 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003450 NestedLoopCount, CollapseLoopCountExpr,
3451 OrderedLoopCountExpr, VarsWithImplicitDSA,
3452 IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003453 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003454 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003455 // OpenMP [2.8.1, simd construct, Restrictions]
3456 // All loops associated with the construct must be perfectly nested; that
3457 // is, there must be no intervening code nor any OpenMP directive between
3458 // any two loops.
3459 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003460 }
3461
Alexander Musmana5f070a2014-10-01 06:03:56 +00003462 Built.clear(/* size */ NestedLoopCount);
3463
3464 if (SemaRef.CurContext->isDependentContext())
3465 return NestedLoopCount;
3466
3467 // An example of what is generated for the following code:
3468 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003469 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003470 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003471 // for (k = 0; k < NK; ++k)
3472 // for (j = J0; j < NJ; j+=2) {
3473 // <loop body>
3474 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003475 //
3476 // We generate the code below.
3477 // Note: the loop body may be outlined in CodeGen.
3478 // Note: some counters may be C++ classes, operator- is used to find number of
3479 // iterations and operator+= to calculate counter value.
3480 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3481 // or i64 is currently supported).
3482 //
3483 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3484 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3485 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3486 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3487 // // similar updates for vars in clauses (e.g. 'linear')
3488 // <loop body (using local i and j)>
3489 // }
3490 // i = NI; // assign final values of counters
3491 // j = NJ;
3492 //
3493
3494 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3495 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003496 // Precondition tests if there is at least one iteration (all conditions are
3497 // true).
3498 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003499 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003500 ExprResult LastIteration32 = WidenIterationCount(
3501 32 /* Bits */, SemaRef.PerformImplicitConversion(
3502 N0->IgnoreImpCasts(), N0->getType(),
3503 Sema::AA_Converting, /*AllowExplicit=*/true)
3504 .get(),
3505 SemaRef);
3506 ExprResult LastIteration64 = WidenIterationCount(
3507 64 /* Bits */, SemaRef.PerformImplicitConversion(
3508 N0->IgnoreImpCasts(), N0->getType(),
3509 Sema::AA_Converting, /*AllowExplicit=*/true)
3510 .get(),
3511 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003512
3513 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3514 return NestedLoopCount;
3515
3516 auto &C = SemaRef.Context;
3517 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3518
3519 Scope *CurScope = DSA.getCurScope();
3520 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003521 if (PreCond.isUsable()) {
3522 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
3523 PreCond.get(), IterSpaces[Cnt].PreCond);
3524 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003525 auto N = IterSpaces[Cnt].NumIterations;
3526 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3527 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003528 LastIteration32 = SemaRef.BuildBinOp(
3529 CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
3530 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3531 Sema::AA_Converting,
3532 /*AllowExplicit=*/true)
3533 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003534 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003535 LastIteration64 = SemaRef.BuildBinOp(
3536 CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
3537 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3538 Sema::AA_Converting,
3539 /*AllowExplicit=*/true)
3540 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003541 }
3542
3543 // Choose either the 32-bit or 64-bit version.
3544 ExprResult LastIteration = LastIteration64;
3545 if (LastIteration32.isUsable() &&
3546 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3547 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3548 FitsInto(
3549 32 /* Bits */,
3550 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3551 LastIteration64.get(), SemaRef)))
3552 LastIteration = LastIteration32;
3553
3554 if (!LastIteration.isUsable())
3555 return 0;
3556
3557 // Save the number of iterations.
3558 ExprResult NumIterations = LastIteration;
3559 {
3560 LastIteration = SemaRef.BuildBinOp(
3561 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
3562 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3563 if (!LastIteration.isUsable())
3564 return 0;
3565 }
3566
3567 // Calculate the last iteration number beforehand instead of doing this on
3568 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3569 llvm::APSInt Result;
3570 bool IsConstant =
3571 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3572 ExprResult CalcLastIteration;
3573 if (!IsConstant) {
3574 SourceLocation SaveLoc;
3575 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00003576 buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003577 ".omp.last.iteration");
Alexey Bataev39f915b82015-05-08 10:41:21 +00003578 ExprResult SaveRef = buildDeclRefExpr(
3579 SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003580 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
3581 SaveRef.get(), LastIteration.get());
3582 LastIteration = SaveRef;
3583
3584 // Prepare SaveRef + 1.
3585 NumIterations = SemaRef.BuildBinOp(
3586 CurScope, SaveLoc, BO_Add, SaveRef.get(),
3587 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3588 if (!NumIterations.isUsable())
3589 return 0;
3590 }
3591
3592 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3593
Alexander Musmanc6388682014-12-15 07:07:06 +00003594 QualType VType = LastIteration.get()->getType();
3595 // Build variables passed into runtime, nesessary for worksharing directives.
3596 ExprResult LB, UB, IL, ST, EUB;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003597 if ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003598 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003599 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3600 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003601 SemaRef.AddInitializerToDecl(
3602 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3603 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3604
3605 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003606 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3607 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003608 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3609 /*DirectInit*/ false,
3610 /*TypeMayContainAuto*/ false);
3611
3612 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3613 // This will be used to implement clause 'lastprivate'.
3614 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00003615 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3616 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003617 SemaRef.AddInitializerToDecl(
3618 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3619 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3620
3621 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev39f915b82015-05-08 10:41:21 +00003622 VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
3623 ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003624 SemaRef.AddInitializerToDecl(
3625 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3626 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3627
3628 // Build expression: UB = min(UB, LastIteration)
3629 // It is nesessary for CodeGen of directives with static scheduling.
3630 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3631 UB.get(), LastIteration.get());
3632 ExprResult CondOp = SemaRef.ActOnConditionalOp(
3633 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
3634 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
3635 CondOp.get());
3636 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
3637 }
3638
3639 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003640 ExprResult IV;
3641 ExprResult Init;
3642 {
Alexey Bataev39f915b82015-05-08 10:41:21 +00003643 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
3644 IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003645 Expr *RHS = (isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop)
Alexander Musmanc6388682014-12-15 07:07:06 +00003646 ? LB.get()
3647 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
3648 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
3649 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003650 }
3651
Alexander Musmanc6388682014-12-15 07:07:06 +00003652 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003653 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00003654 ExprResult Cond =
Alexey Bataev49f6e782015-12-01 04:18:41 +00003655 (isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop)
Alexander Musmanc6388682014-12-15 07:07:06 +00003656 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
3657 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
3658 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003659
3660 // Loop increment (IV = IV + 1)
3661 SourceLocation IncLoc;
3662 ExprResult Inc =
3663 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
3664 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
3665 if (!Inc.isUsable())
3666 return 0;
3667 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00003668 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
3669 if (!Inc.isUsable())
3670 return 0;
3671
3672 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
3673 // Used for directives with static scheduling.
3674 ExprResult NextLB, NextUB;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003675 if (isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003676 // LB + ST
3677 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
3678 if (!NextLB.isUsable())
3679 return 0;
3680 // LB = LB + ST
3681 NextLB =
3682 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
3683 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
3684 if (!NextLB.isUsable())
3685 return 0;
3686 // UB + ST
3687 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
3688 if (!NextUB.isUsable())
3689 return 0;
3690 // UB = UB + ST
3691 NextUB =
3692 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
3693 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
3694 if (!NextUB.isUsable())
3695 return 0;
3696 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003697
3698 // Build updates and final values of the loop counters.
3699 bool HasErrors = false;
3700 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003701 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003702 Built.Updates.resize(NestedLoopCount);
3703 Built.Finals.resize(NestedLoopCount);
3704 {
3705 ExprResult Div;
3706 // Go from inner nested loop to outer.
3707 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
3708 LoopIterationSpace &IS = IterSpaces[Cnt];
3709 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
3710 // Build: Iter = (IV / Div) % IS.NumIters
3711 // where Div is product of previous iterations' IS.NumIters.
3712 ExprResult Iter;
3713 if (Div.isUsable()) {
3714 Iter =
3715 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
3716 } else {
3717 Iter = IV;
3718 assert((Cnt == (int)NestedLoopCount - 1) &&
3719 "unusable div expected on first iteration only");
3720 }
3721
3722 if (Cnt != 0 && Iter.isUsable())
3723 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
3724 IS.NumIterations);
3725 if (!Iter.isUsable()) {
3726 HasErrors = true;
3727 break;
3728 }
3729
Alexey Bataev39f915b82015-05-08 10:41:21 +00003730 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
3731 auto *CounterVar = buildDeclRefExpr(
3732 SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
3733 IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
3734 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003735 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
3736 IS.CounterInit);
3737 if (!Init.isUsable()) {
3738 HasErrors = true;
3739 break;
3740 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003741 ExprResult Update =
Alexey Bataev39f915b82015-05-08 10:41:21 +00003742 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003743 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
3744 if (!Update.isUsable()) {
3745 HasErrors = true;
3746 break;
3747 }
3748
3749 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
3750 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00003751 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003752 IS.NumIterations, IS.CounterStep, IS.Subtract);
3753 if (!Final.isUsable()) {
3754 HasErrors = true;
3755 break;
3756 }
3757
3758 // Build Div for the next iteration: Div <- Div * IS.NumIters
3759 if (Cnt != 0) {
3760 if (Div.isUnset())
3761 Div = IS.NumIterations;
3762 else
3763 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
3764 IS.NumIterations);
3765
3766 // Add parentheses (for debugging purposes only).
3767 if (Div.isUsable())
3768 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
3769 if (!Div.isUsable()) {
3770 HasErrors = true;
3771 break;
3772 }
3773 }
3774 if (!Update.isUsable() || !Final.isUsable()) {
3775 HasErrors = true;
3776 break;
3777 }
3778 // Save results
3779 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00003780 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003781 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003782 Built.Updates[Cnt] = Update.get();
3783 Built.Finals[Cnt] = Final.get();
3784 }
3785 }
3786
3787 if (HasErrors)
3788 return 0;
3789
3790 // Save results
3791 Built.IterationVarRef = IV.get();
3792 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00003793 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003794 Built.CalcLastIteration =
3795 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003796 Built.PreCond = PreCond.get();
3797 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003798 Built.Init = Init.get();
3799 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00003800 Built.LB = LB.get();
3801 Built.UB = UB.get();
3802 Built.IL = IL.get();
3803 Built.ST = ST.get();
3804 Built.EUB = EUB.get();
3805 Built.NLB = NextLB.get();
3806 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003807
Alexey Bataevabfc0692014-06-25 06:52:00 +00003808 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003809}
3810
Alexey Bataev10e775f2015-07-30 11:36:16 +00003811static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003812 auto CollapseClauses =
3813 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
3814 if (CollapseClauses.begin() != CollapseClauses.end())
3815 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003816 return nullptr;
3817}
3818
Alexey Bataev10e775f2015-07-30 11:36:16 +00003819static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003820 auto OrderedClauses =
3821 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
3822 if (OrderedClauses.begin() != OrderedClauses.end())
3823 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003824 return nullptr;
3825}
3826
Alexey Bataev66b15b52015-08-21 11:14:16 +00003827static bool checkSimdlenSafelenValues(Sema &S, const Expr *Simdlen,
3828 const Expr *Safelen) {
3829 llvm::APSInt SimdlenRes, SafelenRes;
3830 if (Simdlen->isValueDependent() || Simdlen->isTypeDependent() ||
3831 Simdlen->isInstantiationDependent() ||
3832 Simdlen->containsUnexpandedParameterPack())
3833 return false;
3834 if (Safelen->isValueDependent() || Safelen->isTypeDependent() ||
3835 Safelen->isInstantiationDependent() ||
3836 Safelen->containsUnexpandedParameterPack())
3837 return false;
3838 Simdlen->EvaluateAsInt(SimdlenRes, S.Context);
3839 Safelen->EvaluateAsInt(SafelenRes, S.Context);
3840 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
3841 // If both simdlen and safelen clauses are specified, the value of the simdlen
3842 // parameter must be less than or equal to the value of the safelen parameter.
3843 if (SimdlenRes > SafelenRes) {
3844 S.Diag(Simdlen->getExprLoc(), diag::err_omp_wrong_simdlen_safelen_values)
3845 << Simdlen->getSourceRange() << Safelen->getSourceRange();
3846 return true;
3847 }
3848 return false;
3849}
3850
Alexey Bataev4acb8592014-07-07 13:01:15 +00003851StmtResult Sema::ActOnOpenMPSimdDirective(
3852 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3853 SourceLocation EndLoc,
3854 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003855 if (!AStmt)
3856 return StmtError();
3857
3858 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00003859 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003860 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
3861 // define the nested loops number.
3862 unsigned NestedLoopCount = CheckOpenMPLoop(
3863 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
3864 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003865 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003866 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003867
Alexander Musmana5f070a2014-10-01 06:03:56 +00003868 assert((CurContext->isDependentContext() || B.builtAll()) &&
3869 "omp simd loop exprs were not built");
3870
Alexander Musman3276a272015-03-21 10:12:56 +00003871 if (!CurContext->isDependentContext()) {
3872 // Finalize the clauses that need pre-built expressions for CodeGen.
3873 for (auto C : Clauses) {
3874 if (auto LC = dyn_cast<OMPLinearClause>(C))
3875 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3876 B.NumIterations, *this, CurScope))
3877 return StmtError();
3878 }
3879 }
3880
Alexey Bataev66b15b52015-08-21 11:14:16 +00003881 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
3882 // If both simdlen and safelen clauses are specified, the value of the simdlen
3883 // parameter must be less than or equal to the value of the safelen parameter.
3884 OMPSafelenClause *Safelen = nullptr;
3885 OMPSimdlenClause *Simdlen = nullptr;
3886 for (auto *Clause : Clauses) {
3887 if (Clause->getClauseKind() == OMPC_safelen)
3888 Safelen = cast<OMPSafelenClause>(Clause);
3889 else if (Clause->getClauseKind() == OMPC_simdlen)
3890 Simdlen = cast<OMPSimdlenClause>(Clause);
3891 if (Safelen && Simdlen)
3892 break;
3893 }
3894 if (Simdlen && Safelen &&
3895 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
3896 Safelen->getSafelen()))
3897 return StmtError();
3898
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003899 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003900 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3901 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003902}
3903
Alexey Bataev4acb8592014-07-07 13:01:15 +00003904StmtResult Sema::ActOnOpenMPForDirective(
3905 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3906 SourceLocation EndLoc,
3907 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003908 if (!AStmt)
3909 return StmtError();
3910
3911 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00003912 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003913 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
3914 // define the nested loops number.
3915 unsigned NestedLoopCount = CheckOpenMPLoop(
3916 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
3917 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003918 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00003919 return StmtError();
3920
Alexander Musmana5f070a2014-10-01 06:03:56 +00003921 assert((CurContext->isDependentContext() || B.builtAll()) &&
3922 "omp for loop exprs were not built");
3923
Alexey Bataev54acd402015-08-04 11:18:19 +00003924 if (!CurContext->isDependentContext()) {
3925 // Finalize the clauses that need pre-built expressions for CodeGen.
3926 for (auto C : Clauses) {
3927 if (auto LC = dyn_cast<OMPLinearClause>(C))
3928 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3929 B.NumIterations, *this, CurScope))
3930 return StmtError();
3931 }
3932 }
3933
Alexey Bataevf29276e2014-06-18 04:14:57 +00003934 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003935 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003936 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00003937}
3938
Alexander Musmanf82886e2014-09-18 05:12:34 +00003939StmtResult Sema::ActOnOpenMPForSimdDirective(
3940 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3941 SourceLocation EndLoc,
3942 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003943 if (!AStmt)
3944 return StmtError();
3945
3946 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00003947 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003948 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
3949 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00003950 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00003951 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
3952 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
3953 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003954 if (NestedLoopCount == 0)
3955 return StmtError();
3956
Alexander Musmanc6388682014-12-15 07:07:06 +00003957 assert((CurContext->isDependentContext() || B.builtAll()) &&
3958 "omp for simd loop exprs were not built");
3959
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00003960 if (!CurContext->isDependentContext()) {
3961 // Finalize the clauses that need pre-built expressions for CodeGen.
3962 for (auto C : Clauses) {
3963 if (auto LC = dyn_cast<OMPLinearClause>(C))
3964 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3965 B.NumIterations, *this, CurScope))
3966 return StmtError();
3967 }
3968 }
3969
Alexey Bataev66b15b52015-08-21 11:14:16 +00003970 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
3971 // If both simdlen and safelen clauses are specified, the value of the simdlen
3972 // parameter must be less than or equal to the value of the safelen parameter.
3973 OMPSafelenClause *Safelen = nullptr;
3974 OMPSimdlenClause *Simdlen = nullptr;
3975 for (auto *Clause : Clauses) {
3976 if (Clause->getClauseKind() == OMPC_safelen)
3977 Safelen = cast<OMPSafelenClause>(Clause);
3978 else if (Clause->getClauseKind() == OMPC_simdlen)
3979 Simdlen = cast<OMPSimdlenClause>(Clause);
3980 if (Safelen && Simdlen)
3981 break;
3982 }
3983 if (Simdlen && Safelen &&
3984 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
3985 Safelen->getSafelen()))
3986 return StmtError();
3987
Alexander Musmanf82886e2014-09-18 05:12:34 +00003988 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003989 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3990 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003991}
3992
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003993StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3994 Stmt *AStmt,
3995 SourceLocation StartLoc,
3996 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003997 if (!AStmt)
3998 return StmtError();
3999
4000 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004001 auto BaseStmt = AStmt;
4002 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4003 BaseStmt = CS->getCapturedStmt();
4004 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4005 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004006 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004007 return StmtError();
4008 // All associated statements must be '#pragma omp section' except for
4009 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004010 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004011 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4012 if (SectionStmt)
4013 Diag(SectionStmt->getLocStart(),
4014 diag::err_omp_sections_substmt_not_section);
4015 return StmtError();
4016 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004017 cast<OMPSectionDirective>(SectionStmt)
4018 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004019 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004020 } else {
4021 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4022 return StmtError();
4023 }
4024
4025 getCurFunction()->setHasBranchProtectedScope();
4026
Alexey Bataev25e5b442015-09-15 12:52:43 +00004027 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4028 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004029}
4030
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004031StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4032 SourceLocation StartLoc,
4033 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004034 if (!AStmt)
4035 return StmtError();
4036
4037 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004038
4039 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004040 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004041
Alexey Bataev25e5b442015-09-15 12:52:43 +00004042 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4043 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004044}
4045
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004046StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4047 Stmt *AStmt,
4048 SourceLocation StartLoc,
4049 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004050 if (!AStmt)
4051 return StmtError();
4052
4053 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004054
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004055 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004056
Alexey Bataev3255bf32015-01-19 05:20:46 +00004057 // OpenMP [2.7.3, single Construct, Restrictions]
4058 // The copyprivate clause must not be used with the nowait clause.
4059 OMPClause *Nowait = nullptr;
4060 OMPClause *Copyprivate = nullptr;
4061 for (auto *Clause : Clauses) {
4062 if (Clause->getClauseKind() == OMPC_nowait)
4063 Nowait = Clause;
4064 else if (Clause->getClauseKind() == OMPC_copyprivate)
4065 Copyprivate = Clause;
4066 if (Copyprivate && Nowait) {
4067 Diag(Copyprivate->getLocStart(),
4068 diag::err_omp_single_copyprivate_with_nowait);
4069 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4070 return StmtError();
4071 }
4072 }
4073
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004074 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4075}
4076
Alexander Musman80c22892014-07-17 08:54:58 +00004077StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4078 SourceLocation StartLoc,
4079 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004080 if (!AStmt)
4081 return StmtError();
4082
4083 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004084
4085 getCurFunction()->setHasBranchProtectedScope();
4086
4087 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4088}
4089
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004090StmtResult
4091Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
4092 Stmt *AStmt, SourceLocation StartLoc,
4093 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004094 if (!AStmt)
4095 return StmtError();
4096
4097 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004098
4099 getCurFunction()->setHasBranchProtectedScope();
4100
4101 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4102 AStmt);
4103}
4104
Alexey Bataev4acb8592014-07-07 13:01:15 +00004105StmtResult Sema::ActOnOpenMPParallelForDirective(
4106 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4107 SourceLocation EndLoc,
4108 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004109 if (!AStmt)
4110 return StmtError();
4111
Alexey Bataev4acb8592014-07-07 13:01:15 +00004112 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4113 // 1.2.2 OpenMP Language Terminology
4114 // Structured block - An executable statement with a single entry at the
4115 // top and a single exit at the bottom.
4116 // The point of exit cannot be a branch out of the structured block.
4117 // longjmp() and throw() must not violate the entry/exit criteria.
4118 CS->getCapturedDecl()->setNothrow();
4119
Alexander Musmanc6388682014-12-15 07:07:06 +00004120 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004121 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4122 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004123 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004124 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4125 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4126 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004127 if (NestedLoopCount == 0)
4128 return StmtError();
4129
Alexander Musmana5f070a2014-10-01 06:03:56 +00004130 assert((CurContext->isDependentContext() || B.builtAll()) &&
4131 "omp parallel for loop exprs were not built");
4132
Alexey Bataev54acd402015-08-04 11:18:19 +00004133 if (!CurContext->isDependentContext()) {
4134 // Finalize the clauses that need pre-built expressions for CodeGen.
4135 for (auto C : Clauses) {
4136 if (auto LC = dyn_cast<OMPLinearClause>(C))
4137 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4138 B.NumIterations, *this, CurScope))
4139 return StmtError();
4140 }
4141 }
4142
Alexey Bataev4acb8592014-07-07 13:01:15 +00004143 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004144 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004145 NestedLoopCount, Clauses, AStmt, B,
4146 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004147}
4148
Alexander Musmane4e893b2014-09-23 09:33:00 +00004149StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4150 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4151 SourceLocation EndLoc,
4152 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004153 if (!AStmt)
4154 return StmtError();
4155
Alexander Musmane4e893b2014-09-23 09:33:00 +00004156 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4157 // 1.2.2 OpenMP Language Terminology
4158 // Structured block - An executable statement with a single entry at the
4159 // top and a single exit at the bottom.
4160 // The point of exit cannot be a branch out of the structured block.
4161 // longjmp() and throw() must not violate the entry/exit criteria.
4162 CS->getCapturedDecl()->setNothrow();
4163
Alexander Musmanc6388682014-12-15 07:07:06 +00004164 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004165 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4166 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004167 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004168 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4169 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4170 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004171 if (NestedLoopCount == 0)
4172 return StmtError();
4173
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004174 if (!CurContext->isDependentContext()) {
4175 // Finalize the clauses that need pre-built expressions for CodeGen.
4176 for (auto C : Clauses) {
4177 if (auto LC = dyn_cast<OMPLinearClause>(C))
4178 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4179 B.NumIterations, *this, CurScope))
4180 return StmtError();
4181 }
4182 }
4183
Alexey Bataev66b15b52015-08-21 11:14:16 +00004184 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4185 // If both simdlen and safelen clauses are specified, the value of the simdlen
4186 // parameter must be less than or equal to the value of the safelen parameter.
4187 OMPSafelenClause *Safelen = nullptr;
4188 OMPSimdlenClause *Simdlen = nullptr;
4189 for (auto *Clause : Clauses) {
4190 if (Clause->getClauseKind() == OMPC_safelen)
4191 Safelen = cast<OMPSafelenClause>(Clause);
4192 else if (Clause->getClauseKind() == OMPC_simdlen)
4193 Simdlen = cast<OMPSimdlenClause>(Clause);
4194 if (Safelen && Simdlen)
4195 break;
4196 }
4197 if (Simdlen && Safelen &&
4198 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
4199 Safelen->getSafelen()))
4200 return StmtError();
4201
Alexander Musmane4e893b2014-09-23 09:33:00 +00004202 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004203 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004204 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004205}
4206
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004207StmtResult
4208Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4209 Stmt *AStmt, SourceLocation StartLoc,
4210 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004211 if (!AStmt)
4212 return StmtError();
4213
4214 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004215 auto BaseStmt = AStmt;
4216 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4217 BaseStmt = CS->getCapturedStmt();
4218 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4219 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004220 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004221 return StmtError();
4222 // All associated statements must be '#pragma omp section' except for
4223 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004224 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004225 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4226 if (SectionStmt)
4227 Diag(SectionStmt->getLocStart(),
4228 diag::err_omp_parallel_sections_substmt_not_section);
4229 return StmtError();
4230 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004231 cast<OMPSectionDirective>(SectionStmt)
4232 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004233 }
4234 } else {
4235 Diag(AStmt->getLocStart(),
4236 diag::err_omp_parallel_sections_not_compound_stmt);
4237 return StmtError();
4238 }
4239
4240 getCurFunction()->setHasBranchProtectedScope();
4241
Alexey Bataev25e5b442015-09-15 12:52:43 +00004242 return OMPParallelSectionsDirective::Create(
4243 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004244}
4245
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004246StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4247 Stmt *AStmt, SourceLocation StartLoc,
4248 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004249 if (!AStmt)
4250 return StmtError();
4251
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004252 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4253 // 1.2.2 OpenMP Language Terminology
4254 // Structured block - An executable statement with a single entry at the
4255 // top and a single exit at the bottom.
4256 // The point of exit cannot be a branch out of the structured block.
4257 // longjmp() and throw() must not violate the entry/exit criteria.
4258 CS->getCapturedDecl()->setNothrow();
4259
4260 getCurFunction()->setHasBranchProtectedScope();
4261
Alexey Bataev25e5b442015-09-15 12:52:43 +00004262 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4263 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004264}
4265
Alexey Bataev68446b72014-07-18 07:47:19 +00004266StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4267 SourceLocation EndLoc) {
4268 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4269}
4270
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004271StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4272 SourceLocation EndLoc) {
4273 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4274}
4275
Alexey Bataev2df347a2014-07-18 10:17:07 +00004276StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4277 SourceLocation EndLoc) {
4278 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4279}
4280
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004281StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4282 SourceLocation StartLoc,
4283 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004284 if (!AStmt)
4285 return StmtError();
4286
4287 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004288
4289 getCurFunction()->setHasBranchProtectedScope();
4290
4291 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4292}
4293
Alexey Bataev6125da92014-07-21 11:26:11 +00004294StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4295 SourceLocation StartLoc,
4296 SourceLocation EndLoc) {
4297 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4298 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4299}
4300
Alexey Bataev346265e2015-09-25 10:37:12 +00004301StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4302 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004303 SourceLocation StartLoc,
4304 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004305 if (!AStmt)
4306 return StmtError();
4307
4308 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004309
4310 getCurFunction()->setHasBranchProtectedScope();
4311
Alexey Bataev346265e2015-09-25 10:37:12 +00004312 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004313 OMPSIMDClause *SC = nullptr;
Alexey Bataev346265e2015-09-25 10:37:12 +00004314 for (auto *C: Clauses) {
4315 if (C->getClauseKind() == OMPC_threads)
4316 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004317 else if (C->getClauseKind() == OMPC_simd)
4318 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004319 }
4320
4321 // TODO: this must happen only if 'threads' clause specified or if no clauses
4322 // is specified.
4323 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4324 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4325 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) << (TC != nullptr);
4326 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4327 return StmtError();
4328 }
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004329 if (!SC && isOpenMPSimdDirective(DSAStack->getParentDirective())) {
4330 // OpenMP [2.8.1,simd Construct, Restrictions]
4331 // An ordered construct with the simd clause is the only OpenMP construct
4332 // that can appear in the simd region.
4333 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
4334 return StmtError();
4335 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004336
4337 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004338}
4339
Alexey Bataev1d160b12015-03-13 12:27:31 +00004340namespace {
4341/// \brief Helper class for checking expression in 'omp atomic [update]'
4342/// construct.
4343class OpenMPAtomicUpdateChecker {
4344 /// \brief Error results for atomic update expressions.
4345 enum ExprAnalysisErrorCode {
4346 /// \brief A statement is not an expression statement.
4347 NotAnExpression,
4348 /// \brief Expression is not builtin binary or unary operation.
4349 NotABinaryOrUnaryExpression,
4350 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4351 NotAnUnaryIncDecExpression,
4352 /// \brief An expression is not of scalar type.
4353 NotAScalarType,
4354 /// \brief A binary operation is not an assignment operation.
4355 NotAnAssignmentOp,
4356 /// \brief RHS part of the binary operation is not a binary expression.
4357 NotABinaryExpression,
4358 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4359 /// expression.
4360 NotABinaryOperator,
4361 /// \brief RHS binary operation does not have reference to the updated LHS
4362 /// part.
4363 NotAnUpdateExpression,
4364 /// \brief No errors is found.
4365 NoError
4366 };
4367 /// \brief Reference to Sema.
4368 Sema &SemaRef;
4369 /// \brief A location for note diagnostics (when error is found).
4370 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004371 /// \brief 'x' lvalue part of the source atomic expression.
4372 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004373 /// \brief 'expr' rvalue part of the source atomic expression.
4374 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004375 /// \brief Helper expression of the form
4376 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4377 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4378 Expr *UpdateExpr;
4379 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4380 /// important for non-associative operations.
4381 bool IsXLHSInRHSPart;
4382 BinaryOperatorKind Op;
4383 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004384 /// \brief true if the source expression is a postfix unary operation, false
4385 /// if it is a prefix unary operation.
4386 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004387
4388public:
4389 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00004390 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00004391 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00004392 /// \brief Check specified statement that it is suitable for 'atomic update'
4393 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00004394 /// expression. If DiagId and NoteId == 0, then only check is performed
4395 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00004396 /// \param DiagId Diagnostic which should be emitted if error is found.
4397 /// \param NoteId Diagnostic note for the main error message.
4398 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00004399 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004400 /// \brief Return the 'x' lvalue part of the source atomic expression.
4401 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00004402 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4403 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00004404 /// \brief Return the update expression used in calculation of the updated
4405 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4406 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4407 Expr *getUpdateExpr() const { return UpdateExpr; }
4408 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4409 /// false otherwise.
4410 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4411
Alexey Bataevb78ca832015-04-01 03:33:17 +00004412 /// \brief true if the source expression is a postfix unary operation, false
4413 /// if it is a prefix unary operation.
4414 bool isPostfixUpdate() const { return IsPostfixUpdate; }
4415
Alexey Bataev1d160b12015-03-13 12:27:31 +00004416private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00004417 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4418 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004419};
4420} // namespace
4421
4422bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4423 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4424 ExprAnalysisErrorCode ErrorFound = NoError;
4425 SourceLocation ErrorLoc, NoteLoc;
4426 SourceRange ErrorRange, NoteRange;
4427 // Allowed constructs are:
4428 // x = x binop expr;
4429 // x = expr binop x;
4430 if (AtomicBinOp->getOpcode() == BO_Assign) {
4431 X = AtomicBinOp->getLHS();
4432 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4433 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4434 if (AtomicInnerBinOp->isMultiplicativeOp() ||
4435 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4436 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00004437 Op = AtomicInnerBinOp->getOpcode();
4438 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004439 auto *LHS = AtomicInnerBinOp->getLHS();
4440 auto *RHS = AtomicInnerBinOp->getRHS();
4441 llvm::FoldingSetNodeID XId, LHSId, RHSId;
4442 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4443 /*Canonical=*/true);
4444 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4445 /*Canonical=*/true);
4446 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4447 /*Canonical=*/true);
4448 if (XId == LHSId) {
4449 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004450 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004451 } else if (XId == RHSId) {
4452 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004453 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004454 } else {
4455 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4456 ErrorRange = AtomicInnerBinOp->getSourceRange();
4457 NoteLoc = X->getExprLoc();
4458 NoteRange = X->getSourceRange();
4459 ErrorFound = NotAnUpdateExpression;
4460 }
4461 } else {
4462 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4463 ErrorRange = AtomicInnerBinOp->getSourceRange();
4464 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4465 NoteRange = SourceRange(NoteLoc, NoteLoc);
4466 ErrorFound = NotABinaryOperator;
4467 }
4468 } else {
4469 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4470 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4471 ErrorFound = NotABinaryExpression;
4472 }
4473 } else {
4474 ErrorLoc = AtomicBinOp->getExprLoc();
4475 ErrorRange = AtomicBinOp->getSourceRange();
4476 NoteLoc = AtomicBinOp->getOperatorLoc();
4477 NoteRange = SourceRange(NoteLoc, NoteLoc);
4478 ErrorFound = NotAnAssignmentOp;
4479 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004480 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004481 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4482 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4483 return true;
4484 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00004485 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004486 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004487}
4488
4489bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
4490 unsigned NoteId) {
4491 ExprAnalysisErrorCode ErrorFound = NoError;
4492 SourceLocation ErrorLoc, NoteLoc;
4493 SourceRange ErrorRange, NoteRange;
4494 // Allowed constructs are:
4495 // x++;
4496 // x--;
4497 // ++x;
4498 // --x;
4499 // x binop= expr;
4500 // x = x binop expr;
4501 // x = expr binop x;
4502 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
4503 AtomicBody = AtomicBody->IgnoreParenImpCasts();
4504 if (AtomicBody->getType()->isScalarType() ||
4505 AtomicBody->isInstantiationDependent()) {
4506 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
4507 AtomicBody->IgnoreParenImpCasts())) {
4508 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00004509 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00004510 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00004511 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004512 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004513 X = AtomicCompAssignOp->getLHS();
4514 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004515 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
4516 AtomicBody->IgnoreParenImpCasts())) {
4517 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00004518 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
4519 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004520 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00004521 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
4522 // Check for Unary Operation
4523 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004524 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004525 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
4526 OpLoc = AtomicUnaryOp->getOperatorLoc();
4527 X = AtomicUnaryOp->getSubExpr();
4528 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
4529 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004530 } else {
4531 ErrorFound = NotAnUnaryIncDecExpression;
4532 ErrorLoc = AtomicUnaryOp->getExprLoc();
4533 ErrorRange = AtomicUnaryOp->getSourceRange();
4534 NoteLoc = AtomicUnaryOp->getOperatorLoc();
4535 NoteRange = SourceRange(NoteLoc, NoteLoc);
4536 }
Alexey Bataev5a195472015-09-04 12:55:50 +00004537 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004538 ErrorFound = NotABinaryOrUnaryExpression;
4539 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
4540 NoteRange = ErrorRange = AtomicBody->getSourceRange();
4541 }
4542 } else {
4543 ErrorFound = NotAScalarType;
4544 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
4545 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4546 }
4547 } else {
4548 ErrorFound = NotAnExpression;
4549 NoteLoc = ErrorLoc = S->getLocStart();
4550 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4551 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004552 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004553 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4554 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4555 return true;
4556 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00004557 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004558 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00004559 // Build an update expression of form 'OpaqueValueExpr(x) binop
4560 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
4561 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
4562 auto *OVEX = new (SemaRef.getASTContext())
4563 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
4564 auto *OVEExpr = new (SemaRef.getASTContext())
4565 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
4566 auto Update =
4567 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
4568 IsXLHSInRHSPart ? OVEExpr : OVEX);
4569 if (Update.isInvalid())
4570 return true;
4571 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
4572 Sema::AA_Casting);
4573 if (Update.isInvalid())
4574 return true;
4575 UpdateExpr = Update.get();
4576 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00004577 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004578}
4579
Alexey Bataev0162e452014-07-22 10:10:35 +00004580StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
4581 Stmt *AStmt,
4582 SourceLocation StartLoc,
4583 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004584 if (!AStmt)
4585 return StmtError();
4586
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004587 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00004588 // 1.2.2 OpenMP Language Terminology
4589 // Structured block - An executable statement with a single entry at the
4590 // top and a single exit at the bottom.
4591 // The point of exit cannot be a branch out of the structured block.
4592 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00004593 OpenMPClauseKind AtomicKind = OMPC_unknown;
4594 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004595 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00004596 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00004597 C->getClauseKind() == OMPC_update ||
4598 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00004599 if (AtomicKind != OMPC_unknown) {
4600 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
4601 << SourceRange(C->getLocStart(), C->getLocEnd());
4602 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
4603 << getOpenMPClauseName(AtomicKind);
4604 } else {
4605 AtomicKind = C->getClauseKind();
4606 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004607 }
4608 }
4609 }
Alexey Bataev62cec442014-11-18 10:14:22 +00004610
Alexey Bataev459dec02014-07-24 06:46:57 +00004611 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00004612 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
4613 Body = EWC->getSubExpr();
4614
Alexey Bataev62cec442014-11-18 10:14:22 +00004615 Expr *X = nullptr;
4616 Expr *V = nullptr;
4617 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004618 Expr *UE = nullptr;
4619 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004620 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00004621 // OpenMP [2.12.6, atomic Construct]
4622 // In the next expressions:
4623 // * x and v (as applicable) are both l-value expressions with scalar type.
4624 // * During the execution of an atomic region, multiple syntactic
4625 // occurrences of x must designate the same storage location.
4626 // * Neither of v and expr (as applicable) may access the storage location
4627 // designated by x.
4628 // * Neither of x and expr (as applicable) may access the storage location
4629 // designated by v.
4630 // * expr is an expression with scalar type.
4631 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
4632 // * binop, binop=, ++, and -- are not overloaded operators.
4633 // * The expression x binop expr must be numerically equivalent to x binop
4634 // (expr). This requirement is satisfied if the operators in expr have
4635 // precedence greater than binop, or by using parentheses around expr or
4636 // subexpressions of expr.
4637 // * The expression expr binop x must be numerically equivalent to (expr)
4638 // binop x. This requirement is satisfied if the operators in expr have
4639 // precedence equal to or greater than binop, or by using parentheses around
4640 // expr or subexpressions of expr.
4641 // * For forms that allow multiple occurrences of x, the number of times
4642 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00004643 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004644 enum {
4645 NotAnExpression,
4646 NotAnAssignmentOp,
4647 NotAScalarType,
4648 NotAnLValue,
4649 NoError
4650 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00004651 SourceLocation ErrorLoc, NoteLoc;
4652 SourceRange ErrorRange, NoteRange;
4653 // If clause is read:
4654 // v = x;
4655 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
4656 auto AtomicBinOp =
4657 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4658 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
4659 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
4660 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
4661 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
4662 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
4663 if (!X->isLValue() || !V->isLValue()) {
4664 auto NotLValueExpr = X->isLValue() ? V : X;
4665 ErrorFound = NotAnLValue;
4666 ErrorLoc = AtomicBinOp->getExprLoc();
4667 ErrorRange = AtomicBinOp->getSourceRange();
4668 NoteLoc = NotLValueExpr->getExprLoc();
4669 NoteRange = NotLValueExpr->getSourceRange();
4670 }
4671 } else if (!X->isInstantiationDependent() ||
4672 !V->isInstantiationDependent()) {
4673 auto NotScalarExpr =
4674 (X->isInstantiationDependent() || X->getType()->isScalarType())
4675 ? V
4676 : X;
4677 ErrorFound = NotAScalarType;
4678 ErrorLoc = AtomicBinOp->getExprLoc();
4679 ErrorRange = AtomicBinOp->getSourceRange();
4680 NoteLoc = NotScalarExpr->getExprLoc();
4681 NoteRange = NotScalarExpr->getSourceRange();
4682 }
Alexey Bataev5a195472015-09-04 12:55:50 +00004683 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00004684 ErrorFound = NotAnAssignmentOp;
4685 ErrorLoc = AtomicBody->getExprLoc();
4686 ErrorRange = AtomicBody->getSourceRange();
4687 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4688 : AtomicBody->getExprLoc();
4689 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4690 : AtomicBody->getSourceRange();
4691 }
4692 } else {
4693 ErrorFound = NotAnExpression;
4694 NoteLoc = ErrorLoc = Body->getLocStart();
4695 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00004696 }
Alexey Bataev62cec442014-11-18 10:14:22 +00004697 if (ErrorFound != NoError) {
4698 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
4699 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00004700 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
4701 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00004702 return StmtError();
4703 } else if (CurContext->isDependentContext())
4704 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00004705 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004706 enum {
4707 NotAnExpression,
4708 NotAnAssignmentOp,
4709 NotAScalarType,
4710 NotAnLValue,
4711 NoError
4712 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00004713 SourceLocation ErrorLoc, NoteLoc;
4714 SourceRange ErrorRange, NoteRange;
4715 // If clause is write:
4716 // x = expr;
4717 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
4718 auto AtomicBinOp =
4719 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4720 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00004721 X = AtomicBinOp->getLHS();
4722 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00004723 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
4724 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
4725 if (!X->isLValue()) {
4726 ErrorFound = NotAnLValue;
4727 ErrorLoc = AtomicBinOp->getExprLoc();
4728 ErrorRange = AtomicBinOp->getSourceRange();
4729 NoteLoc = X->getExprLoc();
4730 NoteRange = X->getSourceRange();
4731 }
4732 } else if (!X->isInstantiationDependent() ||
4733 !E->isInstantiationDependent()) {
4734 auto NotScalarExpr =
4735 (X->isInstantiationDependent() || X->getType()->isScalarType())
4736 ? E
4737 : X;
4738 ErrorFound = NotAScalarType;
4739 ErrorLoc = AtomicBinOp->getExprLoc();
4740 ErrorRange = AtomicBinOp->getSourceRange();
4741 NoteLoc = NotScalarExpr->getExprLoc();
4742 NoteRange = NotScalarExpr->getSourceRange();
4743 }
Alexey Bataev5a195472015-09-04 12:55:50 +00004744 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00004745 ErrorFound = NotAnAssignmentOp;
4746 ErrorLoc = AtomicBody->getExprLoc();
4747 ErrorRange = AtomicBody->getSourceRange();
4748 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4749 : AtomicBody->getExprLoc();
4750 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4751 : AtomicBody->getSourceRange();
4752 }
4753 } else {
4754 ErrorFound = NotAnExpression;
4755 NoteLoc = ErrorLoc = Body->getLocStart();
4756 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00004757 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00004758 if (ErrorFound != NoError) {
4759 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
4760 << ErrorRange;
4761 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
4762 << NoteRange;
4763 return StmtError();
4764 } else if (CurContext->isDependentContext())
4765 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004766 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004767 // If clause is update:
4768 // x++;
4769 // x--;
4770 // ++x;
4771 // --x;
4772 // x binop= expr;
4773 // x = x binop expr;
4774 // x = expr binop x;
4775 OpenMPAtomicUpdateChecker Checker(*this);
4776 if (Checker.checkStatement(
4777 Body, (AtomicKind == OMPC_update)
4778 ? diag::err_omp_atomic_update_not_expression_statement
4779 : diag::err_omp_atomic_not_expression_statement,
4780 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00004781 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004782 if (!CurContext->isDependentContext()) {
4783 E = Checker.getExpr();
4784 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004785 UE = Checker.getUpdateExpr();
4786 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00004787 }
Alexey Bataev459dec02014-07-24 06:46:57 +00004788 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004789 enum {
4790 NotAnAssignmentOp,
4791 NotACompoundStatement,
4792 NotTwoSubstatements,
4793 NotASpecificExpression,
4794 NoError
4795 } ErrorFound = NoError;
4796 SourceLocation ErrorLoc, NoteLoc;
4797 SourceRange ErrorRange, NoteRange;
4798 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
4799 // If clause is a capture:
4800 // v = x++;
4801 // v = x--;
4802 // v = ++x;
4803 // v = --x;
4804 // v = x binop= expr;
4805 // v = x = x binop expr;
4806 // v = x = expr binop x;
4807 auto *AtomicBinOp =
4808 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4809 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
4810 V = AtomicBinOp->getLHS();
4811 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
4812 OpenMPAtomicUpdateChecker Checker(*this);
4813 if (Checker.checkStatement(
4814 Body, diag::err_omp_atomic_capture_not_expression_statement,
4815 diag::note_omp_atomic_update))
4816 return StmtError();
4817 E = Checker.getExpr();
4818 X = Checker.getX();
4819 UE = Checker.getUpdateExpr();
4820 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4821 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00004822 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004823 ErrorLoc = AtomicBody->getExprLoc();
4824 ErrorRange = AtomicBody->getSourceRange();
4825 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4826 : AtomicBody->getExprLoc();
4827 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4828 : AtomicBody->getSourceRange();
4829 ErrorFound = NotAnAssignmentOp;
4830 }
4831 if (ErrorFound != NoError) {
4832 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
4833 << ErrorRange;
4834 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4835 return StmtError();
4836 } else if (CurContext->isDependentContext()) {
4837 UE = V = E = X = nullptr;
4838 }
4839 } else {
4840 // If clause is a capture:
4841 // { v = x; x = expr; }
4842 // { v = x; x++; }
4843 // { v = x; x--; }
4844 // { v = x; ++x; }
4845 // { v = x; --x; }
4846 // { v = x; x binop= expr; }
4847 // { v = x; x = x binop expr; }
4848 // { v = x; x = expr binop x; }
4849 // { x++; v = x; }
4850 // { x--; v = x; }
4851 // { ++x; v = x; }
4852 // { --x; v = x; }
4853 // { x binop= expr; v = x; }
4854 // { x = x binop expr; v = x; }
4855 // { x = expr binop x; v = x; }
4856 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
4857 // Check that this is { expr1; expr2; }
4858 if (CS->size() == 2) {
4859 auto *First = CS->body_front();
4860 auto *Second = CS->body_back();
4861 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
4862 First = EWC->getSubExpr()->IgnoreParenImpCasts();
4863 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
4864 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
4865 // Need to find what subexpression is 'v' and what is 'x'.
4866 OpenMPAtomicUpdateChecker Checker(*this);
4867 bool IsUpdateExprFound = !Checker.checkStatement(Second);
4868 BinaryOperator *BinOp = nullptr;
4869 if (IsUpdateExprFound) {
4870 BinOp = dyn_cast<BinaryOperator>(First);
4871 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4872 }
4873 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4874 // { v = x; x++; }
4875 // { v = x; x--; }
4876 // { v = x; ++x; }
4877 // { v = x; --x; }
4878 // { v = x; x binop= expr; }
4879 // { v = x; x = x binop expr; }
4880 // { v = x; x = expr binop x; }
4881 // Check that the first expression has form v = x.
4882 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4883 llvm::FoldingSetNodeID XId, PossibleXId;
4884 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4885 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4886 IsUpdateExprFound = XId == PossibleXId;
4887 if (IsUpdateExprFound) {
4888 V = BinOp->getLHS();
4889 X = Checker.getX();
4890 E = Checker.getExpr();
4891 UE = Checker.getUpdateExpr();
4892 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00004893 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004894 }
4895 }
4896 if (!IsUpdateExprFound) {
4897 IsUpdateExprFound = !Checker.checkStatement(First);
4898 BinOp = nullptr;
4899 if (IsUpdateExprFound) {
4900 BinOp = dyn_cast<BinaryOperator>(Second);
4901 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4902 }
4903 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4904 // { x++; v = x; }
4905 // { x--; v = x; }
4906 // { ++x; v = x; }
4907 // { --x; v = x; }
4908 // { x binop= expr; v = x; }
4909 // { x = x binop expr; v = x; }
4910 // { x = expr binop x; v = x; }
4911 // Check that the second expression has form v = x.
4912 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4913 llvm::FoldingSetNodeID XId, PossibleXId;
4914 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4915 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4916 IsUpdateExprFound = XId == PossibleXId;
4917 if (IsUpdateExprFound) {
4918 V = BinOp->getLHS();
4919 X = Checker.getX();
4920 E = Checker.getExpr();
4921 UE = Checker.getUpdateExpr();
4922 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00004923 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004924 }
4925 }
4926 }
4927 if (!IsUpdateExprFound) {
4928 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00004929 auto *FirstExpr = dyn_cast<Expr>(First);
4930 auto *SecondExpr = dyn_cast<Expr>(Second);
4931 if (!FirstExpr || !SecondExpr ||
4932 !(FirstExpr->isInstantiationDependent() ||
4933 SecondExpr->isInstantiationDependent())) {
4934 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
4935 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004936 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00004937 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
4938 : First->getLocStart();
4939 NoteRange = ErrorRange = FirstBinOp
4940 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00004941 : SourceRange(ErrorLoc, ErrorLoc);
4942 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00004943 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
4944 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
4945 ErrorFound = NotAnAssignmentOp;
4946 NoteLoc = ErrorLoc = SecondBinOp
4947 ? SecondBinOp->getOperatorLoc()
4948 : Second->getLocStart();
4949 NoteRange = ErrorRange =
4950 SecondBinOp ? SecondBinOp->getSourceRange()
4951 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00004952 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00004953 auto *PossibleXRHSInFirst =
4954 FirstBinOp->getRHS()->IgnoreParenImpCasts();
4955 auto *PossibleXLHSInSecond =
4956 SecondBinOp->getLHS()->IgnoreParenImpCasts();
4957 llvm::FoldingSetNodeID X1Id, X2Id;
4958 PossibleXRHSInFirst->Profile(X1Id, Context,
4959 /*Canonical=*/true);
4960 PossibleXLHSInSecond->Profile(X2Id, Context,
4961 /*Canonical=*/true);
4962 IsUpdateExprFound = X1Id == X2Id;
4963 if (IsUpdateExprFound) {
4964 V = FirstBinOp->getLHS();
4965 X = SecondBinOp->getLHS();
4966 E = SecondBinOp->getRHS();
4967 UE = nullptr;
4968 IsXLHSInRHSPart = false;
4969 IsPostfixUpdate = true;
4970 } else {
4971 ErrorFound = NotASpecificExpression;
4972 ErrorLoc = FirstBinOp->getExprLoc();
4973 ErrorRange = FirstBinOp->getSourceRange();
4974 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
4975 NoteRange = SecondBinOp->getRHS()->getSourceRange();
4976 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004977 }
4978 }
4979 }
4980 }
4981 } else {
4982 NoteLoc = ErrorLoc = Body->getLocStart();
4983 NoteRange = ErrorRange =
4984 SourceRange(Body->getLocStart(), Body->getLocStart());
4985 ErrorFound = NotTwoSubstatements;
4986 }
4987 } else {
4988 NoteLoc = ErrorLoc = Body->getLocStart();
4989 NoteRange = ErrorRange =
4990 SourceRange(Body->getLocStart(), Body->getLocStart());
4991 ErrorFound = NotACompoundStatement;
4992 }
4993 if (ErrorFound != NoError) {
4994 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
4995 << ErrorRange;
4996 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4997 return StmtError();
4998 } else if (CurContext->isDependentContext()) {
4999 UE = V = E = X = nullptr;
5000 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005001 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005002 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005003
5004 getCurFunction()->setHasBranchProtectedScope();
5005
Alexey Bataev62cec442014-11-18 10:14:22 +00005006 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005007 X, V, E, UE, IsXLHSInRHSPart,
5008 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005009}
5010
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005011StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5012 Stmt *AStmt,
5013 SourceLocation StartLoc,
5014 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005015 if (!AStmt)
5016 return StmtError();
5017
5018 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005019
Alexey Bataev13314bf2014-10-09 04:18:56 +00005020 // OpenMP [2.16, Nesting of Regions]
5021 // If specified, a teams construct must be contained within a target
5022 // construct. That target construct must contain no statements or directives
5023 // outside of the teams construct.
5024 if (DSAStack->hasInnerTeamsRegion()) {
5025 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5026 bool OMPTeamsFound = true;
5027 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5028 auto I = CS->body_begin();
5029 while (I != CS->body_end()) {
5030 auto OED = dyn_cast<OMPExecutableDirective>(*I);
5031 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5032 OMPTeamsFound = false;
5033 break;
5034 }
5035 ++I;
5036 }
5037 assert(I != CS->body_end() && "Not found statement");
5038 S = *I;
5039 }
5040 if (!OMPTeamsFound) {
5041 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5042 Diag(DSAStack->getInnerTeamsRegionLoc(),
5043 diag::note_omp_nested_teams_construct_here);
5044 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5045 << isa<OMPExecutableDirective>(S);
5046 return StmtError();
5047 }
5048 }
5049
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005050 getCurFunction()->setHasBranchProtectedScope();
5051
5052 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5053}
5054
Michael Wong65f367f2015-07-21 13:44:28 +00005055StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5056 Stmt *AStmt,
5057 SourceLocation StartLoc,
5058 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005059 if (!AStmt)
5060 return StmtError();
5061
5062 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5063
Michael Wong65f367f2015-07-21 13:44:28 +00005064 getCurFunction()->setHasBranchProtectedScope();
5065
5066 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5067 AStmt);
5068}
5069
Alexey Bataev13314bf2014-10-09 04:18:56 +00005070StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5071 Stmt *AStmt, SourceLocation StartLoc,
5072 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005073 if (!AStmt)
5074 return StmtError();
5075
Alexey Bataev13314bf2014-10-09 04:18:56 +00005076 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5077 // 1.2.2 OpenMP Language Terminology
5078 // Structured block - An executable statement with a single entry at the
5079 // top and a single exit at the bottom.
5080 // The point of exit cannot be a branch out of the structured block.
5081 // longjmp() and throw() must not violate the entry/exit criteria.
5082 CS->getCapturedDecl()->setNothrow();
5083
5084 getCurFunction()->setHasBranchProtectedScope();
5085
5086 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5087}
5088
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005089StmtResult
5090Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5091 SourceLocation EndLoc,
5092 OpenMPDirectiveKind CancelRegion) {
5093 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5094 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5095 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5096 << getOpenMPDirectiveName(CancelRegion);
5097 return StmtError();
5098 }
5099 if (DSAStack->isParentNowaitRegion()) {
5100 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5101 return StmtError();
5102 }
5103 if (DSAStack->isParentOrderedRegion()) {
5104 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5105 return StmtError();
5106 }
5107 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5108 CancelRegion);
5109}
5110
Alexey Bataev87933c72015-09-18 08:07:34 +00005111StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5112 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005113 SourceLocation EndLoc,
5114 OpenMPDirectiveKind CancelRegion) {
5115 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5116 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5117 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5118 << getOpenMPDirectiveName(CancelRegion);
5119 return StmtError();
5120 }
5121 if (DSAStack->isParentNowaitRegion()) {
5122 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5123 return StmtError();
5124 }
5125 if (DSAStack->isParentOrderedRegion()) {
5126 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5127 return StmtError();
5128 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005129 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005130 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5131 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005132}
5133
Alexey Bataev49f6e782015-12-01 04:18:41 +00005134StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5135 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5136 SourceLocation EndLoc,
5137 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
5138 if (!AStmt)
5139 return StmtError();
5140
5141 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5142 OMPLoopDirective::HelperExprs B;
5143 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5144 // define the nested loops number.
5145 unsigned NestedLoopCount =
5146 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
5147 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5148 VarsWithImplicitDSA, B);
5149 if (NestedLoopCount == 0)
5150 return StmtError();
5151
5152 assert((CurContext->isDependentContext() || B.builtAll()) &&
5153 "omp for loop exprs were not built");
5154
5155 getCurFunction()->setHasBranchProtectedScope();
5156 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5157 NestedLoopCount, Clauses, AStmt, B);
5158}
5159
Alexey Bataeved09d242014-05-28 05:53:51 +00005160OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005161 SourceLocation StartLoc,
5162 SourceLocation LParenLoc,
5163 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005164 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005165 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00005166 case OMPC_final:
5167 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
5168 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00005169 case OMPC_num_threads:
5170 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
5171 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00005172 case OMPC_safelen:
5173 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
5174 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00005175 case OMPC_simdlen:
5176 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
5177 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00005178 case OMPC_collapse:
5179 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
5180 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005181 case OMPC_ordered:
5182 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
5183 break;
Michael Wonge710d542015-08-07 16:16:36 +00005184 case OMPC_device:
5185 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
5186 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00005187 case OMPC_num_teams:
5188 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
5189 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00005190 case OMPC_thread_limit:
5191 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
5192 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005193 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005194 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005195 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005196 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005197 case OMPC_private:
5198 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00005199 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005200 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005201 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00005202 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005203 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005204 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005205 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00005206 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005207 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005208 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005209 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005210 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005211 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005212 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005213 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005214 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005215 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005216 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00005217 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005218 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00005219 case OMPC_map:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005220 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005221 llvm_unreachable("Clause is not allowed.");
5222 }
5223 return Res;
5224}
5225
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005226OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
5227 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005228 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005229 SourceLocation NameModifierLoc,
5230 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005231 SourceLocation EndLoc) {
5232 Expr *ValExpr = Condition;
5233 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
5234 !Condition->isInstantiationDependent() &&
5235 !Condition->containsUnexpandedParameterPack()) {
5236 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00005237 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005238 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005239 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005240
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005241 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005242 }
5243
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005244 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
5245 NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005246}
5247
Alexey Bataev3778b602014-07-17 07:32:53 +00005248OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
5249 SourceLocation StartLoc,
5250 SourceLocation LParenLoc,
5251 SourceLocation EndLoc) {
5252 Expr *ValExpr = Condition;
5253 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
5254 !Condition->isInstantiationDependent() &&
5255 !Condition->containsUnexpandedParameterPack()) {
5256 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
5257 Condition->getExprLoc(), Condition);
5258 if (Val.isInvalid())
5259 return nullptr;
5260
5261 ValExpr = Val.get();
5262 }
5263
5264 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
5265}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005266ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
5267 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00005268 if (!Op)
5269 return ExprError();
5270
5271 class IntConvertDiagnoser : public ICEConvertDiagnoser {
5272 public:
5273 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00005274 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00005275 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
5276 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005277 return S.Diag(Loc, diag::err_omp_not_integral) << T;
5278 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005279 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
5280 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005281 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
5282 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005283 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
5284 QualType T,
5285 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005286 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
5287 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005288 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
5289 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005290 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00005291 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00005292 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005293 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
5294 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005295 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
5296 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005297 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
5298 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005299 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00005300 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00005301 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005302 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
5303 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005304 llvm_unreachable("conversion functions are permitted");
5305 }
5306 } ConvertDiagnoser;
5307 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
5308}
5309
Kelvin Lia15fb1a2015-11-27 18:47:36 +00005310static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
5311 OpenMPClauseKind CKind) {
5312 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
5313 !ValExpr->isInstantiationDependent()) {
5314 SourceLocation Loc = ValExpr->getExprLoc();
5315 ExprResult Value =
5316 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
5317 if (Value.isInvalid())
5318 return false;
5319
5320 ValExpr = Value.get();
5321 // The expression must evaluate to a non-negative integer value.
5322 llvm::APSInt Result;
5323 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
5324 Result.isSigned() && !Result.isStrictlyPositive()) {
5325 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
5326 << getOpenMPClauseName(CKind) << ValExpr->getSourceRange();
5327 return false;
5328 }
5329 }
5330 return true;
5331}
5332
Alexey Bataev568a8332014-03-06 06:15:19 +00005333OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
5334 SourceLocation StartLoc,
5335 SourceLocation LParenLoc,
5336 SourceLocation EndLoc) {
5337 Expr *ValExpr = NumThreads;
Alexey Bataev568a8332014-03-06 06:15:19 +00005338
Kelvin Lia15fb1a2015-11-27 18:47:36 +00005339 // OpenMP [2.5, Restrictions]
5340 // The num_threads expression must evaluate to a positive integer value.
5341 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads))
5342 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00005343
Alexey Bataeved09d242014-05-28 05:53:51 +00005344 return new (Context)
5345 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00005346}
5347
Alexey Bataev62c87d22014-03-21 04:51:18 +00005348ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
5349 OpenMPClauseKind CKind) {
5350 if (!E)
5351 return ExprError();
5352 if (E->isValueDependent() || E->isTypeDependent() ||
5353 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005354 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00005355 llvm::APSInt Result;
5356 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
5357 if (ICE.isInvalid())
5358 return ExprError();
5359 if (!Result.isStrictlyPositive()) {
5360 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
5361 << getOpenMPClauseName(CKind) << E->getSourceRange();
5362 return ExprError();
5363 }
Alexander Musman09184fe2014-09-30 05:29:28 +00005364 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
5365 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
5366 << E->getSourceRange();
5367 return ExprError();
5368 }
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005369 if (CKind == OMPC_collapse)
5370 DSAStack->setCollapseNumber(Result.getExtValue());
5371 else if (CKind == OMPC_ordered)
5372 DSAStack->setCollapseNumber(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00005373 return ICE;
5374}
5375
5376OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
5377 SourceLocation LParenLoc,
5378 SourceLocation EndLoc) {
5379 // OpenMP [2.8.1, simd construct, Description]
5380 // The parameter of the safelen clause must be a constant
5381 // positive integer expression.
5382 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
5383 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005384 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00005385 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005386 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00005387}
5388
Alexey Bataev66b15b52015-08-21 11:14:16 +00005389OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
5390 SourceLocation LParenLoc,
5391 SourceLocation EndLoc) {
5392 // OpenMP [2.8.1, simd construct, Description]
5393 // The parameter of the simdlen clause must be a constant
5394 // positive integer expression.
5395 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
5396 if (Simdlen.isInvalid())
5397 return nullptr;
5398 return new (Context)
5399 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
5400}
5401
Alexander Musman64d33f12014-06-04 07:53:32 +00005402OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
5403 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00005404 SourceLocation LParenLoc,
5405 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00005406 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00005407 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00005408 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00005409 // The parameter of the collapse clause must be a constant
5410 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00005411 ExprResult NumForLoopsResult =
5412 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
5413 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00005414 return nullptr;
5415 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00005416 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00005417}
5418
Alexey Bataev10e775f2015-07-30 11:36:16 +00005419OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
5420 SourceLocation EndLoc,
5421 SourceLocation LParenLoc,
5422 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00005423 // OpenMP [2.7.1, loop construct, Description]
5424 // OpenMP [2.8.1, simd construct, Description]
5425 // OpenMP [2.9.6, distribute construct, Description]
5426 // The parameter of the ordered clause must be a constant
5427 // positive integer expression if any.
5428 if (NumForLoops && LParenLoc.isValid()) {
5429 ExprResult NumForLoopsResult =
5430 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
5431 if (NumForLoopsResult.isInvalid())
5432 return nullptr;
5433 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00005434 } else
5435 NumForLoops = nullptr;
5436 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00005437 return new (Context)
5438 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
5439}
5440
Alexey Bataeved09d242014-05-28 05:53:51 +00005441OMPClause *Sema::ActOnOpenMPSimpleClause(
5442 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
5443 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005444 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005445 switch (Kind) {
5446 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00005447 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00005448 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
5449 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005450 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005451 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00005452 Res = ActOnOpenMPProcBindClause(
5453 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
5454 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005455 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005456 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00005457 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00005458 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00005459 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005460 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00005461 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005462 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005463 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005464 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00005465 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00005466 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005467 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00005468 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005469 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005470 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005471 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005472 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00005473 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005474 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005475 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005476 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005477 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005478 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005479 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005480 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005481 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005482 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005483 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00005484 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00005485 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005486 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00005487 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00005488 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00005489 case OMPC_thread_limit:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005490 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005491 llvm_unreachable("Clause is not allowed.");
5492 }
5493 return Res;
5494}
5495
5496OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
5497 SourceLocation KindKwLoc,
5498 SourceLocation StartLoc,
5499 SourceLocation LParenLoc,
5500 SourceLocation EndLoc) {
5501 if (Kind == OMPC_DEFAULT_unknown) {
5502 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005503 static_assert(OMPC_DEFAULT_unknown > 0,
5504 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00005505 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005506 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005507 Values += "'";
5508 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
5509 Values += "'";
5510 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005511 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005512 Values += " or ";
5513 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005514 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005515 break;
5516 default:
5517 Values += Sep;
5518 break;
5519 }
5520 }
5521 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00005522 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005523 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005524 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00005525 switch (Kind) {
5526 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005527 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005528 break;
5529 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005530 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005531 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005532 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005533 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00005534 break;
5535 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005536 return new (Context)
5537 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005538}
5539
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005540OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
5541 SourceLocation KindKwLoc,
5542 SourceLocation StartLoc,
5543 SourceLocation LParenLoc,
5544 SourceLocation EndLoc) {
5545 if (Kind == OMPC_PROC_BIND_unknown) {
5546 std::string Values;
5547 std::string Sep(", ");
5548 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
5549 Values += "'";
5550 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
5551 Values += "'";
5552 switch (i) {
5553 case OMPC_PROC_BIND_unknown - 2:
5554 Values += " or ";
5555 break;
5556 case OMPC_PROC_BIND_unknown - 1:
5557 break;
5558 default:
5559 Values += Sep;
5560 break;
5561 }
5562 }
5563 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00005564 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005565 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005566 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005567 return new (Context)
5568 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005569}
5570
Alexey Bataev56dafe82014-06-20 07:16:17 +00005571OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
5572 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
5573 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005574 SourceLocation ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00005575 SourceLocation EndLoc) {
5576 OMPClause *Res = nullptr;
5577 switch (Kind) {
5578 case OMPC_schedule:
5579 Res = ActOnOpenMPScheduleClause(
5580 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005581 LParenLoc, ArgumentLoc, DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00005582 break;
5583 case OMPC_if:
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005584 Res =
5585 ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument), Expr,
5586 StartLoc, LParenLoc, ArgumentLoc, DelimLoc, EndLoc);
5587 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00005588 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005589 case OMPC_num_threads:
5590 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005591 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005592 case OMPC_collapse:
5593 case OMPC_default:
5594 case OMPC_proc_bind:
5595 case OMPC_private:
5596 case OMPC_firstprivate:
5597 case OMPC_lastprivate:
5598 case OMPC_shared:
5599 case OMPC_reduction:
5600 case OMPC_linear:
5601 case OMPC_aligned:
5602 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005603 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005604 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00005605 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005606 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005607 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005608 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005609 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005610 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005611 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005612 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005613 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005614 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005615 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00005616 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00005617 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005618 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00005619 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00005620 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00005621 case OMPC_thread_limit:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005622 case OMPC_unknown:
5623 llvm_unreachable("Clause is not allowed.");
5624 }
5625 return Res;
5626}
5627
5628OMPClause *Sema::ActOnOpenMPScheduleClause(
5629 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
5630 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
5631 SourceLocation EndLoc) {
5632 if (Kind == OMPC_SCHEDULE_unknown) {
5633 std::string Values;
5634 std::string Sep(", ");
5635 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
5636 Values += "'";
5637 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
5638 Values += "'";
5639 switch (i) {
5640 case OMPC_SCHEDULE_unknown - 2:
5641 Values += " or ";
5642 break;
5643 case OMPC_SCHEDULE_unknown - 1:
5644 break;
5645 default:
5646 Values += Sep;
5647 break;
5648 }
5649 }
5650 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
5651 << Values << getOpenMPClauseName(OMPC_schedule);
5652 return nullptr;
5653 }
5654 Expr *ValExpr = ChunkSize;
Alexey Bataev040d5402015-05-12 08:35:28 +00005655 Expr *HelperValExpr = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00005656 if (ChunkSize) {
5657 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
5658 !ChunkSize->isInstantiationDependent() &&
5659 !ChunkSize->containsUnexpandedParameterPack()) {
5660 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
5661 ExprResult Val =
5662 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
5663 if (Val.isInvalid())
5664 return nullptr;
5665
5666 ValExpr = Val.get();
5667
5668 // OpenMP [2.7.1, Restrictions]
5669 // chunk_size must be a loop invariant integer expression with a positive
5670 // value.
5671 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00005672 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
5673 if (Result.isSigned() && !Result.isStrictlyPositive()) {
5674 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
5675 << "schedule" << ChunkSize->getSourceRange();
5676 return nullptr;
5677 }
5678 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
5679 auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
5680 ChunkSize->getType(), ".chunk.");
5681 auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
5682 ChunkSize->getExprLoc(),
5683 /*RefersToCapture=*/true);
5684 HelperValExpr = ImpVarRef;
Alexey Bataev56dafe82014-06-20 07:16:17 +00005685 }
5686 }
5687 }
5688
5689 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
Alexey Bataev040d5402015-05-12 08:35:28 +00005690 EndLoc, Kind, ValExpr, HelperValExpr);
Alexey Bataev56dafe82014-06-20 07:16:17 +00005691}
5692
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005693OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
5694 SourceLocation StartLoc,
5695 SourceLocation EndLoc) {
5696 OMPClause *Res = nullptr;
5697 switch (Kind) {
5698 case OMPC_ordered:
5699 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
5700 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00005701 case OMPC_nowait:
5702 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
5703 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005704 case OMPC_untied:
5705 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
5706 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005707 case OMPC_mergeable:
5708 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
5709 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005710 case OMPC_read:
5711 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
5712 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00005713 case OMPC_write:
5714 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
5715 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005716 case OMPC_update:
5717 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
5718 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00005719 case OMPC_capture:
5720 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
5721 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005722 case OMPC_seq_cst:
5723 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
5724 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00005725 case OMPC_threads:
5726 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
5727 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005728 case OMPC_simd:
5729 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
5730 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005731 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00005732 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005733 case OMPC_num_threads:
5734 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005735 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005736 case OMPC_collapse:
5737 case OMPC_schedule:
5738 case OMPC_private:
5739 case OMPC_firstprivate:
5740 case OMPC_lastprivate:
5741 case OMPC_shared:
5742 case OMPC_reduction:
5743 case OMPC_linear:
5744 case OMPC_aligned:
5745 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005746 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005747 case OMPC_default:
5748 case OMPC_proc_bind:
5749 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005750 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005751 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00005752 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00005753 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00005754 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00005755 case OMPC_thread_limit:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005756 case OMPC_unknown:
5757 llvm_unreachable("Clause is not allowed.");
5758 }
5759 return Res;
5760}
5761
Alexey Bataev236070f2014-06-20 11:19:47 +00005762OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
5763 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005764 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00005765 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
5766}
5767
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005768OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
5769 SourceLocation EndLoc) {
5770 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
5771}
5772
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005773OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
5774 SourceLocation EndLoc) {
5775 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
5776}
5777
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005778OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
5779 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005780 return new (Context) OMPReadClause(StartLoc, EndLoc);
5781}
5782
Alexey Bataevdea47612014-07-23 07:46:59 +00005783OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
5784 SourceLocation EndLoc) {
5785 return new (Context) OMPWriteClause(StartLoc, EndLoc);
5786}
5787
Alexey Bataev67a4f222014-07-23 10:25:33 +00005788OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
5789 SourceLocation EndLoc) {
5790 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
5791}
5792
Alexey Bataev459dec02014-07-24 06:46:57 +00005793OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
5794 SourceLocation EndLoc) {
5795 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
5796}
5797
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005798OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
5799 SourceLocation EndLoc) {
5800 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
5801}
5802
Alexey Bataev346265e2015-09-25 10:37:12 +00005803OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
5804 SourceLocation EndLoc) {
5805 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
5806}
5807
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005808OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
5809 SourceLocation EndLoc) {
5810 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
5811}
5812
Alexey Bataevc5e02582014-06-16 07:08:35 +00005813OMPClause *Sema::ActOnOpenMPVarListClause(
5814 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
5815 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
5816 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005817 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Kelvin Li0bff7af2015-11-23 05:32:03 +00005818 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
5819 OpenMPMapClauseKind MapType, SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005820 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005821 switch (Kind) {
5822 case OMPC_private:
5823 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5824 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005825 case OMPC_firstprivate:
5826 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5827 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005828 case OMPC_lastprivate:
5829 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5830 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00005831 case OMPC_shared:
5832 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
5833 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005834 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00005835 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
5836 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005837 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00005838 case OMPC_linear:
5839 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00005840 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00005841 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005842 case OMPC_aligned:
5843 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
5844 ColonLoc, EndLoc);
5845 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005846 case OMPC_copyin:
5847 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
5848 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00005849 case OMPC_copyprivate:
5850 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5851 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00005852 case OMPC_flush:
5853 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
5854 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005855 case OMPC_depend:
Kelvin Li0bff7af2015-11-23 05:32:03 +00005856 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
5857 StartLoc, LParenLoc, EndLoc);
5858 break;
5859 case OMPC_map:
5860 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, DepLinMapLoc, ColonLoc,
5861 VarList, StartLoc, LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005862 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005863 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00005864 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00005865 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00005866 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005867 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00005868 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005869 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005870 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005871 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005872 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00005873 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005874 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005875 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005876 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005877 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005878 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005879 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005880 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005881 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00005882 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00005883 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005884 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00005885 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00005886 case OMPC_thread_limit:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005887 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005888 llvm_unreachable("Clause is not allowed.");
5889 }
5890 return Res;
5891}
5892
5893OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
5894 SourceLocation StartLoc,
5895 SourceLocation LParenLoc,
5896 SourceLocation EndLoc) {
5897 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00005898 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00005899 for (auto &RefExpr : VarList) {
5900 assert(RefExpr && "NULL expr in OpenMP private clause.");
5901 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005902 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005903 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005904 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005905 continue;
5906 }
5907
Alexey Bataeved09d242014-05-28 05:53:51 +00005908 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005909 // OpenMP [2.1, C/C++]
5910 // A list item is a variable name.
5911 // OpenMP [2.9.3.3, Restrictions, p.1]
5912 // A variable that is part of another variable (as an array or
5913 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005914 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005915 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005916 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005917 continue;
5918 }
5919 Decl *D = DE->getDecl();
5920 VarDecl *VD = cast<VarDecl>(D);
5921
5922 QualType Type = VD->getType();
5923 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5924 // It will be analyzed later.
5925 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005926 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005927 continue;
5928 }
5929
5930 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5931 // A variable that appears in a private clause must not have an incomplete
5932 // type or a reference type.
5933 if (RequireCompleteType(ELoc, Type,
5934 diag::err_omp_private_incomplete_type)) {
5935 continue;
5936 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00005937 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005938
Alexey Bataev758e55e2013-09-06 18:03:48 +00005939 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5940 // in a Construct]
5941 // Variables with the predetermined data-sharing attributes may not be
5942 // listed in data-sharing attributes clauses, except for the cases
5943 // listed below. For these exceptions only, listing a predetermined
5944 // variable in a data-sharing attribute clause is allowed and overrides
5945 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005946 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005947 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005948 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5949 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005950 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005951 continue;
5952 }
5953
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005954 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00005955 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005956 DSAStack->getCurrentDirective() == OMPD_task) {
5957 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5958 << getOpenMPClauseName(OMPC_private) << Type
5959 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5960 bool IsDecl =
5961 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5962 Diag(VD->getLocation(),
5963 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5964 << VD;
5965 continue;
5966 }
5967
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005968 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
5969 // A variable of class type (or array thereof) that appears in a private
5970 // clause requires an accessible, unambiguous default constructor for the
5971 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00005972 // Generate helper private variable and initialize it with the default
5973 // value. The address of the original variable is replaced by the address of
5974 // the new private variable in CodeGen. This new variable is not added to
5975 // IdResolver, so the code in the OpenMP region uses original variable for
5976 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005977 Type = Type.getUnqualifiedType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00005978 auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName(),
5979 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005980 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005981 if (VDPrivate->isInvalidDecl())
5982 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005983 auto VDPrivateRefExpr = buildDeclRefExpr(
5984 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev03b340a2014-10-21 03:16:40 +00005985
Alexey Bataev758e55e2013-09-06 18:03:48 +00005986 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005987 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005988 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005989 }
5990
Alexey Bataeved09d242014-05-28 05:53:51 +00005991 if (Vars.empty())
5992 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005993
Alexey Bataev03b340a2014-10-21 03:16:40 +00005994 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
5995 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005996}
5997
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005998namespace {
5999class DiagsUninitializedSeveretyRAII {
6000private:
6001 DiagnosticsEngine &Diags;
6002 SourceLocation SavedLoc;
6003 bool IsIgnored;
6004
6005public:
6006 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
6007 bool IsIgnored)
6008 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
6009 if (!IsIgnored) {
6010 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
6011 /*Map*/ diag::Severity::Ignored, Loc);
6012 }
6013 }
6014 ~DiagsUninitializedSeveretyRAII() {
6015 if (!IsIgnored)
6016 Diags.popMappings(SavedLoc);
6017 }
6018};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006019}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006020
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006021OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
6022 SourceLocation StartLoc,
6023 SourceLocation LParenLoc,
6024 SourceLocation EndLoc) {
6025 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006026 SmallVector<Expr *, 8> PrivateCopies;
6027 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006028 bool IsImplicitClause =
6029 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
6030 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
6031
Alexey Bataeved09d242014-05-28 05:53:51 +00006032 for (auto &RefExpr : VarList) {
6033 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
6034 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006035 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006036 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006037 PrivateCopies.push_back(nullptr);
6038 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006039 continue;
6040 }
6041
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006042 SourceLocation ELoc =
6043 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006044 // OpenMP [2.1, C/C++]
6045 // A list item is a variable name.
6046 // OpenMP [2.9.3.3, Restrictions, p.1]
6047 // A variable that is part of another variable (as an array or
6048 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00006049 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006050 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00006051 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006052 continue;
6053 }
6054 Decl *D = DE->getDecl();
6055 VarDecl *VD = cast<VarDecl>(D);
6056
6057 QualType Type = VD->getType();
6058 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6059 // It will be analyzed later.
6060 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006061 PrivateCopies.push_back(nullptr);
6062 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006063 continue;
6064 }
6065
6066 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
6067 // A variable that appears in a private clause must not have an incomplete
6068 // type or a reference type.
6069 if (RequireCompleteType(ELoc, Type,
6070 diag::err_omp_firstprivate_incomplete_type)) {
6071 continue;
6072 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006073 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006074
6075 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
6076 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00006077 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006078 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006079 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006080
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006081 // If an implicit firstprivate variable found it was checked already.
6082 if (!IsImplicitClause) {
6083 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006084 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006085 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
6086 // A list item that specifies a given variable may not appear in more
6087 // than one clause on the same directive, except that a variable may be
6088 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006089 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00006090 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006091 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00006092 << getOpenMPClauseName(DVar.CKind)
6093 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006094 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006095 continue;
6096 }
6097
6098 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
6099 // in a Construct]
6100 // Variables with the predetermined data-sharing attributes may not be
6101 // listed in data-sharing attributes clauses, except for the cases
6102 // listed below. For these exceptions only, listing a predetermined
6103 // variable in a data-sharing attribute clause is allowed and overrides
6104 // the variable's predetermined data-sharing attributes.
6105 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
6106 // in a Construct, C/C++, p.2]
6107 // Variables with const-qualified type having no mutable member may be
6108 // listed in a firstprivate clause, even if they are static data members.
6109 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
6110 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
6111 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00006112 << getOpenMPClauseName(DVar.CKind)
6113 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006114 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006115 continue;
6116 }
6117
Alexey Bataevf29276e2014-06-18 04:14:57 +00006118 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006119 // OpenMP [2.9.3.4, Restrictions, p.2]
6120 // A list item that is private within a parallel region must not appear
6121 // in a firstprivate clause on a worksharing construct if any of the
6122 // worksharing regions arising from the worksharing construct ever bind
6123 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00006124 if (isOpenMPWorksharingDirective(CurrDir) &&
6125 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006126 DVar = DSAStack->getImplicitDSA(VD, true);
6127 if (DVar.CKind != OMPC_shared &&
6128 (isOpenMPParallelDirective(DVar.DKind) ||
6129 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00006130 Diag(ELoc, diag::err_omp_required_access)
6131 << getOpenMPClauseName(OMPC_firstprivate)
6132 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006133 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006134 continue;
6135 }
6136 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006137 // OpenMP [2.9.3.4, Restrictions, p.3]
6138 // A list item that appears in a reduction clause of a parallel construct
6139 // must not appear in a firstprivate clause on a worksharing or task
6140 // construct if any of the worksharing or task regions arising from the
6141 // worksharing or task construct ever bind to any of the parallel regions
6142 // arising from the parallel construct.
6143 // OpenMP [2.9.3.4, Restrictions, p.4]
6144 // A list item that appears in a reduction clause in worksharing
6145 // construct must not appear in a firstprivate clause in a task construct
6146 // encountered during execution of any of the worksharing regions arising
6147 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006148 if (CurrDir == OMPD_task) {
6149 DVar =
6150 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
6151 [](OpenMPDirectiveKind K) -> bool {
6152 return isOpenMPParallelDirective(K) ||
6153 isOpenMPWorksharingDirective(K);
6154 },
6155 false);
6156 if (DVar.CKind == OMPC_reduction &&
6157 (isOpenMPParallelDirective(DVar.DKind) ||
6158 isOpenMPWorksharingDirective(DVar.DKind))) {
6159 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
6160 << getOpenMPDirectiveName(DVar.DKind);
6161 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6162 continue;
6163 }
6164 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006165 }
6166
Alexey Bataevccb59ec2015-05-19 08:44:56 +00006167 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00006168 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataevccb59ec2015-05-19 08:44:56 +00006169 DSAStack->getCurrentDirective() == OMPD_task) {
6170 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
6171 << getOpenMPClauseName(OMPC_firstprivate) << Type
6172 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
6173 bool IsDecl =
6174 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6175 Diag(VD->getLocation(),
6176 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6177 << VD;
6178 continue;
6179 }
6180
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006181 Type = Type.getUnqualifiedType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00006182 auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName(),
6183 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006184 // Generate helper private variable and initialize it with the value of the
6185 // original variable. The address of the original variable is replaced by
6186 // the address of the new private variable in the CodeGen. This new variable
6187 // is not added to IdResolver, so the code in the OpenMP region uses
6188 // original variable for proper diagnostics and variable capturing.
6189 Expr *VDInitRefExpr = nullptr;
6190 // For arrays generate initializer for single element and replace it by the
6191 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006192 if (Type->isArrayType()) {
6193 auto VDInit =
6194 buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
6195 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006196 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006197 ElemType = ElemType.getUnqualifiedType();
6198 auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
6199 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00006200 InitializedEntity Entity =
6201 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006202 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
6203
6204 InitializationSequence InitSeq(*this, Entity, Kind, Init);
6205 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
6206 if (Result.isInvalid())
6207 VDPrivate->setInvalidDecl();
6208 else
6209 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006210 // Remove temp variable declaration.
6211 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006212 } else {
Alexey Bataev69c62a92015-04-15 04:52:20 +00006213 auto *VDInit =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006214 buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006215 VDInitRefExpr =
6216 buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00006217 AddInitializerToDecl(VDPrivate,
6218 DefaultLvalueConversion(VDInitRefExpr).get(),
6219 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006220 }
6221 if (VDPrivate->isInvalidDecl()) {
6222 if (IsImplicitClause) {
6223 Diag(DE->getExprLoc(),
6224 diag::note_omp_task_predetermined_firstprivate_here);
6225 }
6226 continue;
6227 }
6228 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00006229 auto VDPrivateRefExpr = buildDeclRefExpr(
6230 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006231 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
6232 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006233 PrivateCopies.push_back(VDPrivateRefExpr);
6234 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006235 }
6236
Alexey Bataeved09d242014-05-28 05:53:51 +00006237 if (Vars.empty())
6238 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006239
6240 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006241 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006242}
6243
Alexander Musman1bb328c2014-06-04 13:06:39 +00006244OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
6245 SourceLocation StartLoc,
6246 SourceLocation LParenLoc,
6247 SourceLocation EndLoc) {
6248 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00006249 SmallVector<Expr *, 8> SrcExprs;
6250 SmallVector<Expr *, 8> DstExprs;
6251 SmallVector<Expr *, 8> AssignmentOps;
Alexander Musman1bb328c2014-06-04 13:06:39 +00006252 for (auto &RefExpr : VarList) {
6253 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
6254 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6255 // It will be analyzed later.
6256 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00006257 SrcExprs.push_back(nullptr);
6258 DstExprs.push_back(nullptr);
6259 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006260 continue;
6261 }
6262
6263 SourceLocation ELoc = RefExpr->getExprLoc();
6264 // OpenMP [2.1, C/C++]
6265 // A list item is a variable name.
6266 // OpenMP [2.14.3.5, Restrictions, p.1]
6267 // A variable that is part of another variable (as an array or structure
6268 // element) cannot appear in a lastprivate clause.
6269 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
6270 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6271 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6272 continue;
6273 }
6274 Decl *D = DE->getDecl();
6275 VarDecl *VD = cast<VarDecl>(D);
6276
6277 QualType Type = VD->getType();
6278 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6279 // It will be analyzed later.
6280 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00006281 SrcExprs.push_back(nullptr);
6282 DstExprs.push_back(nullptr);
6283 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006284 continue;
6285 }
6286
6287 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
6288 // A variable that appears in a lastprivate clause must not have an
6289 // incomplete type or a reference type.
6290 if (RequireCompleteType(ELoc, Type,
6291 diag::err_omp_lastprivate_incomplete_type)) {
6292 continue;
6293 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006294 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00006295
6296 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
6297 // in a Construct]
6298 // Variables with the predetermined data-sharing attributes may not be
6299 // listed in data-sharing attributes clauses, except for the cases
6300 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006301 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006302 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
6303 DVar.CKind != OMPC_firstprivate &&
6304 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
6305 Diag(ELoc, diag::err_omp_wrong_dsa)
6306 << getOpenMPClauseName(DVar.CKind)
6307 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006308 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006309 continue;
6310 }
6311
Alexey Bataevf29276e2014-06-18 04:14:57 +00006312 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
6313 // OpenMP [2.14.3.5, Restrictions, p.2]
6314 // A list item that is private within a parallel region, or that appears in
6315 // the reduction clause of a parallel construct, must not appear in a
6316 // lastprivate clause on a worksharing construct if any of the corresponding
6317 // worksharing regions ever binds to any of the corresponding parallel
6318 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00006319 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00006320 if (isOpenMPWorksharingDirective(CurrDir) &&
6321 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006322 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006323 if (DVar.CKind != OMPC_shared) {
6324 Diag(ELoc, diag::err_omp_required_access)
6325 << getOpenMPClauseName(OMPC_lastprivate)
6326 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006327 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006328 continue;
6329 }
6330 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00006331 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00006332 // A variable of class type (or array thereof) that appears in a
6333 // lastprivate clause requires an accessible, unambiguous default
6334 // constructor for the class type, unless the list item is also specified
6335 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00006336 // A variable of class type (or array thereof) that appears in a
6337 // lastprivate clause requires an accessible, unambiguous copy assignment
6338 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00006339 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00006340 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00006341 Type.getUnqualifiedType(), ".lastprivate.src",
6342 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00006343 auto *PseudoSrcExpr = buildDeclRefExpr(
6344 *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00006345 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00006346 buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst",
6347 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00006348 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006349 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00006350 // For arrays generate assignment operation for single element and replace
6351 // it by the original array element in CodeGen.
6352 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6353 PseudoDstExpr, PseudoSrcExpr);
6354 if (AssignmentOp.isInvalid())
6355 continue;
6356 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6357 /*DiscardedValue=*/true);
6358 if (AssignmentOp.isInvalid())
6359 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00006360
Alexey Bataev39f915b82015-05-08 10:41:21 +00006361 if (TopDVar.CKind != OMPC_firstprivate)
Alexey Bataevf29276e2014-06-18 04:14:57 +00006362 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006363 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00006364 SrcExprs.push_back(PseudoSrcExpr);
6365 DstExprs.push_back(PseudoDstExpr);
6366 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00006367 }
6368
6369 if (Vars.empty())
6370 return nullptr;
6371
6372 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00006373 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006374}
6375
Alexey Bataev758e55e2013-09-06 18:03:48 +00006376OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
6377 SourceLocation StartLoc,
6378 SourceLocation LParenLoc,
6379 SourceLocation EndLoc) {
6380 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00006381 for (auto &RefExpr : VarList) {
6382 assert(RefExpr && "NULL expr in OpenMP shared clause.");
6383 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00006384 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006385 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006386 continue;
6387 }
6388
Alexey Bataeved09d242014-05-28 05:53:51 +00006389 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00006390 // OpenMP [2.1, C/C++]
6391 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00006392 // OpenMP [2.14.3.2, Restrictions, p.1]
6393 // A variable that is part of another variable (as an array or structure
6394 // element) cannot appear in a shared unless it is a static data member
6395 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00006396 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006397 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00006398 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00006399 continue;
6400 }
6401 Decl *D = DE->getDecl();
6402 VarDecl *VD = cast<VarDecl>(D);
6403
6404 QualType Type = VD->getType();
6405 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6406 // It will be analyzed later.
6407 Vars.push_back(DE);
6408 continue;
6409 }
6410
6411 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
6412 // in a Construct]
6413 // Variables with the predetermined data-sharing attributes may not be
6414 // listed in data-sharing attributes clauses, except for the cases
6415 // listed below. For these exceptions only, listing a predetermined
6416 // variable in a data-sharing attribute clause is allowed and overrides
6417 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006418 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00006419 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
6420 DVar.RefExpr) {
6421 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
6422 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006423 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006424 continue;
6425 }
6426
6427 DSAStack->addDSA(VD, DE, OMPC_shared);
6428 Vars.push_back(DE);
6429 }
6430
Alexey Bataeved09d242014-05-28 05:53:51 +00006431 if (Vars.empty())
6432 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00006433
6434 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
6435}
6436
Alexey Bataevc5e02582014-06-16 07:08:35 +00006437namespace {
6438class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
6439 DSAStackTy *Stack;
6440
6441public:
6442 bool VisitDeclRefExpr(DeclRefExpr *E) {
6443 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006444 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006445 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
6446 return false;
6447 if (DVar.CKind != OMPC_unknown)
6448 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00006449 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006450 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006451 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00006452 return true;
6453 return false;
6454 }
6455 return false;
6456 }
6457 bool VisitStmt(Stmt *S) {
6458 for (auto Child : S->children()) {
6459 if (Child && Visit(Child))
6460 return true;
6461 }
6462 return false;
6463 }
Alexey Bataev23b69422014-06-18 07:08:49 +00006464 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00006465};
Alexey Bataev23b69422014-06-18 07:08:49 +00006466} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00006467
6468OMPClause *Sema::ActOnOpenMPReductionClause(
6469 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
6470 SourceLocation ColonLoc, SourceLocation EndLoc,
6471 CXXScopeSpec &ReductionIdScopeSpec,
6472 const DeclarationNameInfo &ReductionId) {
6473 // TODO: Allow scope specification search when 'declare reduction' is
6474 // supported.
6475 assert(ReductionIdScopeSpec.isEmpty() &&
6476 "No support for scoped reduction identifiers yet.");
6477
6478 auto DN = ReductionId.getName();
6479 auto OOK = DN.getCXXOverloadedOperator();
6480 BinaryOperatorKind BOK = BO_Comma;
6481
6482 // OpenMP [2.14.3.6, reduction clause]
6483 // C
6484 // reduction-identifier is either an identifier or one of the following
6485 // operators: +, -, *, &, |, ^, && and ||
6486 // C++
6487 // reduction-identifier is either an id-expression or one of the following
6488 // operators: +, -, *, &, |, ^, && and ||
6489 // FIXME: Only 'min' and 'max' identifiers are supported for now.
6490 switch (OOK) {
6491 case OO_Plus:
6492 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006493 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006494 break;
6495 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006496 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006497 break;
6498 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006499 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006500 break;
6501 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006502 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006503 break;
6504 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006505 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006506 break;
6507 case OO_AmpAmp:
6508 BOK = BO_LAnd;
6509 break;
6510 case OO_PipePipe:
6511 BOK = BO_LOr;
6512 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006513 case OO_New:
6514 case OO_Delete:
6515 case OO_Array_New:
6516 case OO_Array_Delete:
6517 case OO_Slash:
6518 case OO_Percent:
6519 case OO_Tilde:
6520 case OO_Exclaim:
6521 case OO_Equal:
6522 case OO_Less:
6523 case OO_Greater:
6524 case OO_LessEqual:
6525 case OO_GreaterEqual:
6526 case OO_PlusEqual:
6527 case OO_MinusEqual:
6528 case OO_StarEqual:
6529 case OO_SlashEqual:
6530 case OO_PercentEqual:
6531 case OO_CaretEqual:
6532 case OO_AmpEqual:
6533 case OO_PipeEqual:
6534 case OO_LessLess:
6535 case OO_GreaterGreater:
6536 case OO_LessLessEqual:
6537 case OO_GreaterGreaterEqual:
6538 case OO_EqualEqual:
6539 case OO_ExclaimEqual:
6540 case OO_PlusPlus:
6541 case OO_MinusMinus:
6542 case OO_Comma:
6543 case OO_ArrowStar:
6544 case OO_Arrow:
6545 case OO_Call:
6546 case OO_Subscript:
6547 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00006548 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006549 case NUM_OVERLOADED_OPERATORS:
6550 llvm_unreachable("Unexpected reduction identifier");
6551 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006552 if (auto II = DN.getAsIdentifierInfo()) {
6553 if (II->isStr("max"))
6554 BOK = BO_GT;
6555 else if (II->isStr("min"))
6556 BOK = BO_LT;
6557 }
6558 break;
6559 }
6560 SourceRange ReductionIdRange;
6561 if (ReductionIdScopeSpec.isValid()) {
6562 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
6563 }
6564 ReductionIdRange.setEnd(ReductionId.getEndLoc());
6565 if (BOK == BO_Comma) {
6566 // Not allowed reduction identifier is found.
6567 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
6568 << ReductionIdRange;
6569 return nullptr;
6570 }
6571
6572 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006573 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006574 SmallVector<Expr *, 8> LHSs;
6575 SmallVector<Expr *, 8> RHSs;
6576 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006577 for (auto RefExpr : VarList) {
6578 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
6579 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6580 // It will be analyzed later.
6581 Vars.push_back(RefExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006582 Privates.push_back(nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006583 LHSs.push_back(nullptr);
6584 RHSs.push_back(nullptr);
6585 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006586 continue;
6587 }
6588
6589 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
6590 RefExpr->isInstantiationDependent() ||
6591 RefExpr->containsUnexpandedParameterPack()) {
6592 // It will be analyzed later.
6593 Vars.push_back(RefExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006594 Privates.push_back(nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006595 LHSs.push_back(nullptr);
6596 RHSs.push_back(nullptr);
6597 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006598 continue;
6599 }
6600
6601 auto ELoc = RefExpr->getExprLoc();
6602 auto ERange = RefExpr->getSourceRange();
6603 // OpenMP [2.1, C/C++]
6604 // A list item is a variable or array section, subject to the restrictions
6605 // specified in Section 2.4 on page 42 and in each of the sections
6606 // describing clauses and directives for which a list appears.
6607 // OpenMP [2.14.3.3, Restrictions, p.1]
6608 // A variable that is part of another variable (as an array or
6609 // structure element) cannot appear in a private clause.
Alexey Bataeva1764212015-09-30 09:22:36 +00006610 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
6611 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr);
6612 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr);
6613 if (!ASE && !OASE && (!DE || !isa<VarDecl>(DE->getDecl()))) {
6614 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item) << ERange;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006615 continue;
6616 }
Alexey Bataeva1764212015-09-30 09:22:36 +00006617 QualType Type;
6618 VarDecl *VD = nullptr;
6619 if (DE) {
6620 auto D = DE->getDecl();
6621 VD = cast<VarDecl>(D);
6622 Type = VD->getType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006623 } else if (ASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006624 Type = ASE->getType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006625 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
6626 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
6627 Base = TempASE->getBase()->IgnoreParenImpCasts();
6628 DE = dyn_cast<DeclRefExpr>(Base);
6629 if (DE)
6630 VD = dyn_cast<VarDecl>(DE->getDecl());
6631 if (!VD) {
6632 Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name)
6633 << 0 << Base->getSourceRange();
6634 continue;
6635 }
6636 } else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006637 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
6638 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
6639 Type = ATy->getElementType();
6640 else
6641 Type = BaseType->getPointeeType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006642 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
6643 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
6644 Base = TempOASE->getBase()->IgnoreParenImpCasts();
6645 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
6646 Base = TempASE->getBase()->IgnoreParenImpCasts();
6647 DE = dyn_cast<DeclRefExpr>(Base);
6648 if (DE)
6649 VD = dyn_cast<VarDecl>(DE->getDecl());
6650 if (!VD) {
6651 Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name)
6652 << 1 << Base->getSourceRange();
6653 continue;
6654 }
Alexey Bataeva1764212015-09-30 09:22:36 +00006655 }
6656
Alexey Bataevc5e02582014-06-16 07:08:35 +00006657 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
6658 // A variable that appears in a private clause must not have an incomplete
6659 // type or a reference type.
6660 if (RequireCompleteType(ELoc, Type,
6661 diag::err_omp_reduction_incomplete_type))
6662 continue;
6663 // OpenMP [2.14.3.6, reduction clause, Restrictions]
6664 // Arrays may not appear in a reduction clause.
6665 if (Type.getNonReferenceType()->isArrayType()) {
6666 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006667 if (!ASE && !OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006668 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6669 VarDecl::DeclarationOnly;
6670 Diag(VD->getLocation(),
6671 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6672 << VD;
6673 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006674 continue;
6675 }
6676 // OpenMP [2.14.3.6, reduction clause, Restrictions]
6677 // A list item that appears in a reduction clause must not be
6678 // const-qualified.
6679 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006680 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00006681 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006682 if (!ASE && !OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006683 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6684 VarDecl::DeclarationOnly;
6685 Diag(VD->getLocation(),
6686 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6687 << VD;
6688 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006689 continue;
6690 }
6691 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
6692 // If a list-item is a reference type then it must bind to the same object
6693 // for all threads of the team.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006694 if (!ASE && !OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006695 VarDecl *VDDef = VD->getDefinition();
6696 if (Type->isReferenceType() && VDDef) {
6697 DSARefChecker Check(DSAStack);
6698 if (Check.Visit(VDDef->getInit())) {
6699 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
6700 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
6701 continue;
6702 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006703 }
6704 }
6705 // OpenMP [2.14.3.6, reduction clause, Restrictions]
6706 // The type of a list item that appears in a reduction clause must be valid
6707 // for the reduction-identifier. For a max or min reduction in C, the type
6708 // of the list item must be an allowed arithmetic data type: char, int,
6709 // float, double, or _Bool, possibly modified with long, short, signed, or
6710 // unsigned. For a max or min reduction in C++, the type of the list item
6711 // must be an allowed arithmetic data type: char, wchar_t, int, float,
6712 // double, or bool, possibly modified with long, short, signed, or unsigned.
6713 if ((BOK == BO_GT || BOK == BO_LT) &&
6714 !(Type->isScalarType() ||
6715 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
6716 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
6717 << getLangOpts().CPlusPlus;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006718 if (!ASE && !OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006719 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6720 VarDecl::DeclarationOnly;
6721 Diag(VD->getLocation(),
6722 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6723 << VD;
6724 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006725 continue;
6726 }
6727 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
6728 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
6729 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006730 if (!ASE && !OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006731 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6732 VarDecl::DeclarationOnly;
6733 Diag(VD->getLocation(),
6734 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6735 << VD;
6736 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006737 continue;
6738 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006739 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
6740 // in a Construct]
6741 // Variables with the predetermined data-sharing attributes may not be
6742 // listed in data-sharing attributes clauses, except for the cases
6743 // listed below. For these exceptions only, listing a predetermined
6744 // variable in a data-sharing attribute clause is allowed and overrides
6745 // the variable's predetermined data-sharing attributes.
6746 // OpenMP [2.14.3.6, Restrictions, p.3]
6747 // Any number of reduction clauses can be specified on the directive,
6748 // but a list item can appear only once in the reduction clauses for that
6749 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00006750 DSAStackTy::DSAVarData DVar;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006751 DVar = DSAStack->getTopDSA(VD, false);
6752 if (DVar.CKind == OMPC_reduction) {
6753 Diag(ELoc, diag::err_omp_once_referenced)
6754 << getOpenMPClauseName(OMPC_reduction);
6755 if (DVar.RefExpr) {
6756 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006757 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006758 } else if (DVar.CKind != OMPC_unknown) {
6759 Diag(ELoc, diag::err_omp_wrong_dsa)
6760 << getOpenMPClauseName(DVar.CKind)
6761 << getOpenMPClauseName(OMPC_reduction);
6762 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6763 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006764 }
6765
6766 // OpenMP [2.14.3.6, Restrictions, p.1]
6767 // A list item that appears in a reduction clause of a worksharing
6768 // construct must be shared in the parallel regions to which any of the
6769 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006770 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
6771 if (isOpenMPWorksharingDirective(CurrDir) &&
6772 !isOpenMPParallelDirective(CurrDir)) {
6773 DVar = DSAStack->getImplicitDSA(VD, true);
6774 if (DVar.CKind != OMPC_shared) {
6775 Diag(ELoc, diag::err_omp_required_access)
6776 << getOpenMPClauseName(OMPC_reduction)
6777 << getOpenMPClauseName(OMPC_shared);
6778 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6779 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00006780 }
6781 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006782
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006783 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006784 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
6785 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6786 auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName(),
6787 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6788 auto PrivateTy = Type;
6789 if (OASE) {
6790 // For array sections only:
6791 // Create pseudo array type for private copy. The size for this array will
6792 // be generated during codegen.
6793 // For array subscripts or single variables Private Ty is the same as Type
6794 // (type of the variable or single array element).
6795 PrivateTy = Context.getVariableArrayType(
6796 Type, new (Context) OpaqueValueExpr(SourceLocation(),
6797 Context.getSizeType(), VK_RValue),
6798 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
6799 }
6800 // Private copy.
6801 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, VD->getName(),
6802 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006803 // Add initializer for private variable.
6804 Expr *Init = nullptr;
6805 switch (BOK) {
6806 case BO_Add:
6807 case BO_Xor:
6808 case BO_Or:
6809 case BO_LOr:
6810 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
6811 if (Type->isScalarType() || Type->isAnyComplexType()) {
6812 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00006813 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006814 break;
6815 case BO_Mul:
6816 case BO_LAnd:
6817 if (Type->isScalarType() || Type->isAnyComplexType()) {
6818 // '*' and '&&' reduction ops - initializer is '1'.
6819 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
6820 }
6821 break;
6822 case BO_And: {
6823 // '&' reduction op - initializer is '~0'.
6824 QualType OrigType = Type;
6825 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
6826 Type = ComplexTy->getElementType();
6827 }
6828 if (Type->isRealFloatingType()) {
6829 llvm::APFloat InitValue =
6830 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
6831 /*isIEEE=*/true);
6832 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
6833 Type, ELoc);
6834 } else if (Type->isScalarType()) {
6835 auto Size = Context.getTypeSize(Type);
6836 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
6837 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
6838 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
6839 }
6840 if (Init && OrigType->isAnyComplexType()) {
6841 // Init = 0xFFFF + 0xFFFFi;
6842 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
6843 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
6844 }
6845 Type = OrigType;
6846 break;
6847 }
6848 case BO_LT:
6849 case BO_GT: {
6850 // 'min' reduction op - initializer is 'Largest representable number in
6851 // the reduction list item type'.
6852 // 'max' reduction op - initializer is 'Least representable number in
6853 // the reduction list item type'.
6854 if (Type->isIntegerType() || Type->isPointerType()) {
6855 bool IsSigned = Type->hasSignedIntegerRepresentation();
6856 auto Size = Context.getTypeSize(Type);
6857 QualType IntTy =
6858 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
6859 llvm::APInt InitValue =
6860 (BOK != BO_LT)
6861 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
6862 : llvm::APInt::getMinValue(Size)
6863 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
6864 : llvm::APInt::getMaxValue(Size);
6865 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
6866 if (Type->isPointerType()) {
6867 // Cast to pointer type.
6868 auto CastExpr = BuildCStyleCastExpr(
6869 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
6870 SourceLocation(), Init);
6871 if (CastExpr.isInvalid())
6872 continue;
6873 Init = CastExpr.get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00006874 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006875 } else if (Type->isRealFloatingType()) {
6876 llvm::APFloat InitValue = llvm::APFloat::getLargest(
6877 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
6878 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
6879 Type, ELoc);
6880 }
6881 break;
6882 }
6883 case BO_PtrMemD:
6884 case BO_PtrMemI:
6885 case BO_MulAssign:
6886 case BO_Div:
6887 case BO_Rem:
6888 case BO_Sub:
6889 case BO_Shl:
6890 case BO_Shr:
6891 case BO_LE:
6892 case BO_GE:
6893 case BO_EQ:
6894 case BO_NE:
6895 case BO_AndAssign:
6896 case BO_XorAssign:
6897 case BO_OrAssign:
6898 case BO_Assign:
6899 case BO_AddAssign:
6900 case BO_SubAssign:
6901 case BO_DivAssign:
6902 case BO_RemAssign:
6903 case BO_ShlAssign:
6904 case BO_ShrAssign:
6905 case BO_Comma:
6906 llvm_unreachable("Unexpected reduction operation");
6907 }
6908 if (Init) {
6909 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
6910 /*TypeMayContainAuto=*/false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006911 } else
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006912 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006913 if (!RHSVD->hasInit()) {
6914 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
6915 << ReductionIdRange;
Alexey Bataeva1764212015-09-30 09:22:36 +00006916 if (VD) {
6917 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6918 VarDecl::DeclarationOnly;
6919 Diag(VD->getLocation(),
6920 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6921 << VD;
6922 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006923 continue;
6924 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006925 // Store initializer for single element in private copy. Will be used during
6926 // codegen.
6927 PrivateVD->setInit(RHSVD->getInit());
6928 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataev39f915b82015-05-08 10:41:21 +00006929 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
6930 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006931 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006932 ExprResult ReductionOp =
6933 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
6934 LHSDRE, RHSDRE);
6935 if (ReductionOp.isUsable()) {
Alexey Bataev69a47792015-05-07 03:54:03 +00006936 if (BOK != BO_LT && BOK != BO_GT) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006937 ReductionOp =
6938 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
6939 BO_Assign, LHSDRE, ReductionOp.get());
6940 } else {
6941 auto *ConditionalOp = new (Context) ConditionalOperator(
6942 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
6943 RHSDRE, Type, VK_LValue, OK_Ordinary);
6944 ReductionOp =
6945 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
6946 BO_Assign, LHSDRE, ConditionalOp);
6947 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006948 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00006949 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006950 if (ReductionOp.isInvalid())
6951 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006952
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006953 DSAStack->addDSA(VD, DE, OMPC_reduction);
Alexey Bataeva1764212015-09-30 09:22:36 +00006954 Vars.push_back(RefExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006955 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006956 LHSs.push_back(LHSDRE);
6957 RHSs.push_back(RHSDRE);
6958 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00006959 }
6960
6961 if (Vars.empty())
6962 return nullptr;
6963
6964 return OMPReductionClause::Create(
6965 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006966 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
6967 LHSs, RHSs, ReductionOps);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006968}
6969
Alexey Bataev182227b2015-08-20 10:54:39 +00006970OMPClause *Sema::ActOnOpenMPLinearClause(
6971 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
6972 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
6973 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00006974 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006975 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00006976 SmallVector<Expr *, 8> Inits;
Alexey Bataev182227b2015-08-20 10:54:39 +00006977 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
6978 LinKind == OMPC_LINEAR_unknown) {
6979 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
6980 LinKind = OMPC_LINEAR_val;
6981 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006982 for (auto &RefExpr : VarList) {
6983 assert(RefExpr && "NULL expr in OpenMP linear clause.");
6984 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00006985 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006986 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006987 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00006988 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00006989 continue;
6990 }
6991
6992 // OpenMP [2.14.3.7, linear clause]
6993 // A list item that appears in a linear clause is subject to the private
6994 // clause semantics described in Section 2.14.3.3 on page 159 except as
6995 // noted. In addition, the value of the new list item on each iteration
6996 // of the associated loop(s) corresponds to the value of the original
6997 // list item before entering the construct plus the logical number of
6998 // the iteration times linear-step.
6999
Alexey Bataeved09d242014-05-28 05:53:51 +00007000 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00007001 // OpenMP [2.1, C/C++]
7002 // A list item is a variable name.
7003 // OpenMP [2.14.3.3, Restrictions, p.1]
7004 // A variable that is part of another variable (as an array or
7005 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00007006 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00007007 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007008 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00007009 continue;
7010 }
7011
7012 VarDecl *VD = cast<VarDecl>(DE->getDecl());
7013
7014 // OpenMP [2.14.3.7, linear clause]
7015 // A list-item cannot appear in more than one linear clause.
7016 // A list-item that appears in a linear clause cannot appear in any
7017 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007018 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00007019 if (DVar.RefExpr) {
7020 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7021 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00007022 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00007023 continue;
7024 }
7025
7026 QualType QType = VD->getType();
7027 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
7028 // It will be analyzed later.
7029 Vars.push_back(DE);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007030 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00007031 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00007032 continue;
7033 }
7034
7035 // A variable must not have an incomplete type or a reference type.
7036 if (RequireCompleteType(ELoc, QType,
7037 diag::err_omp_linear_incomplete_type)) {
7038 continue;
7039 }
Alexey Bataev1185e192015-08-20 12:15:57 +00007040 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
7041 !QType->isReferenceType()) {
7042 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
7043 << QType << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
7044 continue;
7045 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007046 QType = QType.getNonReferenceType();
Alexander Musman8dba6642014-04-22 13:09:42 +00007047
7048 // A list item must not be const-qualified.
7049 if (QType.isConstant(Context)) {
7050 Diag(ELoc, diag::err_omp_const_variable)
7051 << getOpenMPClauseName(OMPC_linear);
7052 bool IsDecl =
7053 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7054 Diag(VD->getLocation(),
7055 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7056 << VD;
7057 continue;
7058 }
7059
7060 // A list item must be of integral or pointer type.
7061 QType = QType.getUnqualifiedType().getCanonicalType();
7062 const Type *Ty = QType.getTypePtrOrNull();
7063 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
7064 !Ty->isPointerType())) {
7065 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
7066 bool IsDecl =
7067 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7068 Diag(VD->getLocation(),
7069 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7070 << VD;
7071 continue;
7072 }
7073
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007074 // Build private copy of original var.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007075 auto *Private = buildVarDecl(*this, ELoc, QType, VD->getName(),
7076 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007077 auto *PrivateRef = buildDeclRefExpr(
7078 *this, Private, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexander Musman3276a272015-03-21 10:12:56 +00007079 // Build var to save initial value.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007080 VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00007081 Expr *InitExpr;
7082 if (LinKind == OMPC_LINEAR_uval)
7083 InitExpr = VD->getInit();
7084 else
7085 InitExpr = DE;
7086 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Alexander Musman3276a272015-03-21 10:12:56 +00007087 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007088 auto InitRef = buildDeclRefExpr(
7089 *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexander Musman8dba6642014-04-22 13:09:42 +00007090 DSAStack->addDSA(VD, DE, OMPC_linear);
7091 Vars.push_back(DE);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007092 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00007093 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00007094 }
7095
7096 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007097 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00007098
7099 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00007100 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00007101 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
7102 !Step->isInstantiationDependent() &&
7103 !Step->containsUnexpandedParameterPack()) {
7104 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007105 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00007106 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007107 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007108 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00007109
Alexander Musman3276a272015-03-21 10:12:56 +00007110 // Build var to save the step value.
7111 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00007112 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00007113 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00007114 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00007115 ExprResult CalcStep =
7116 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007117 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00007118
Alexander Musman8dba6642014-04-22 13:09:42 +00007119 // Warn about zero linear step (it would be probably better specified as
7120 // making corresponding variables 'const').
7121 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00007122 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
7123 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00007124 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
7125 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00007126 if (!IsConstant && CalcStep.isUsable()) {
7127 // Calculate the step beforehand instead of doing this on each iteration.
7128 // (This is not used if the number of iterations may be kfold-ed).
7129 CalcStepExpr = CalcStep.get();
7130 }
Alexander Musman8dba6642014-04-22 13:09:42 +00007131 }
7132
Alexey Bataev182227b2015-08-20 10:54:39 +00007133 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
7134 ColonLoc, EndLoc, Vars, Privates, Inits,
7135 StepExpr, CalcStepExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00007136}
7137
7138static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
7139 Expr *NumIterations, Sema &SemaRef,
7140 Scope *S) {
7141 // Walk the vars and build update/final expressions for the CodeGen.
7142 SmallVector<Expr *, 8> Updates;
7143 SmallVector<Expr *, 8> Finals;
7144 Expr *Step = Clause.getStep();
7145 Expr *CalcStep = Clause.getCalcStep();
7146 // OpenMP [2.14.3.7, linear clause]
7147 // If linear-step is not specified it is assumed to be 1.
7148 if (Step == nullptr)
7149 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7150 else if (CalcStep)
7151 Step = cast<BinaryOperator>(CalcStep)->getLHS();
7152 bool HasErrors = false;
7153 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007154 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00007155 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00007156 for (auto &RefExpr : Clause.varlists()) {
7157 Expr *InitExpr = *CurInit;
7158
7159 // Build privatized reference to the current linear var.
7160 auto DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00007161 Expr *CapturedRef;
7162 if (LinKind == OMPC_LINEAR_uval)
7163 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
7164 else
7165 CapturedRef =
7166 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
7167 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
7168 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00007169
7170 // Build update: Var = InitExpr + IV * Step
7171 ExprResult Update =
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007172 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexander Musman3276a272015-03-21 10:12:56 +00007173 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007174 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
7175 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00007176
7177 // Build final: Var = InitExpr + NumIterations * Step
7178 ExprResult Final =
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007179 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataev39f915b82015-05-08 10:41:21 +00007180 InitExpr, NumIterations, Step, /* Subtract */ false);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007181 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
7182 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00007183 if (!Update.isUsable() || !Final.isUsable()) {
7184 Updates.push_back(nullptr);
7185 Finals.push_back(nullptr);
7186 HasErrors = true;
7187 } else {
7188 Updates.push_back(Update.get());
7189 Finals.push_back(Final.get());
7190 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007191 ++CurInit, ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00007192 }
7193 Clause.setUpdates(Updates);
7194 Clause.setFinals(Finals);
7195 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00007196}
7197
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007198OMPClause *Sema::ActOnOpenMPAlignedClause(
7199 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
7200 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
7201
7202 SmallVector<Expr *, 8> Vars;
7203 for (auto &RefExpr : VarList) {
7204 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
7205 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7206 // It will be analyzed later.
7207 Vars.push_back(RefExpr);
7208 continue;
7209 }
7210
7211 SourceLocation ELoc = RefExpr->getExprLoc();
7212 // OpenMP [2.1, C/C++]
7213 // A list item is a variable name.
7214 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7215 if (!DE || !isa<VarDecl>(DE->getDecl())) {
7216 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7217 continue;
7218 }
7219
7220 VarDecl *VD = cast<VarDecl>(DE->getDecl());
7221
7222 // OpenMP [2.8.1, simd construct, Restrictions]
7223 // The type of list items appearing in the aligned clause must be
7224 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007225 QualType QType = VD->getType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007226 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007227 const Type *Ty = QType.getTypePtrOrNull();
7228 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
7229 !Ty->isPointerType())) {
7230 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
7231 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
7232 bool IsDecl =
7233 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7234 Diag(VD->getLocation(),
7235 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7236 << VD;
7237 continue;
7238 }
7239
7240 // OpenMP [2.8.1, simd construct, Restrictions]
7241 // A list-item cannot appear in more than one aligned clause.
7242 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
7243 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
7244 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
7245 << getOpenMPClauseName(OMPC_aligned);
7246 continue;
7247 }
7248
7249 Vars.push_back(DE);
7250 }
7251
7252 // OpenMP [2.8.1, simd construct, Description]
7253 // The parameter of the aligned clause, alignment, must be a constant
7254 // positive integer expression.
7255 // If no optional parameter is specified, implementation-defined default
7256 // alignments for SIMD instructions on the target platforms are assumed.
7257 if (Alignment != nullptr) {
7258 ExprResult AlignResult =
7259 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
7260 if (AlignResult.isInvalid())
7261 return nullptr;
7262 Alignment = AlignResult.get();
7263 }
7264 if (Vars.empty())
7265 return nullptr;
7266
7267 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
7268 EndLoc, Vars, Alignment);
7269}
7270
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007271OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
7272 SourceLocation StartLoc,
7273 SourceLocation LParenLoc,
7274 SourceLocation EndLoc) {
7275 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007276 SmallVector<Expr *, 8> SrcExprs;
7277 SmallVector<Expr *, 8> DstExprs;
7278 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00007279 for (auto &RefExpr : VarList) {
7280 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
7281 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007282 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007283 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007284 SrcExprs.push_back(nullptr);
7285 DstExprs.push_back(nullptr);
7286 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007287 continue;
7288 }
7289
Alexey Bataeved09d242014-05-28 05:53:51 +00007290 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007291 // OpenMP [2.1, C/C++]
7292 // A list item is a variable name.
7293 // OpenMP [2.14.4.1, Restrictions, p.1]
7294 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00007295 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007296 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007297 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007298 continue;
7299 }
7300
7301 Decl *D = DE->getDecl();
7302 VarDecl *VD = cast<VarDecl>(D);
7303
7304 QualType Type = VD->getType();
7305 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
7306 // It will be analyzed later.
7307 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007308 SrcExprs.push_back(nullptr);
7309 DstExprs.push_back(nullptr);
7310 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007311 continue;
7312 }
7313
7314 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
7315 // A list item that appears in a copyin clause must be threadprivate.
7316 if (!DSAStack->isThreadPrivate(VD)) {
7317 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00007318 << getOpenMPClauseName(OMPC_copyin)
7319 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007320 continue;
7321 }
7322
7323 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
7324 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00007325 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007326 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007327 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007328 auto *SrcVD =
7329 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
7330 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007331 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007332 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
7333 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007334 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
7335 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007336 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007337 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007338 // For arrays generate assignment operation for single element and replace
7339 // it by the original array element in CodeGen.
7340 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
7341 PseudoDstExpr, PseudoSrcExpr);
7342 if (AssignmentOp.isInvalid())
7343 continue;
7344 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
7345 /*DiscardedValue=*/true);
7346 if (AssignmentOp.isInvalid())
7347 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007348
7349 DSAStack->addDSA(VD, DE, OMPC_copyin);
7350 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007351 SrcExprs.push_back(PseudoSrcExpr);
7352 DstExprs.push_back(PseudoDstExpr);
7353 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007354 }
7355
Alexey Bataeved09d242014-05-28 05:53:51 +00007356 if (Vars.empty())
7357 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007358
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007359 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7360 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007361}
7362
Alexey Bataevbae9a792014-06-27 10:37:06 +00007363OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
7364 SourceLocation StartLoc,
7365 SourceLocation LParenLoc,
7366 SourceLocation EndLoc) {
7367 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00007368 SmallVector<Expr *, 8> SrcExprs;
7369 SmallVector<Expr *, 8> DstExprs;
7370 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007371 for (auto &RefExpr : VarList) {
7372 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
7373 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7374 // It will be analyzed later.
7375 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007376 SrcExprs.push_back(nullptr);
7377 DstExprs.push_back(nullptr);
7378 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007379 continue;
7380 }
7381
7382 SourceLocation ELoc = RefExpr->getExprLoc();
7383 // OpenMP [2.1, C/C++]
7384 // A list item is a variable name.
7385 // OpenMP [2.14.4.1, Restrictions, p.1]
7386 // A list item that appears in a copyin clause must be threadprivate.
7387 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7388 if (!DE || !isa<VarDecl>(DE->getDecl())) {
7389 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7390 continue;
7391 }
7392
7393 Decl *D = DE->getDecl();
7394 VarDecl *VD = cast<VarDecl>(D);
7395
7396 QualType Type = VD->getType();
7397 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
7398 // It will be analyzed later.
7399 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007400 SrcExprs.push_back(nullptr);
7401 DstExprs.push_back(nullptr);
7402 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007403 continue;
7404 }
7405
7406 // OpenMP [2.14.4.2, Restrictions, p.2]
7407 // A list item that appears in a copyprivate clause may not appear in a
7408 // private or firstprivate clause on the single construct.
7409 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007410 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007411 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
7412 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00007413 Diag(ELoc, diag::err_omp_wrong_dsa)
7414 << getOpenMPClauseName(DVar.CKind)
7415 << getOpenMPClauseName(OMPC_copyprivate);
7416 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7417 continue;
7418 }
7419
7420 // OpenMP [2.11.4.2, Restrictions, p.1]
7421 // All list items that appear in a copyprivate clause must be either
7422 // threadprivate or private in the enclosing context.
7423 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007424 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007425 if (DVar.CKind == OMPC_shared) {
7426 Diag(ELoc, diag::err_omp_required_access)
7427 << getOpenMPClauseName(OMPC_copyprivate)
7428 << "threadprivate or private in the enclosing context";
7429 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7430 continue;
7431 }
7432 }
7433 }
7434
Alexey Bataev7a3e5852015-05-19 08:19:24 +00007435 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007436 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00007437 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007438 << getOpenMPClauseName(OMPC_copyprivate) << Type
7439 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00007440 bool IsDecl =
7441 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7442 Diag(VD->getLocation(),
7443 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7444 << VD;
7445 continue;
7446 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007447
Alexey Bataevbae9a792014-06-27 10:37:06 +00007448 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
7449 // A variable of class type (or array thereof) that appears in a
7450 // copyin clause requires an accessible, unambiguous copy assignment
7451 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007452 Type = Context.getBaseElementType(Type.getNonReferenceType())
7453 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00007454 auto *SrcVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007455 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src",
7456 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev420d45b2015-04-14 05:11:24 +00007457 auto *PseudoSrcExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00007458 buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
Alexey Bataev420d45b2015-04-14 05:11:24 +00007459 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007460 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst",
7461 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev420d45b2015-04-14 05:11:24 +00007462 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00007463 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataeva63048e2015-03-23 06:18:07 +00007464 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
7465 PseudoDstExpr, PseudoSrcExpr);
7466 if (AssignmentOp.isInvalid())
7467 continue;
7468 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
7469 /*DiscardedValue=*/true);
7470 if (AssignmentOp.isInvalid())
7471 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007472
7473 // No need to mark vars as copyprivate, they are already threadprivate or
7474 // implicitly private.
7475 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007476 SrcExprs.push_back(PseudoSrcExpr);
7477 DstExprs.push_back(PseudoDstExpr);
7478 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00007479 }
7480
7481 if (Vars.empty())
7482 return nullptr;
7483
Alexey Bataeva63048e2015-03-23 06:18:07 +00007484 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
7485 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007486}
7487
Alexey Bataev6125da92014-07-21 11:26:11 +00007488OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
7489 SourceLocation StartLoc,
7490 SourceLocation LParenLoc,
7491 SourceLocation EndLoc) {
7492 if (VarList.empty())
7493 return nullptr;
7494
7495 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
7496}
Alexey Bataevdea47612014-07-23 07:46:59 +00007497
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007498OMPClause *
7499Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
7500 SourceLocation DepLoc, SourceLocation ColonLoc,
7501 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
7502 SourceLocation LParenLoc, SourceLocation EndLoc) {
7503 if (DepKind == OMPC_DEPEND_unknown) {
7504 std::string Values;
7505 std::string Sep(", ");
7506 for (unsigned i = 0; i < OMPC_DEPEND_unknown; ++i) {
7507 Values += "'";
7508 Values += getOpenMPSimpleClauseTypeName(OMPC_depend, i);
7509 Values += "'";
7510 switch (i) {
7511 case OMPC_DEPEND_unknown - 2:
7512 Values += " or ";
7513 break;
7514 case OMPC_DEPEND_unknown - 1:
7515 break;
7516 default:
7517 Values += Sep;
7518 break;
7519 }
7520 }
7521 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
7522 << Values << getOpenMPClauseName(OMPC_depend);
7523 return nullptr;
7524 }
7525 SmallVector<Expr *, 8> Vars;
7526 for (auto &RefExpr : VarList) {
7527 assert(RefExpr && "NULL expr in OpenMP shared clause.");
7528 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7529 // It will be analyzed later.
7530 Vars.push_back(RefExpr);
7531 continue;
7532 }
7533
7534 SourceLocation ELoc = RefExpr->getExprLoc();
7535 // OpenMP [2.11.1.1, Restrictions, p.3]
7536 // A variable that is part of another variable (such as a field of a
7537 // structure) but is not an array element or an array section cannot appear
7538 // in a depend clause.
7539 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007540 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
7541 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
7542 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
7543 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
7544 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007545 (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
7546 !ASE->getBase()->getType()->isArrayType())) {
7547 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
7548 << RefExpr->getSourceRange();
7549 continue;
7550 }
7551
7552 Vars.push_back(RefExpr->IgnoreParenImpCasts());
7553 }
7554
7555 if (Vars.empty())
7556 return nullptr;
7557
7558 return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind,
7559 DepLoc, ColonLoc, Vars);
7560}
Michael Wonge710d542015-08-07 16:16:36 +00007561
7562OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
7563 SourceLocation LParenLoc,
7564 SourceLocation EndLoc) {
7565 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +00007566
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007567 // OpenMP [2.9.1, Restrictions]
7568 // The device expression must evaluate to a non-negative integer value.
7569 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device))
7570 return nullptr;
7571
Michael Wonge710d542015-08-07 16:16:36 +00007572 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7573}
Kelvin Li0bff7af2015-11-23 05:32:03 +00007574
7575static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
7576 DSAStackTy *Stack, CXXRecordDecl *RD) {
7577 if (!RD || RD->isInvalidDecl())
7578 return true;
7579
7580 auto QTy = SemaRef.Context.getRecordType(RD);
7581 if (RD->isDynamicClass()) {
7582 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
7583 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
7584 return false;
7585 }
7586 auto *DC = RD;
7587 bool IsCorrect = true;
7588 for (auto *I : DC->decls()) {
7589 if (I) {
7590 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
7591 if (MD->isStatic()) {
7592 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
7593 SemaRef.Diag(MD->getLocation(),
7594 diag::note_omp_static_member_in_target);
7595 IsCorrect = false;
7596 }
7597 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
7598 if (VD->isStaticDataMember()) {
7599 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
7600 SemaRef.Diag(VD->getLocation(),
7601 diag::note_omp_static_member_in_target);
7602 IsCorrect = false;
7603 }
7604 }
7605 }
7606 }
7607
7608 for (auto &I : RD->bases()) {
7609 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
7610 I.getType()->getAsCXXRecordDecl()))
7611 IsCorrect = false;
7612 }
7613 return IsCorrect;
7614}
7615
7616static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
7617 DSAStackTy *Stack, QualType QTy) {
7618 NamedDecl *ND;
7619 if (QTy->isIncompleteType(&ND)) {
7620 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
7621 return false;
7622 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
7623 if (!RD->isInvalidDecl() &&
7624 !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
7625 return false;
7626 }
7627 return true;
7628}
7629
7630OMPClause *Sema::ActOnOpenMPMapClause(
7631 OpenMPMapClauseKind MapTypeModifier, OpenMPMapClauseKind MapType,
7632 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
7633 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
7634 SmallVector<Expr *, 4> Vars;
7635
7636 for (auto &RE : VarList) {
7637 assert(RE && "Null expr in omp map");
7638 if (isa<DependentScopeDeclRefExpr>(RE)) {
7639 // It will be analyzed later.
7640 Vars.push_back(RE);
7641 continue;
7642 }
7643 SourceLocation ELoc = RE->getExprLoc();
7644
7645 // OpenMP [2.14.5, Restrictions]
7646 // A variable that is part of another variable (such as field of a
7647 // structure) but is not an array element or an array section cannot appear
7648 // in a map clause.
7649 auto *VE = RE->IgnoreParenLValueCasts();
7650
7651 if (VE->isValueDependent() || VE->isTypeDependent() ||
7652 VE->isInstantiationDependent() ||
7653 VE->containsUnexpandedParameterPack()) {
7654 // It will be analyzed later.
7655 Vars.push_back(RE);
7656 continue;
7657 }
7658
7659 auto *SimpleExpr = RE->IgnoreParenCasts();
7660 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
7661 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
7662 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
7663
7664 if (!RE->IgnoreParenImpCasts()->isLValue() ||
7665 (!OASE && !ASE && !DE) ||
7666 (DE && !isa<VarDecl>(DE->getDecl())) ||
7667 (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
7668 !ASE->getBase()->getType()->isArrayType())) {
7669 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
7670 << RE->getSourceRange();
7671 continue;
7672 }
7673
7674 Decl *D = nullptr;
7675 if (DE) {
7676 D = DE->getDecl();
7677 } else if (ASE) {
7678 auto *B = ASE->getBase()->IgnoreParenCasts();
7679 D = dyn_cast<DeclRefExpr>(B)->getDecl();
7680 } else if (OASE) {
7681 auto *B = OASE->getBase();
7682 D = dyn_cast<DeclRefExpr>(B)->getDecl();
7683 }
7684 assert(D && "Null decl on map clause.");
7685 auto *VD = cast<VarDecl>(D);
7686
7687 // OpenMP [2.14.5, Restrictions, p.8]
7688 // threadprivate variables cannot appear in a map clause.
7689 if (DSAStack->isThreadPrivate(VD)) {
7690 auto DVar = DSAStack->getTopDSA(VD, false);
7691 Diag(ELoc, diag::err_omp_threadprivate_in_map);
7692 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7693 continue;
7694 }
7695
7696 // OpenMP [2.14.5, Restrictions, p.2]
7697 // At most one list item can be an array item derived from a given variable
7698 // in map clauses of the same construct.
7699 // OpenMP [2.14.5, Restrictions, p.3]
7700 // List items of map clauses in the same construct must not share original
7701 // storage.
7702 // OpenMP [2.14.5, Restrictions, C/C++, p.2]
7703 // A variable for which the type is pointer, reference to array, or
7704 // reference to pointer and an array section derived from that variable
7705 // must not appear as list items of map clauses of the same construct.
7706 DSAStackTy::MapInfo MI = DSAStack->IsMappedInCurrentRegion(VD);
7707 if (MI.RefExpr) {
7708 Diag(ELoc, diag::err_omp_map_shared_storage) << ELoc;
7709 Diag(MI.RefExpr->getExprLoc(), diag::note_used_here)
7710 << MI.RefExpr->getSourceRange();
7711 continue;
7712 }
7713
7714 // OpenMP [2.14.5, Restrictions, C/C++, p.3,4]
7715 // A variable for which the type is pointer, reference to array, or
7716 // reference to pointer must not appear as a list item if the enclosing
7717 // device data environment already contains an array section derived from
7718 // that variable.
7719 // An array section derived from a variable for which the type is pointer,
7720 // reference to array, or reference to pointer must not appear as a list
7721 // item if the enclosing device data environment already contains that
7722 // variable.
7723 QualType Type = VD->getType();
7724 MI = DSAStack->getMapInfoForVar(VD);
7725 if (MI.RefExpr && (isa<DeclRefExpr>(MI.RefExpr->IgnoreParenLValueCasts()) !=
7726 isa<DeclRefExpr>(VE)) &&
7727 (Type->isPointerType() || Type->isReferenceType())) {
7728 Diag(ELoc, diag::err_omp_map_shared_storage) << ELoc;
7729 Diag(MI.RefExpr->getExprLoc(), diag::note_used_here)
7730 << MI.RefExpr->getSourceRange();
7731 continue;
7732 }
7733
7734 // OpenMP [2.14.5, Restrictions, C/C++, p.7]
7735 // A list item must have a mappable type.
7736 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), *this,
7737 DSAStack, Type))
7738 continue;
7739
7740 Vars.push_back(RE);
7741 MI.RefExpr = RE;
7742 DSAStack->addMapInfoForVar(VD, MI);
7743 }
7744 if (Vars.empty())
7745 return nullptr;
7746
7747 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7748 MapTypeModifier, MapType, MapLoc);
7749}
Kelvin Li099bb8c2015-11-24 20:50:12 +00007750
7751OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
7752 SourceLocation StartLoc,
7753 SourceLocation LParenLoc,
7754 SourceLocation EndLoc) {
7755 Expr *ValExpr = NumTeams;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007756
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007757 // OpenMP [teams Constrcut, Restrictions]
7758 // The num_teams expression must evaluate to a positive integer value.
7759 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams))
7760 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007761
7762 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7763}
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007764
7765OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
7766 SourceLocation StartLoc,
7767 SourceLocation LParenLoc,
7768 SourceLocation EndLoc) {
7769 Expr *ValExpr = ThreadLimit;
7770
7771 // OpenMP [teams Constrcut, Restrictions]
7772 // The thread_limit expression must evaluate to a positive integer value.
7773 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit))
7774 return nullptr;
7775
7776 return new (Context) OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc,
7777 EndLoc);
7778}