blob: e6f3eb6c85aee9edb634a5ffe2dadbded3271e4a [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 Bataev13314bf2014-10-09 04:18:56 +0000346 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000347}
Alexey Bataeved09d242014-05-28 05:53:51 +0000348} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000349
350DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
351 VarDecl *D) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000352 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000353 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000354 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000355 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
356 // in a region but not in construct]
357 // File-scope or namespace-scope variables referenced in called routines
358 // in the region are shared unless they appear in a threadprivate
359 // directive.
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000360 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000361 DVar.CKind = OMPC_shared;
362
363 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
364 // in a region but not in construct]
365 // Variables with static storage duration that are declared in called
366 // routines in the region are shared.
367 if (D->hasGlobalStorage())
368 DVar.CKind = OMPC_shared;
369
Alexey Bataev758e55e2013-09-06 18:03:48 +0000370 return DVar;
371 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000372
Alexey Bataev758e55e2013-09-06 18:03:48 +0000373 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000374 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
375 // in a Construct, C/C++, predetermined, p.1]
376 // Variables with automatic storage duration that are declared in a scope
377 // inside the construct are private.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000378 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
379 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
380 DVar.CKind = OMPC_private;
381 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000382 }
383
Alexey Bataev758e55e2013-09-06 18:03:48 +0000384 // Explicitly specified attributes and local variables with predetermined
385 // attributes.
386 if (Iter->SharingMap.count(D)) {
387 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
388 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000389 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000390 return DVar;
391 }
392
393 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
394 // in a Construct, C/C++, implicitly determined, p.1]
395 // In a parallel or task construct, the data-sharing attributes of these
396 // variables are determined by the default clause, if present.
397 switch (Iter->DefaultAttr) {
398 case DSA_shared:
399 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000400 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000401 return DVar;
402 case DSA_none:
403 return DVar;
404 case DSA_unspecified:
405 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
406 // in a Construct, implicitly determined, p.2]
407 // In a parallel construct, if no default clause is present, these
408 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000409 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000410 if (isOpenMPParallelDirective(DVar.DKind) ||
411 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000412 DVar.CKind = OMPC_shared;
413 return DVar;
414 }
415
416 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
417 // in a Construct, implicitly determined, p.4]
418 // In a task construct, if no default clause is present, a variable that in
419 // the enclosing context is determined to be shared by all implicit tasks
420 // bound to the current team is shared.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000421 if (DVar.DKind == OMPD_task) {
422 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000423 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000424 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000425 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
426 // Referenced
Alexey Bataev758e55e2013-09-06 18:03:48 +0000427 // in a Construct, implicitly determined, p.6]
428 // In a task construct, if no default clause is present, a variable
429 // whose data-sharing attribute is not determined by the rules above is
430 // firstprivate.
431 DVarTemp = getDSA(I, D);
432 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000433 DVar.RefExpr = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000434 DVar.DKind = OMPD_task;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000435 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000436 return DVar;
437 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000438 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000439 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000440 }
441 DVar.DKind = OMPD_task;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000442 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000443 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000444 return DVar;
445 }
446 }
447 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
448 // in a Construct, implicitly determined, p.3]
449 // For constructs other than task, if no default clause is present, these
450 // variables inherit their data-sharing attributes from the enclosing
451 // context.
Benjamin Kramer167e9992014-03-02 12:20:24 +0000452 return getDSA(std::next(Iter), D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000453}
454
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000455DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
456 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000457 D = D->getCanonicalDecl();
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000458 auto It = Stack.back().AlignedMap.find(D);
459 if (It == Stack.back().AlignedMap.end()) {
460 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
461 Stack.back().AlignedMap[D] = NewDE;
462 return nullptr;
463 } else {
464 assert(It->second && "Unexpected nullptr expr in the aligned map");
465 return It->second;
466 }
467 return nullptr;
468}
469
Alexey Bataev9c821032015-04-30 04:23:23 +0000470void DSAStackTy::addLoopControlVariable(VarDecl *D) {
471 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
472 D = D->getCanonicalDecl();
473 Stack.back().LCVSet.insert(D);
474}
475
476bool DSAStackTy::isLoopControlVariable(VarDecl *D) {
477 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
478 D = D->getCanonicalDecl();
479 return Stack.back().LCVSet.count(D) > 0;
480}
481
Alexey Bataev758e55e2013-09-06 18:03:48 +0000482void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000483 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000484 if (A == OMPC_threadprivate) {
485 Stack[0].SharingMap[D].Attributes = A;
486 Stack[0].SharingMap[D].RefExpr = E;
487 } else {
488 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
489 Stack.back().SharingMap[D].Attributes = A;
490 Stack.back().SharingMap[D].RefExpr = E;
491 }
492}
493
Alexey Bataeved09d242014-05-28 05:53:51 +0000494bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000495 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000496 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000497 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000498 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000499 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000500 ++I;
501 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000502 if (I == E)
503 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000504 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000505 Scope *CurScope = getCurScope();
506 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000507 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000508 }
509 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000510 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000511 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000512}
513
Alexey Bataev39f915b82015-05-08 10:41:21 +0000514/// \brief Build a variable declaration for OpenMP loop iteration variable.
515static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000516 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000517 DeclContext *DC = SemaRef.CurContext;
518 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
519 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
520 VarDecl *Decl =
521 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000522 if (Attrs) {
523 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
524 I != E; ++I)
525 Decl->addAttr(*I);
526 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000527 Decl->setImplicit();
528 return Decl;
529}
530
531static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
532 SourceLocation Loc,
533 bool RefersToCapture = false) {
534 D->setReferenced();
535 D->markUsed(S.Context);
536 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
537 SourceLocation(), D, RefersToCapture, Loc, Ty,
538 VK_LValue);
539}
540
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000541DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000542 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000543 DSAVarData DVar;
544
545 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
546 // in a Construct, C/C++, predetermined, p.1]
547 // Variables appearing in threadprivate directives are threadprivate.
Samuel Antaof8b50122015-07-13 22:54:53 +0000548 if ((D->getTLSKind() != VarDecl::TLS_None &&
549 !(D->hasAttr<OMPThreadPrivateDeclAttr>() &&
550 SemaRef.getLangOpts().OpenMPUseTLS &&
551 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +0000552 (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() &&
553 !D->isLocalVarDecl())) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000554 addDSA(D, buildDeclRefExpr(SemaRef, D, D->getType().getNonReferenceType(),
555 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000556 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000557 }
558 if (Stack[0].SharingMap.count(D)) {
559 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
560 DVar.CKind = OMPC_threadprivate;
561 return DVar;
562 }
563
564 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
565 // in a Construct, C/C++, predetermined, p.1]
566 // Variables with automatic storage duration that are declared in a scope
567 // inside the construct are private.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000568 OpenMPDirectiveKind Kind =
569 FromParent ? getParentDirective() : getCurrentDirective();
570 auto StartI = std::next(Stack.rbegin());
571 auto EndI = std::prev(Stack.rend());
572 if (FromParent && StartI != EndI) {
573 StartI = std::next(StartI);
574 }
575 if (!isParallelOrTaskRegion(Kind)) {
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000576 if (isOpenMPLocal(D, StartI) &&
577 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
578 D->getStorageClass() == SC_None)) ||
579 isa<ParmVarDecl>(D))) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000580 DVar.CKind = OMPC_private;
581 return DVar;
Alexander Musman8dba6642014-04-22 13:09:42 +0000582 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000583
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000584 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
585 // in a Construct, C/C++, predetermined, p.4]
586 // Static data members are shared.
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000587 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
588 // in a Construct, C/C++, predetermined, p.7]
589 // Variables with static storage duration that are declared in a scope
590 // inside the construct are shared.
Kelvin Li4eea8c62015-09-15 18:56:58 +0000591 if (D->isStaticDataMember()) {
Alexey Bataev42971a32015-01-20 07:03:46 +0000592 DSAVarData DVarTemp =
593 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
594 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
595 return DVar;
596
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000597 DVar.CKind = OMPC_shared;
598 return DVar;
599 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000600 }
601
602 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000603 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
604 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000605 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
606 // in a Construct, C/C++, predetermined, p.6]
607 // Variables with const qualified type having no mutable member are
608 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000609 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000610 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000611 if (IsConstant &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000612 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000613 // Variables with const-qualified type having no mutable member may be
614 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000615 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
616 MatchesAlways(), FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000617 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
618 return DVar;
619
Alexey Bataev758e55e2013-09-06 18:03:48 +0000620 DVar.CKind = OMPC_shared;
621 return DVar;
622 }
623
Alexey Bataev758e55e2013-09-06 18:03:48 +0000624 // Explicitly specified attributes and local variables with predetermined
625 // attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000626 auto I = std::prev(StartI);
627 if (I->SharingMap.count(D)) {
628 DVar.RefExpr = I->SharingMap[D].RefExpr;
629 DVar.CKind = I->SharingMap[D].Attributes;
630 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000631 }
632
633 return DVar;
634}
635
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000636DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000637 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000638 auto StartI = Stack.rbegin();
639 auto EndI = std::prev(Stack.rend());
640 if (FromParent && StartI != EndI) {
641 StartI = std::next(StartI);
642 }
643 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000644}
645
Alexey Bataevf29276e2014-06-18 04:14:57 +0000646template <class ClausesPredicate, class DirectivesPredicate>
647DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000648 DirectivesPredicate DPred,
649 bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000650 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000651 auto StartI = std::next(Stack.rbegin());
652 auto EndI = std::prev(Stack.rend());
653 if (FromParent && StartI != EndI) {
654 StartI = std::next(StartI);
655 }
656 for (auto I = StartI, EE = EndI; I != EE; ++I) {
657 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000658 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000659 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000660 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000661 return DVar;
662 }
663 return DSAVarData();
664}
665
Alexey Bataevf29276e2014-06-18 04:14:57 +0000666template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000667DSAStackTy::DSAVarData
668DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
669 DirectivesPredicate DPred, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000670 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000671 auto StartI = std::next(Stack.rbegin());
672 auto EndI = std::prev(Stack.rend());
673 if (FromParent && StartI != EndI) {
674 StartI = std::next(StartI);
675 }
676 for (auto I = StartI, EE = EndI; I != EE; ++I) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000677 if (!DPred(I->Directive))
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000678 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +0000679 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000680 if (CPred(DVar.CKind))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000681 return DVar;
682 return DSAVarData();
683 }
684 return DSAVarData();
685}
686
Alexey Bataevaac108a2015-06-23 04:51:00 +0000687bool DSAStackTy::hasExplicitDSA(
688 VarDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
689 unsigned Level) {
690 if (CPred(ClauseKindMode))
691 return true;
692 if (isClauseParsingMode())
693 ++Level;
694 D = D->getCanonicalDecl();
695 auto StartI = Stack.rbegin();
696 auto EndI = std::prev(Stack.rend());
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000697 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000698 return false;
699 std::advance(StartI, Level);
700 return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr &&
701 CPred(StartI->SharingMap[D].Attributes);
702}
703
Samuel Antao4be30e92015-10-02 17:14:03 +0000704bool DSAStackTy::hasExplicitDirective(
705 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
706 unsigned Level) {
707 if (isClauseParsingMode())
708 ++Level;
709 auto StartI = Stack.rbegin();
710 auto EndI = std::prev(Stack.rend());
711 if (std::distance(StartI, EndI) <= (int)Level)
712 return false;
713 std::advance(StartI, Level);
714 return DPred(StartI->Directive);
715}
716
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000717template <class NamedDirectivesPredicate>
718bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
719 auto StartI = std::next(Stack.rbegin());
720 auto EndI = std::prev(Stack.rend());
721 if (FromParent && StartI != EndI) {
722 StartI = std::next(StartI);
723 }
724 for (auto I = StartI, EE = EndI; I != EE; ++I) {
725 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
726 return true;
727 }
728 return false;
729}
730
Alexey Bataev758e55e2013-09-06 18:03:48 +0000731void Sema::InitDataSharingAttributesStack() {
732 VarDataSharingAttributesStack = new DSAStackTy(*this);
733}
734
735#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
736
Alexey Bataevf841bd92014-12-16 07:00:22 +0000737bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
738 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000739 VD = VD->getCanonicalDecl();
Samuel Antao4be30e92015-10-02 17:14:03 +0000740
741 // If we are attempting to capture a global variable in a directive with
742 // 'target' we return true so that this global is also mapped to the device.
743 //
744 // FIXME: If the declaration is enclosed in a 'declare target' directive,
745 // then it should not be captured. Therefore, an extra check has to be
746 // inserted here once support for 'declare target' is added.
747 //
748 if (!VD->hasLocalStorage()) {
749 if (DSAStack->getCurrentDirective() == OMPD_target &&
750 !DSAStack->isClauseParsingMode()) {
751 return true;
752 }
753 if (DSAStack->getCurScope() &&
754 DSAStack->hasDirective(
755 [](OpenMPDirectiveKind K, const DeclarationNameInfo &DNI,
756 SourceLocation Loc) -> bool {
757 return isOpenMPTargetDirective(K);
758 },
759 false)) {
760 return true;
761 }
762 }
763
Alexey Bataev48977c32015-08-04 08:10:48 +0000764 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
765 (!DSAStack->isClauseParsingMode() ||
766 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000767 if (DSAStack->isLoopControlVariable(VD) ||
768 (VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000769 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
770 DSAStack->isForceVarCapturing())
Alexey Bataev9c821032015-04-30 04:23:23 +0000771 return true;
Alexey Bataevaac108a2015-06-23 04:51:00 +0000772 auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000773 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
774 return true;
775 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
Alexey Bataevaac108a2015-06-23 04:51:00 +0000776 DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000777 return DVarPrivate.CKind != OMPC_unknown;
778 }
779 return false;
780}
781
Alexey Bataevaac108a2015-06-23 04:51:00 +0000782bool Sema::isOpenMPPrivateVar(VarDecl *VD, unsigned Level) {
783 assert(LangOpts.OpenMP && "OpenMP is not allowed");
784 return DSAStack->hasExplicitDSA(
785 VD, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
786}
787
Samuel Antao4be30e92015-10-02 17:14:03 +0000788bool Sema::isOpenMPTargetCapturedVar(VarDecl *VD, unsigned Level) {
789 assert(LangOpts.OpenMP && "OpenMP is not allowed");
790 // Return true if the current level is no longer enclosed in a target region.
791
792 return !VD->hasLocalStorage() &&
793 DSAStack->hasExplicitDirective(isOpenMPTargetDirective, Level);
794}
795
Alexey Bataeved09d242014-05-28 05:53:51 +0000796void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000797
798void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
799 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000800 Scope *CurScope, SourceLocation Loc) {
801 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000802 PushExpressionEvaluationContext(PotentiallyEvaluated);
803}
804
Alexey Bataevaac108a2015-06-23 04:51:00 +0000805void Sema::StartOpenMPClause(OpenMPClauseKind K) {
806 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000807}
808
Alexey Bataevaac108a2015-06-23 04:51:00 +0000809void Sema::EndOpenMPClause() {
810 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000811}
812
Alexey Bataev758e55e2013-09-06 18:03:48 +0000813void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000814 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
815 // A variable of class type (or array thereof) that appears in a lastprivate
816 // clause requires an accessible, unambiguous default constructor for the
817 // class type, unless the list item is also specified in a firstprivate
818 // clause.
819 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000820 for (auto *C : D->clauses()) {
821 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
822 SmallVector<Expr *, 8> PrivateCopies;
823 for (auto *DE : Clause->varlists()) {
824 if (DE->isValueDependent() || DE->isTypeDependent()) {
825 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000826 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +0000827 }
828 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000829 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000830 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000831 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000832 // Generate helper private variable and initialize it with the
833 // default value. The address of the original variable is replaced
834 // by the address of the new private variable in CodeGen. This new
835 // variable is not added to IdResolver, so the code in the OpenMP
836 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000837 auto *VDPrivate = buildVarDecl(
838 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
839 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +0000840 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
841 if (VDPrivate->isInvalidDecl())
842 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000843 PrivateCopies.push_back(buildDeclRefExpr(
844 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +0000845 } else {
846 // The variable is also a firstprivate, so initialization sequence
847 // for private copy is generated already.
848 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000849 }
850 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000851 // Set initializers to private copies if no errors were found.
852 if (PrivateCopies.size() == Clause->varlist_size()) {
853 Clause->setPrivateCopies(PrivateCopies);
854 }
Alexey Bataevf29276e2014-06-18 04:14:57 +0000855 }
856 }
857 }
858
Alexey Bataev758e55e2013-09-06 18:03:48 +0000859 DSAStack->pop();
860 DiscardCleanupsInEvaluationContext();
861 PopExpressionEvaluationContext();
862}
863
Alexander Musman3276a272015-03-21 10:12:56 +0000864static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
865 Expr *NumIterations, Sema &SemaRef,
866 Scope *S);
867
Alexey Bataeva769e072013-03-22 06:34:35 +0000868namespace {
869
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000870class VarDeclFilterCCC : public CorrectionCandidateCallback {
871private:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000872 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +0000873
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000874public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000875 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +0000876 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000877 NamedDecl *ND = Candidate.getCorrectionDecl();
878 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
879 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000880 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
881 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +0000882 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000883 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +0000884 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000885};
Alexey Bataeved09d242014-05-28 05:53:51 +0000886} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000887
888ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
889 CXXScopeSpec &ScopeSpec,
890 const DeclarationNameInfo &Id) {
891 LookupResult Lookup(*this, Id, LookupOrdinaryName);
892 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
893
894 if (Lookup.isAmbiguous())
895 return ExprError();
896
897 VarDecl *VD;
898 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000899 if (TypoCorrection Corrected = CorrectTypo(
900 Id, LookupOrdinaryName, CurScope, nullptr,
901 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000902 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000903 PDiag(Lookup.empty()
904 ? diag::err_undeclared_var_use_suggest
905 : diag::err_omp_expected_var_arg_suggest)
906 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +0000907 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000908 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000909 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
910 : diag::err_omp_expected_var_arg)
911 << Id.getName();
912 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000913 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000914 } else {
915 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000916 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000917 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
918 return ExprError();
919 }
920 }
921 Lookup.suppressDiagnostics();
922
923 // OpenMP [2.9.2, Syntax, C/C++]
924 // Variables must be file-scope, namespace-scope, or static block-scope.
925 if (!VD->hasGlobalStorage()) {
926 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000927 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
928 bool IsDecl =
929 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000930 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +0000931 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
932 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000933 return ExprError();
934 }
935
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000936 VarDecl *CanonicalVD = VD->getCanonicalDecl();
937 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000938 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
939 // A threadprivate directive for file-scope variables must appear outside
940 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000941 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
942 !getCurLexicalContext()->isTranslationUnit()) {
943 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000944 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
945 bool IsDecl =
946 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
947 Diag(VD->getLocation(),
948 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
949 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000950 return ExprError();
951 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000952 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
953 // A threadprivate directive for static class member variables must appear
954 // in the class definition, in the same scope in which the member
955 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000956 if (CanonicalVD->isStaticDataMember() &&
957 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
958 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000959 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
960 bool IsDecl =
961 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
962 Diag(VD->getLocation(),
963 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
964 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000965 return ExprError();
966 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000967 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
968 // A threadprivate directive for namespace-scope variables must appear
969 // outside any definition or declaration other than the namespace
970 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000971 if (CanonicalVD->getDeclContext()->isNamespace() &&
972 (!getCurLexicalContext()->isFileContext() ||
973 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
974 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000975 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
976 bool IsDecl =
977 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
978 Diag(VD->getLocation(),
979 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
980 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000981 return ExprError();
982 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000983 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
984 // A threadprivate directive for static block-scope variables must appear
985 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000986 if (CanonicalVD->isStaticLocal() && CurScope &&
987 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000988 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000989 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
990 bool IsDecl =
991 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
992 Diag(VD->getLocation(),
993 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
994 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000995 return ExprError();
996 }
997
998 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
999 // A threadprivate directive must lexically precede all references to any
1000 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001001 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001002 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001003 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001004 return ExprError();
1005 }
1006
1007 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00001008 ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001009 return DE;
1010}
1011
Alexey Bataeved09d242014-05-28 05:53:51 +00001012Sema::DeclGroupPtrTy
1013Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1014 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001015 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001016 CurContext->addDecl(D);
1017 return DeclGroupPtrTy::make(DeclGroupRef(D));
1018 }
1019 return DeclGroupPtrTy();
1020}
1021
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001022namespace {
1023class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1024 Sema &SemaRef;
1025
1026public:
1027 bool VisitDeclRefExpr(const DeclRefExpr *E) {
1028 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
1029 if (VD->hasLocalStorage()) {
1030 SemaRef.Diag(E->getLocStart(),
1031 diag::err_omp_local_var_in_threadprivate_init)
1032 << E->getSourceRange();
1033 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1034 << VD << VD->getSourceRange();
1035 return true;
1036 }
1037 }
1038 return false;
1039 }
1040 bool VisitStmt(const Stmt *S) {
1041 for (auto Child : S->children()) {
1042 if (Child && Visit(Child))
1043 return true;
1044 }
1045 return false;
1046 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001047 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001048};
1049} // namespace
1050
Alexey Bataeved09d242014-05-28 05:53:51 +00001051OMPThreadPrivateDecl *
1052Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001053 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001054 for (auto &RefExpr : VarList) {
1055 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001056 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1057 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001058
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001059 QualType QType = VD->getType();
1060 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1061 // It will be analyzed later.
1062 Vars.push_back(DE);
1063 continue;
1064 }
1065
Alexey Bataeva769e072013-03-22 06:34:35 +00001066 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1067 // A threadprivate variable must not have an incomplete type.
1068 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001069 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001070 continue;
1071 }
1072
1073 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1074 // A threadprivate variable must not have a reference type.
1075 if (VD->getType()->isReferenceType()) {
1076 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001077 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1078 bool IsDecl =
1079 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1080 Diag(VD->getLocation(),
1081 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1082 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001083 continue;
1084 }
1085
Samuel Antaof8b50122015-07-13 22:54:53 +00001086 // Check if this is a TLS variable. If TLS is not being supported, produce
1087 // the corresponding diagnostic.
1088 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1089 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1090 getLangOpts().OpenMPUseTLS &&
1091 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001092 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1093 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001094 Diag(ILoc, diag::err_omp_var_thread_local)
1095 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001096 bool IsDecl =
1097 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1098 Diag(VD->getLocation(),
1099 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1100 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001101 continue;
1102 }
1103
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001104 // Check if initial value of threadprivate variable reference variable with
1105 // local storage (it is not supported by runtime).
1106 if (auto Init = VD->getAnyInitializer()) {
1107 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001108 if (Checker.Visit(Init))
1109 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001110 }
1111
Alexey Bataeved09d242014-05-28 05:53:51 +00001112 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001113 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001114 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1115 Context, SourceRange(Loc, Loc)));
1116 if (auto *ML = Context.getASTMutationListener())
1117 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001118 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001119 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001120 if (!Vars.empty()) {
1121 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1122 Vars);
1123 D->setAccess(AS_public);
1124 }
1125 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001126}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001127
Alexey Bataev7ff55242014-06-19 09:13:45 +00001128static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1129 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
1130 bool IsLoopIterVar = false) {
1131 if (DVar.RefExpr) {
1132 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1133 << getOpenMPClauseName(DVar.CKind);
1134 return;
1135 }
1136 enum {
1137 PDSA_StaticMemberShared,
1138 PDSA_StaticLocalVarShared,
1139 PDSA_LoopIterVarPrivate,
1140 PDSA_LoopIterVarLinear,
1141 PDSA_LoopIterVarLastprivate,
1142 PDSA_ConstVarShared,
1143 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001144 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001145 PDSA_LocalVarPrivate,
1146 PDSA_Implicit
1147 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001148 bool ReportHint = false;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001149 auto ReportLoc = VD->getLocation();
Alexey Bataev7ff55242014-06-19 09:13:45 +00001150 if (IsLoopIterVar) {
1151 if (DVar.CKind == OMPC_private)
1152 Reason = PDSA_LoopIterVarPrivate;
1153 else if (DVar.CKind == OMPC_lastprivate)
1154 Reason = PDSA_LoopIterVarLastprivate;
1155 else
1156 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001157 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
1158 Reason = PDSA_TaskVarFirstprivate;
1159 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001160 } else if (VD->isStaticLocal())
1161 Reason = PDSA_StaticLocalVarShared;
1162 else if (VD->isStaticDataMember())
1163 Reason = PDSA_StaticMemberShared;
1164 else if (VD->isFileVarDecl())
1165 Reason = PDSA_GlobalVarShared;
1166 else if (VD->getType().isConstant(SemaRef.getASTContext()))
1167 Reason = PDSA_ConstVarShared;
Alexey Bataevbae9a792014-06-27 10:37:06 +00001168 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001169 ReportHint = true;
1170 Reason = PDSA_LocalVarPrivate;
1171 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001172 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001173 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001174 << Reason << ReportHint
1175 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1176 } else if (DVar.ImplicitDSALoc.isValid()) {
1177 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1178 << getOpenMPClauseName(DVar.CKind);
1179 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001180}
1181
Alexey Bataev758e55e2013-09-06 18:03:48 +00001182namespace {
1183class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1184 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001185 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001186 bool ErrorFound;
1187 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001188 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001189 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001190
Alexey Bataev758e55e2013-09-06 18:03:48 +00001191public:
1192 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001193 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001194 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001195 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1196 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001197
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001198 auto DVar = Stack->getTopDSA(VD, false);
1199 // Check if the variable has explicit DSA set and stop analysis if it so.
1200 if (DVar.RefExpr) return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001201
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001202 auto ELoc = E->getExprLoc();
1203 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001204 // The default(none) clause requires that each variable that is referenced
1205 // in the construct, and does not have a predetermined data-sharing
1206 // attribute, must have its data-sharing attribute explicitly determined
1207 // by being listed in a data-sharing attribute clause.
1208 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001209 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001210 VarsWithInheritedDSA.count(VD) == 0) {
1211 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001212 return;
1213 }
1214
1215 // OpenMP [2.9.3.6, Restrictions, p.2]
1216 // A list item that appears in a reduction clause of the innermost
1217 // enclosing worksharing or parallel construct may not be accessed in an
1218 // explicit task.
Alexey Bataevf29276e2014-06-18 04:14:57 +00001219 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001220 [](OpenMPDirectiveKind K) -> bool {
1221 return isOpenMPParallelDirective(K) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001222 isOpenMPWorksharingDirective(K) ||
1223 isOpenMPTeamsDirective(K);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001224 },
1225 false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001226 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1227 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001228 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1229 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001230 return;
1231 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001232
1233 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001234 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001235 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001236 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001237 }
1238 }
1239 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001240 for (auto *C : S->clauses()) {
1241 // Skip analysis of arguments of implicitly defined firstprivate clause
1242 // for task directives.
1243 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1244 for (auto *CC : C->children()) {
1245 if (CC)
1246 Visit(CC);
1247 }
1248 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001249 }
1250 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001251 for (auto *C : S->children()) {
1252 if (C && !isa<OMPExecutableDirective>(C))
1253 Visit(C);
1254 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001255 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001256
1257 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001258 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001259 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1260 return VarsWithInheritedDSA;
1261 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001262
Alexey Bataev7ff55242014-06-19 09:13:45 +00001263 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1264 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001265};
Alexey Bataeved09d242014-05-28 05:53:51 +00001266} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001267
Alexey Bataevbae9a792014-06-27 10:37:06 +00001268void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001269 switch (DKind) {
1270 case OMPD_parallel: {
1271 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001272 QualType KmpInt32PtrTy =
1273 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001274 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001275 std::make_pair(".global_tid.", KmpInt32PtrTy),
1276 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1277 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001278 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001279 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1280 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001281 break;
1282 }
1283 case OMPD_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001284 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001285 std::make_pair(StringRef(), QualType()) // __context with shared vars
1286 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001287 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1288 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001289 break;
1290 }
1291 case OMPD_for: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001292 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001293 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001294 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001295 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1296 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001297 break;
1298 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001299 case OMPD_for_simd: {
1300 Sema::CapturedParamNameType Params[] = {
1301 std::make_pair(StringRef(), QualType()) // __context with shared vars
1302 };
1303 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1304 Params);
1305 break;
1306 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001307 case OMPD_sections: {
1308 Sema::CapturedParamNameType Params[] = {
1309 std::make_pair(StringRef(), QualType()) // __context with shared vars
1310 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001311 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1312 Params);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001313 break;
1314 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001315 case OMPD_section: {
1316 Sema::CapturedParamNameType Params[] = {
1317 std::make_pair(StringRef(), QualType()) // __context with shared vars
1318 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001319 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1320 Params);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001321 break;
1322 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001323 case OMPD_single: {
1324 Sema::CapturedParamNameType Params[] = {
1325 std::make_pair(StringRef(), QualType()) // __context with shared vars
1326 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001327 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1328 Params);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001329 break;
1330 }
Alexander Musman80c22892014-07-17 08:54:58 +00001331 case OMPD_master: {
1332 Sema::CapturedParamNameType Params[] = {
1333 std::make_pair(StringRef(), QualType()) // __context with shared vars
1334 };
1335 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1336 Params);
1337 break;
1338 }
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001339 case OMPD_critical: {
1340 Sema::CapturedParamNameType Params[] = {
1341 std::make_pair(StringRef(), QualType()) // __context with shared vars
1342 };
1343 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1344 Params);
1345 break;
1346 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001347 case OMPD_parallel_for: {
1348 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001349 QualType KmpInt32PtrTy =
1350 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataev4acb8592014-07-07 13:01:15 +00001351 Sema::CapturedParamNameType Params[] = {
1352 std::make_pair(".global_tid.", KmpInt32PtrTy),
1353 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1354 std::make_pair(StringRef(), QualType()) // __context with shared vars
1355 };
1356 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1357 Params);
1358 break;
1359 }
Alexander Musmane4e893b2014-09-23 09:33:00 +00001360 case OMPD_parallel_for_simd: {
1361 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001362 QualType KmpInt32PtrTy =
1363 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexander Musmane4e893b2014-09-23 09:33:00 +00001364 Sema::CapturedParamNameType Params[] = {
1365 std::make_pair(".global_tid.", KmpInt32PtrTy),
1366 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1367 std::make_pair(StringRef(), QualType()) // __context with shared vars
1368 };
1369 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1370 Params);
1371 break;
1372 }
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001373 case OMPD_parallel_sections: {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001374 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001375 QualType KmpInt32PtrTy =
1376 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001377 Sema::CapturedParamNameType Params[] = {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001378 std::make_pair(".global_tid.", KmpInt32PtrTy),
1379 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001380 std::make_pair(StringRef(), QualType()) // __context with shared vars
1381 };
1382 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1383 Params);
1384 break;
1385 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001386 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001387 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001388 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1389 FunctionProtoType::ExtProtoInfo EPI;
1390 EPI.Variadic = true;
1391 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001392 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001393 std::make_pair(".global_tid.", KmpInt32Ty),
1394 std::make_pair(".part_id.", KmpInt32Ty),
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001395 std::make_pair(".privates.",
1396 Context.VoidPtrTy.withConst().withRestrict()),
1397 std::make_pair(
1398 ".copy_fn.",
1399 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001400 std::make_pair(StringRef(), QualType()) // __context with shared vars
1401 };
1402 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1403 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001404 // Mark this captured region as inlined, because we don't use outlined
1405 // function directly.
1406 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1407 AlwaysInlineAttr::CreateImplicit(
1408 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001409 break;
1410 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001411 case OMPD_ordered: {
1412 Sema::CapturedParamNameType Params[] = {
1413 std::make_pair(StringRef(), QualType()) // __context with shared vars
1414 };
1415 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1416 Params);
1417 break;
1418 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001419 case OMPD_atomic: {
1420 Sema::CapturedParamNameType Params[] = {
1421 std::make_pair(StringRef(), QualType()) // __context with shared vars
1422 };
1423 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1424 Params);
1425 break;
1426 }
Michael Wong65f367f2015-07-21 13:44:28 +00001427 case OMPD_target_data:
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001428 case OMPD_target: {
1429 Sema::CapturedParamNameType Params[] = {
1430 std::make_pair(StringRef(), QualType()) // __context with shared vars
1431 };
1432 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1433 Params);
1434 break;
1435 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001436 case OMPD_teams: {
1437 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001438 QualType KmpInt32PtrTy =
1439 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataev13314bf2014-10-09 04:18:56 +00001440 Sema::CapturedParamNameType Params[] = {
1441 std::make_pair(".global_tid.", KmpInt32PtrTy),
1442 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1443 std::make_pair(StringRef(), QualType()) // __context with shared vars
1444 };
1445 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1446 Params);
1447 break;
1448 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001449 case OMPD_taskgroup: {
1450 Sema::CapturedParamNameType Params[] = {
1451 std::make_pair(StringRef(), QualType()) // __context with shared vars
1452 };
1453 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1454 Params);
1455 break;
1456 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001457 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001458 case OMPD_taskyield:
1459 case OMPD_barrier:
1460 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001461 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001462 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001463 case OMPD_flush:
Alexey Bataev9959db52014-05-06 10:08:46 +00001464 llvm_unreachable("OpenMP Directive is not allowed");
1465 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001466 llvm_unreachable("Unknown OpenMP directive");
1467 }
1468}
1469
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001470StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1471 ArrayRef<OMPClause *> Clauses) {
1472 if (!S.isUsable()) {
1473 ActOnCapturedRegionError();
1474 return StmtError();
1475 }
Alexey Bataev040d5402015-05-12 08:35:28 +00001476 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001477 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001478 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001479 Clause->getClauseKind() == OMPC_copyprivate ||
1480 (getLangOpts().OpenMPUseTLS &&
1481 getASTContext().getTargetInfo().isTLSSupported() &&
1482 Clause->getClauseKind() == OMPC_copyin)) {
1483 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001484 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001485 for (auto *VarRef : Clause->children()) {
1486 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001487 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001488 }
1489 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001490 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev040d5402015-05-12 08:35:28 +00001491 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
1492 Clause->getClauseKind() == OMPC_schedule) {
1493 // Mark all variables in private list clauses as used in inner region.
1494 // Required for proper codegen of combined directives.
1495 // TODO: add processing for other clauses.
1496 if (auto *E = cast_or_null<Expr>(
1497 cast<OMPScheduleClause>(Clause)->getHelperChunkSize())) {
1498 MarkDeclarationsReferencedInExpr(E);
1499 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001500 }
1501 }
1502 return ActOnCapturedRegionEnd(S.get());
1503}
1504
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001505static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1506 OpenMPDirectiveKind CurrentRegion,
1507 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001508 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001509 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001510 // Allowed nesting of constructs
1511 // +------------------+-----------------+------------------------------------+
1512 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1513 // +------------------+-----------------+------------------------------------+
1514 // | parallel | parallel | * |
1515 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001516 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001517 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001518 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001519 // | parallel | simd | * |
1520 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001521 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001522 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001523 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001524 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001525 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001526 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001527 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001528 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001529 // | parallel | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001530 // | parallel | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001531 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001532 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001533 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001534 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001535 // | parallel | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001536 // | parallel | cancellation | |
1537 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001538 // | parallel | cancel | ! |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001539 // +------------------+-----------------+------------------------------------+
1540 // | for | parallel | * |
1541 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001542 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001543 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001544 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001545 // | for | simd | * |
1546 // | for | sections | + |
1547 // | for | section | + |
1548 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001549 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001550 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001551 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001552 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001553 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001554 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001555 // | for | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001556 // | for | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001557 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001558 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001559 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001560 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001561 // | for | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001562 // | for | cancellation | |
1563 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001564 // | for | cancel | ! |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001565 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001566 // | master | parallel | * |
1567 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001568 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001569 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001570 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001571 // | master | simd | * |
1572 // | master | sections | + |
1573 // | master | section | + |
1574 // | master | single | + |
1575 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001576 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001577 // | master |parallel sections| * |
1578 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001579 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001580 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001581 // | master | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001582 // | master | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001583 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001584 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001585 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001586 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001587 // | master | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001588 // | master | cancellation | |
1589 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001590 // | master | cancel | |
Alexander Musman80c22892014-07-17 08:54:58 +00001591 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001592 // | critical | parallel | * |
1593 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001594 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001595 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001596 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001597 // | critical | simd | * |
1598 // | critical | sections | + |
1599 // | critical | section | + |
1600 // | critical | single | + |
1601 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001602 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001603 // | critical |parallel sections| * |
1604 // | critical | task | * |
1605 // | critical | taskyield | * |
1606 // | critical | barrier | + |
1607 // | critical | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001608 // | critical | taskgroup | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001609 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001610 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001611 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001612 // | critical | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001613 // | critical | cancellation | |
1614 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001615 // | critical | cancel | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001616 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001617 // | simd | parallel | |
1618 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001619 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001620 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001621 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001622 // | simd | simd | |
1623 // | simd | sections | |
1624 // | simd | section | |
1625 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001626 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001627 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001628 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001629 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001630 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001631 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001632 // | simd | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001633 // | simd | taskgroup | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001634 // | simd | flush | |
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001635 // | simd | ordered | + (with simd clause) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001636 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001637 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001638 // | simd | teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001639 // | simd | cancellation | |
1640 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001641 // | simd | cancel | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001642 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001643 // | for simd | parallel | |
1644 // | for simd | for | |
1645 // | for simd | for simd | |
1646 // | for simd | master | |
1647 // | for simd | critical | |
1648 // | for simd | simd | |
1649 // | for simd | sections | |
1650 // | for simd | section | |
1651 // | for simd | single | |
1652 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001653 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001654 // | for simd |parallel sections| |
1655 // | for simd | task | |
1656 // | for simd | taskyield | |
1657 // | for simd | barrier | |
1658 // | for simd | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001659 // | for simd | taskgroup | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001660 // | for simd | flush | |
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001661 // | for simd | ordered | + (with simd clause) |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001662 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001663 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001664 // | for simd | teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001665 // | for simd | cancellation | |
1666 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001667 // | for simd | cancel | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001668 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001669 // | parallel for simd| parallel | |
1670 // | parallel for simd| for | |
1671 // | parallel for simd| for simd | |
1672 // | parallel for simd| master | |
1673 // | parallel for simd| critical | |
1674 // | parallel for simd| simd | |
1675 // | parallel for simd| sections | |
1676 // | parallel for simd| section | |
1677 // | parallel for simd| single | |
1678 // | parallel for simd| parallel for | |
1679 // | parallel for simd|parallel for simd| |
1680 // | parallel for simd|parallel sections| |
1681 // | parallel for simd| task | |
1682 // | parallel for simd| taskyield | |
1683 // | parallel for simd| barrier | |
1684 // | parallel for simd| taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001685 // | parallel for simd| taskgroup | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001686 // | parallel for simd| flush | |
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001687 // | parallel for simd| ordered | + (with simd clause) |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001688 // | parallel for simd| atomic | |
1689 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001690 // | parallel for simd| teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001691 // | parallel for simd| cancellation | |
1692 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001693 // | parallel for simd| cancel | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001694 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001695 // | sections | parallel | * |
1696 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001697 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001698 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001699 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001700 // | sections | simd | * |
1701 // | sections | sections | + |
1702 // | sections | section | * |
1703 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001704 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001705 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001706 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001707 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001708 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001709 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001710 // | sections | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001711 // | sections | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001712 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001713 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001714 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001715 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001716 // | sections | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001717 // | sections | cancellation | |
1718 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001719 // | sections | cancel | ! |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001720 // +------------------+-----------------+------------------------------------+
1721 // | section | parallel | * |
1722 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001723 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001724 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001725 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001726 // | section | simd | * |
1727 // | section | sections | + |
1728 // | section | section | + |
1729 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001730 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001731 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001732 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001733 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001734 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001735 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001736 // | section | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001737 // | section | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001738 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001739 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001740 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001741 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001742 // | section | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001743 // | section | cancellation | |
1744 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001745 // | section | cancel | ! |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001746 // +------------------+-----------------+------------------------------------+
1747 // | single | parallel | * |
1748 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001749 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001750 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001751 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001752 // | single | simd | * |
1753 // | single | sections | + |
1754 // | single | section | + |
1755 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001756 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001757 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001758 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001759 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001760 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001761 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001762 // | single | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001763 // | single | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001764 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001765 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001766 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001767 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001768 // | single | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001769 // | single | cancellation | |
1770 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001771 // | single | cancel | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001772 // +------------------+-----------------+------------------------------------+
1773 // | parallel for | parallel | * |
1774 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001775 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001776 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001777 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001778 // | parallel for | simd | * |
1779 // | parallel for | sections | + |
1780 // | parallel for | section | + |
1781 // | parallel for | single | + |
1782 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001783 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001784 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001785 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001786 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001787 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001788 // | parallel for | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001789 // | parallel for | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001790 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001791 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001792 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001793 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001794 // | parallel for | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001795 // | parallel for | cancellation | |
1796 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001797 // | parallel for | cancel | ! |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001798 // +------------------+-----------------+------------------------------------+
1799 // | parallel sections| parallel | * |
1800 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001801 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001802 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001803 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001804 // | parallel sections| simd | * |
1805 // | parallel sections| sections | + |
1806 // | parallel sections| section | * |
1807 // | parallel sections| single | + |
1808 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001809 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001810 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001811 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001812 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001813 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001814 // | parallel sections| taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001815 // | parallel sections| taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001816 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001817 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001818 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001819 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001820 // | parallel sections| teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001821 // | parallel sections| cancellation | |
1822 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001823 // | parallel sections| cancel | ! |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001824 // +------------------+-----------------+------------------------------------+
1825 // | task | parallel | * |
1826 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001827 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001828 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001829 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001830 // | task | simd | * |
1831 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001832 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001833 // | task | single | + |
1834 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001835 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001836 // | task |parallel sections| * |
1837 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001838 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001839 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001840 // | task | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001841 // | task | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001842 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001843 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001844 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001845 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001846 // | task | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001847 // | task | cancellation | |
Alexey Bataev80909872015-07-02 11:25:17 +00001848 // | | point | ! |
1849 // | task | cancel | ! |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001850 // +------------------+-----------------+------------------------------------+
1851 // | ordered | parallel | * |
1852 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001853 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001854 // | ordered | master | * |
1855 // | ordered | critical | * |
1856 // | ordered | simd | * |
1857 // | ordered | sections | + |
1858 // | ordered | section | + |
1859 // | ordered | single | + |
1860 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001861 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001862 // | ordered |parallel sections| * |
1863 // | ordered | task | * |
1864 // | ordered | taskyield | * |
1865 // | ordered | barrier | + |
1866 // | ordered | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001867 // | ordered | taskgroup | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001868 // | ordered | flush | * |
1869 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001870 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001871 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001872 // | ordered | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001873 // | ordered | cancellation | |
1874 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001875 // | ordered | cancel | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001876 // +------------------+-----------------+------------------------------------+
1877 // | atomic | parallel | |
1878 // | atomic | for | |
1879 // | atomic | for simd | |
1880 // | atomic | master | |
1881 // | atomic | critical | |
1882 // | atomic | simd | |
1883 // | atomic | sections | |
1884 // | atomic | section | |
1885 // | atomic | single | |
1886 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001887 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001888 // | atomic |parallel sections| |
1889 // | atomic | task | |
1890 // | atomic | taskyield | |
1891 // | atomic | barrier | |
1892 // | atomic | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001893 // | atomic | taskgroup | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001894 // | atomic | flush | |
1895 // | atomic | ordered | |
1896 // | atomic | atomic | |
1897 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001898 // | atomic | teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001899 // | atomic | cancellation | |
1900 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001901 // | atomic | cancel | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001902 // +------------------+-----------------+------------------------------------+
1903 // | target | parallel | * |
1904 // | target | for | * |
1905 // | target | for simd | * |
1906 // | target | master | * |
1907 // | target | critical | * |
1908 // | target | simd | * |
1909 // | target | sections | * |
1910 // | target | section | * |
1911 // | target | single | * |
1912 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001913 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001914 // | target |parallel sections| * |
1915 // | target | task | * |
1916 // | target | taskyield | * |
1917 // | target | barrier | * |
1918 // | target | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001919 // | target | taskgroup | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001920 // | target | flush | * |
1921 // | target | ordered | * |
1922 // | target | atomic | * |
1923 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001924 // | target | teams | * |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001925 // | target | cancellation | |
1926 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001927 // | target | cancel | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001928 // +------------------+-----------------+------------------------------------+
1929 // | teams | parallel | * |
1930 // | teams | for | + |
1931 // | teams | for simd | + |
1932 // | teams | master | + |
1933 // | teams | critical | + |
1934 // | teams | simd | + |
1935 // | teams | sections | + |
1936 // | teams | section | + |
1937 // | teams | single | + |
1938 // | teams | parallel for | * |
1939 // | teams |parallel for simd| * |
1940 // | teams |parallel sections| * |
1941 // | teams | task | + |
1942 // | teams | taskyield | + |
1943 // | teams | barrier | + |
1944 // | teams | taskwait | + |
Alexey Bataev80909872015-07-02 11:25:17 +00001945 // | teams | taskgroup | + |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001946 // | teams | flush | + |
1947 // | teams | ordered | + |
1948 // | teams | atomic | + |
1949 // | teams | target | + |
1950 // | teams | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001951 // | teams | cancellation | |
1952 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001953 // | teams | cancel | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001954 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00001955 if (Stack->getCurScope()) {
1956 auto ParentRegion = Stack->getParentDirective();
1957 bool NestingProhibited = false;
1958 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001959 enum {
1960 NoRecommend,
1961 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001962 ShouldBeInOrderedRegion,
1963 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001964 } Recommend = NoRecommend;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001965 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001966 // OpenMP [2.16, Nesting of Regions]
1967 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001968 // OpenMP [2.8.1,simd Construct, Restrictions]
1969 // An ordered construct with the simd clause is the only OpenMP construct
1970 // that can appear in the simd region.
Alexey Bataev549210e2014-06-24 04:39:47 +00001971 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1972 return true;
1973 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001974 if (ParentRegion == OMPD_atomic) {
1975 // OpenMP [2.16, Nesting of Regions]
1976 // OpenMP constructs may not be nested inside an atomic region.
1977 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1978 return true;
1979 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001980 if (CurrentRegion == OMPD_section) {
1981 // OpenMP [2.7.2, sections Construct, Restrictions]
1982 // Orphaned section directives are prohibited. That is, the section
1983 // directives must appear within the sections construct and must not be
1984 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001985 if (ParentRegion != OMPD_sections &&
1986 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001987 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1988 << (ParentRegion != OMPD_unknown)
1989 << getOpenMPDirectiveName(ParentRegion);
1990 return true;
1991 }
1992 return false;
1993 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001994 // Allow some constructs to be orphaned (they could be used in functions,
1995 // called from OpenMP regions with the required preconditions).
1996 if (ParentRegion == OMPD_unknown)
1997 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00001998 if (CurrentRegion == OMPD_cancellation_point ||
1999 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002000 // OpenMP [2.16, Nesting of Regions]
2001 // A cancellation point construct for which construct-type-clause is
2002 // taskgroup must be nested inside a task construct. A cancellation
2003 // point construct for which construct-type-clause is not taskgroup must
2004 // be closely nested inside an OpenMP construct that matches the type
2005 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002006 // A cancel construct for which construct-type-clause is taskgroup must be
2007 // nested inside a task construct. A cancel construct for which
2008 // construct-type-clause is not taskgroup must be closely nested inside an
2009 // OpenMP construct that matches the type specified in
2010 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002011 NestingProhibited =
2012 !((CancelRegion == OMPD_parallel && ParentRegion == OMPD_parallel) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002013 (CancelRegion == OMPD_for &&
2014 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002015 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2016 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002017 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2018 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002019 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002020 // OpenMP [2.16, Nesting of Regions]
2021 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002022 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002023 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2024 ParentRegion == OMPD_task;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002025 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2026 // OpenMP [2.16, Nesting of Regions]
2027 // A critical region may not be nested (closely or otherwise) inside a
2028 // critical region with the same name. Note that this restriction is not
2029 // sufficient to prevent deadlock.
2030 SourceLocation PreviousCriticalLoc;
2031 bool DeadLock =
2032 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
2033 OpenMPDirectiveKind K,
2034 const DeclarationNameInfo &DNI,
2035 SourceLocation Loc)
2036 ->bool {
2037 if (K == OMPD_critical &&
2038 DNI.getName() == CurrentName.getName()) {
2039 PreviousCriticalLoc = Loc;
2040 return true;
2041 } else
2042 return false;
2043 },
2044 false /* skip top directive */);
2045 if (DeadLock) {
2046 SemaRef.Diag(StartLoc,
2047 diag::err_omp_prohibited_region_critical_same_name)
2048 << CurrentName.getName();
2049 if (PreviousCriticalLoc.isValid())
2050 SemaRef.Diag(PreviousCriticalLoc,
2051 diag::note_omp_previous_critical_region);
2052 return true;
2053 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002054 } else if (CurrentRegion == OMPD_barrier) {
2055 // OpenMP [2.16, Nesting of Regions]
2056 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002057 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002058 NestingProhibited =
2059 isOpenMPWorksharingDirective(ParentRegion) ||
2060 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
2061 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002062 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00002063 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002064 // OpenMP [2.16, Nesting of Regions]
2065 // A worksharing region may not be closely nested inside a worksharing,
2066 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002067 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00002068 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002069 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
2070 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
2071 Recommend = ShouldBeInParallelRegion;
2072 } else if (CurrentRegion == OMPD_ordered) {
2073 // OpenMP [2.16, Nesting of Regions]
2074 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002075 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002076 // An ordered region must be closely nested inside a loop region (or
2077 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002078 // OpenMP [2.8.1,simd Construct, Restrictions]
2079 // An ordered construct with the simd clause is the only OpenMP construct
2080 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002081 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00002082 ParentRegion == OMPD_task ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002083 !(isOpenMPSimdDirective(ParentRegion) ||
2084 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002085 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002086 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
2087 // OpenMP [2.16, Nesting of Regions]
2088 // If specified, a teams construct must be contained within a target
2089 // construct.
2090 NestingProhibited = ParentRegion != OMPD_target;
2091 Recommend = ShouldBeInTargetRegion;
2092 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2093 }
2094 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
2095 // OpenMP [2.16, Nesting of Regions]
2096 // distribute, parallel, parallel sections, parallel workshare, and the
2097 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2098 // constructs that can be closely nested in the teams region.
2099 // TODO: add distribute directive.
2100 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
2101 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002102 }
2103 if (NestingProhibited) {
2104 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002105 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
2106 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00002107 return true;
2108 }
2109 }
2110 return false;
2111}
2112
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002113static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2114 ArrayRef<OMPClause *> Clauses,
2115 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2116 bool ErrorFound = false;
2117 unsigned NamedModifiersNumber = 0;
2118 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2119 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002120 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002121 for (const auto *C : Clauses) {
2122 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2123 // At most one if clause without a directive-name-modifier can appear on
2124 // the directive.
2125 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2126 if (FoundNameModifiers[CurNM]) {
2127 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2128 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2129 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2130 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002131 } else if (CurNM != OMPD_unknown) {
2132 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002133 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002134 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002135 FoundNameModifiers[CurNM] = IC;
2136 if (CurNM == OMPD_unknown)
2137 continue;
2138 // Check if the specified name modifier is allowed for the current
2139 // directive.
2140 // At most one if clause with the particular directive-name-modifier can
2141 // appear on the directive.
2142 bool MatchFound = false;
2143 for (auto NM : AllowedNameModifiers) {
2144 if (CurNM == NM) {
2145 MatchFound = true;
2146 break;
2147 }
2148 }
2149 if (!MatchFound) {
2150 S.Diag(IC->getNameModifierLoc(),
2151 diag::err_omp_wrong_if_directive_name_modifier)
2152 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2153 ErrorFound = true;
2154 }
2155 }
2156 }
2157 // If any if clause on the directive includes a directive-name-modifier then
2158 // all if clauses on the directive must include a directive-name-modifier.
2159 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2160 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2161 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2162 diag::err_omp_no_more_if_clause);
2163 } else {
2164 std::string Values;
2165 std::string Sep(", ");
2166 unsigned AllowedCnt = 0;
2167 unsigned TotalAllowedNum =
2168 AllowedNameModifiers.size() - NamedModifiersNumber;
2169 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2170 ++Cnt) {
2171 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2172 if (!FoundNameModifiers[NM]) {
2173 Values += "'";
2174 Values += getOpenMPDirectiveName(NM);
2175 Values += "'";
2176 if (AllowedCnt + 2 == TotalAllowedNum)
2177 Values += " or ";
2178 else if (AllowedCnt + 1 != TotalAllowedNum)
2179 Values += Sep;
2180 ++AllowedCnt;
2181 }
2182 }
2183 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2184 diag::err_omp_unnamed_if_clause)
2185 << (TotalAllowedNum > 1) << Values;
2186 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002187 for (auto Loc : NameModifierLoc) {
2188 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2189 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002190 ErrorFound = true;
2191 }
2192 return ErrorFound;
2193}
2194
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002195StmtResult Sema::ActOnOpenMPExecutableDirective(
2196 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2197 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2198 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002199 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002200 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2201 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002202 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002203
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002204 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00002205 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002206 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002207 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002208 if (AStmt) {
2209 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2210
2211 // Check default data sharing attributes for referenced variables.
2212 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2213 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2214 if (DSAChecker.isErrorFound())
2215 return StmtError();
2216 // Generate list of implicitly defined firstprivate variables.
2217 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002218
2219 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2220 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2221 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2222 SourceLocation(), SourceLocation())) {
2223 ClausesWithImplicit.push_back(Implicit);
2224 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2225 DSAChecker.getImplicitFirstprivate().size();
2226 } else
2227 ErrorFound = true;
2228 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002229 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002230
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002231 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002232 switch (Kind) {
2233 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002234 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2235 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002236 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002237 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002238 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002239 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2240 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002241 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002242 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002243 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2244 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002245 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002246 case OMPD_for_simd:
2247 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2248 EndLoc, VarsWithInheritedDSA);
2249 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002250 case OMPD_sections:
2251 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2252 EndLoc);
2253 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002254 case OMPD_section:
2255 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002256 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002257 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2258 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002259 case OMPD_single:
2260 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2261 EndLoc);
2262 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002263 case OMPD_master:
2264 assert(ClausesWithImplicit.empty() &&
2265 "No clauses are allowed for 'omp master' directive");
2266 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2267 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002268 case OMPD_critical:
2269 assert(ClausesWithImplicit.empty() &&
2270 "No clauses are allowed for 'omp critical' directive");
2271 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
2272 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002273 case OMPD_parallel_for:
2274 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2275 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002276 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002277 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002278 case OMPD_parallel_for_simd:
2279 Res = ActOnOpenMPParallelForSimdDirective(
2280 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002281 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002282 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002283 case OMPD_parallel_sections:
2284 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2285 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002286 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002287 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002288 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002289 Res =
2290 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002291 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002292 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002293 case OMPD_taskyield:
2294 assert(ClausesWithImplicit.empty() &&
2295 "No clauses are allowed for 'omp taskyield' directive");
2296 assert(AStmt == nullptr &&
2297 "No associated statement allowed for 'omp taskyield' directive");
2298 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2299 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002300 case OMPD_barrier:
2301 assert(ClausesWithImplicit.empty() &&
2302 "No clauses are allowed for 'omp barrier' directive");
2303 assert(AStmt == nullptr &&
2304 "No associated statement allowed for 'omp barrier' directive");
2305 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2306 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002307 case OMPD_taskwait:
2308 assert(ClausesWithImplicit.empty() &&
2309 "No clauses are allowed for 'omp taskwait' directive");
2310 assert(AStmt == nullptr &&
2311 "No associated statement allowed for 'omp taskwait' directive");
2312 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2313 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002314 case OMPD_taskgroup:
2315 assert(ClausesWithImplicit.empty() &&
2316 "No clauses are allowed for 'omp taskgroup' directive");
2317 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2318 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002319 case OMPD_flush:
2320 assert(AStmt == nullptr &&
2321 "No associated statement allowed for 'omp flush' directive");
2322 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2323 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002324 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002325 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2326 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002327 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002328 case OMPD_atomic:
2329 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2330 EndLoc);
2331 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002332 case OMPD_teams:
2333 Res =
2334 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2335 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002336 case OMPD_target:
2337 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2338 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002339 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002340 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002341 case OMPD_cancellation_point:
2342 assert(ClausesWithImplicit.empty() &&
2343 "No clauses are allowed for 'omp cancellation point' directive");
2344 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2345 "cancellation point' directive");
2346 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2347 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002348 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002349 assert(AStmt == nullptr &&
2350 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002351 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2352 CancelRegion);
2353 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002354 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002355 case OMPD_target_data:
2356 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2357 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002358 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002359 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002360 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002361 llvm_unreachable("OpenMP Directive is not allowed");
2362 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002363 llvm_unreachable("Unknown OpenMP directive");
2364 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002365
Alexey Bataev4acb8592014-07-07 13:01:15 +00002366 for (auto P : VarsWithInheritedDSA) {
2367 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2368 << P.first << P.second->getSourceRange();
2369 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002370 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2371
2372 if (!AllowedNameModifiers.empty())
2373 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2374 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002375
Alexey Bataeved09d242014-05-28 05:53:51 +00002376 if (ErrorFound)
2377 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002378 return Res;
2379}
2380
2381StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2382 Stmt *AStmt,
2383 SourceLocation StartLoc,
2384 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002385 if (!AStmt)
2386 return StmtError();
2387
Alexey Bataev9959db52014-05-06 10:08:46 +00002388 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2389 // 1.2.2 OpenMP Language Terminology
2390 // Structured block - An executable statement with a single entry at the
2391 // top and a single exit at the bottom.
2392 // The point of exit cannot be a branch out of the structured block.
2393 // longjmp() and throw() must not violate the entry/exit criteria.
2394 CS->getCapturedDecl()->setNothrow();
2395
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002396 getCurFunction()->setHasBranchProtectedScope();
2397
Alexey Bataev25e5b442015-09-15 12:52:43 +00002398 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2399 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002400}
2401
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002402namespace {
2403/// \brief Helper class for checking canonical form of the OpenMP loops and
2404/// extracting iteration space of each loop in the loop nest, that will be used
2405/// for IR generation.
2406class OpenMPIterationSpaceChecker {
2407 /// \brief Reference to Sema.
2408 Sema &SemaRef;
2409 /// \brief A location for diagnostics (when there is no some better location).
2410 SourceLocation DefaultLoc;
2411 /// \brief A location for diagnostics (when increment is not compatible).
2412 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002413 /// \brief A source location for referring to loop init later.
2414 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002415 /// \brief A source location for referring to condition later.
2416 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002417 /// \brief A source location for referring to increment later.
2418 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002419 /// \brief Loop variable.
2420 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002421 /// \brief Reference to loop variable.
2422 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002423 /// \brief Lower bound (initializer for the var).
2424 Expr *LB;
2425 /// \brief Upper bound.
2426 Expr *UB;
2427 /// \brief Loop step (increment).
2428 Expr *Step;
2429 /// \brief This flag is true when condition is one of:
2430 /// Var < UB
2431 /// Var <= UB
2432 /// UB > Var
2433 /// UB >= Var
2434 bool TestIsLessOp;
2435 /// \brief This flag is true when condition is strict ( < or > ).
2436 bool TestIsStrictOp;
2437 /// \brief This flag is true when step is subtracted on each iteration.
2438 bool SubtractStep;
2439
2440public:
2441 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2442 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00002443 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
2444 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002445 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
2446 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002447 /// \brief Check init-expr for canonical loop form and save loop counter
2448 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002449 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002450 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2451 /// for less/greater and for strict/non-strict comparison.
2452 bool CheckCond(Expr *S);
2453 /// \brief Check incr-expr for canonical loop form and return true if it
2454 /// does not conform, otherwise save loop step (#Step).
2455 bool CheckInc(Expr *S);
2456 /// \brief Return the loop counter variable.
2457 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002458 /// \brief Return the reference expression to loop counter variable.
2459 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002460 /// \brief Source range of the loop init.
2461 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2462 /// \brief Source range of the loop condition.
2463 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2464 /// \brief Source range of the loop increment.
2465 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2466 /// \brief True if the step should be subtracted.
2467 bool ShouldSubtractStep() const { return SubtractStep; }
2468 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002469 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002470 /// \brief Build the precondition expression for the loops.
2471 Expr *BuildPreCond(Scope *S, Expr *Cond) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002472 /// \brief Build reference expression to the counter be used for codegen.
2473 Expr *BuildCounterVar() const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002474 /// \brief Build reference expression to the private counter be used for
2475 /// codegen.
2476 Expr *BuildPrivateCounterVar() const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002477 /// \brief Build initization of the counter be used for codegen.
2478 Expr *BuildCounterInit() const;
2479 /// \brief Build step of the counter be used for codegen.
2480 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002481 /// \brief Return true if any expression is dependent.
2482 bool Dependent() const;
2483
2484private:
2485 /// \brief Check the right-hand side of an assignment in the increment
2486 /// expression.
2487 bool CheckIncRHS(Expr *RHS);
2488 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002489 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002490 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002491 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002492 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002493 /// \brief Helper to set loop increment.
2494 bool SetStep(Expr *NewStep, bool Subtract);
2495};
2496
2497bool OpenMPIterationSpaceChecker::Dependent() const {
2498 if (!Var) {
2499 assert(!LB && !UB && !Step);
2500 return false;
2501 }
2502 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2503 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2504}
2505
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002506template <typename T>
2507static T *getExprAsWritten(T *E) {
2508 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2509 E = ExprTemp->getSubExpr();
2510
2511 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2512 E = MTE->GetTemporaryExpr();
2513
2514 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2515 E = Binder->getSubExpr();
2516
2517 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2518 E = ICE->getSubExprAsWritten();
2519 return E->IgnoreParens();
2520}
2521
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002522bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2523 DeclRefExpr *NewVarRefExpr,
2524 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002525 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002526 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2527 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002528 if (!NewVar || !NewLB)
2529 return true;
2530 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002531 VarRef = NewVarRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002532 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2533 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002534 if ((Ctor->isCopyOrMoveConstructor() ||
2535 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2536 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002537 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002538 LB = NewLB;
2539 return false;
2540}
2541
2542bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002543 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002544 // State consistency checking to ensure correct usage.
2545 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2546 !TestIsLessOp && !TestIsStrictOp);
2547 if (!NewUB)
2548 return true;
2549 UB = NewUB;
2550 TestIsLessOp = LessOp;
2551 TestIsStrictOp = StrictOp;
2552 ConditionSrcRange = SR;
2553 ConditionLoc = SL;
2554 return false;
2555}
2556
2557bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2558 // State consistency checking to ensure correct usage.
2559 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2560 if (!NewStep)
2561 return true;
2562 if (!NewStep->isValueDependent()) {
2563 // Check that the step is integer expression.
2564 SourceLocation StepLoc = NewStep->getLocStart();
2565 ExprResult Val =
2566 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2567 if (Val.isInvalid())
2568 return true;
2569 NewStep = Val.get();
2570
2571 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2572 // If test-expr is of form var relational-op b and relational-op is < or
2573 // <= then incr-expr must cause var to increase on each iteration of the
2574 // loop. If test-expr is of form var relational-op b and relational-op is
2575 // > or >= then incr-expr must cause var to decrease on each iteration of
2576 // the loop.
2577 // If test-expr is of form b relational-op var and relational-op is < or
2578 // <= then incr-expr must cause var to decrease on each iteration of the
2579 // loop. If test-expr is of form b relational-op var and relational-op is
2580 // > or >= then incr-expr must cause var to increase on each iteration of
2581 // the loop.
2582 llvm::APSInt Result;
2583 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2584 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2585 bool IsConstNeg =
2586 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002587 bool IsConstPos =
2588 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002589 bool IsConstZero = IsConstant && !Result.getBoolValue();
2590 if (UB && (IsConstZero ||
2591 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002592 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002593 SemaRef.Diag(NewStep->getExprLoc(),
2594 diag::err_omp_loop_incr_not_compatible)
2595 << Var << TestIsLessOp << NewStep->getSourceRange();
2596 SemaRef.Diag(ConditionLoc,
2597 diag::note_omp_loop_cond_requres_compatible_incr)
2598 << TestIsLessOp << ConditionSrcRange;
2599 return true;
2600 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002601 if (TestIsLessOp == Subtract) {
2602 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2603 NewStep).get();
2604 Subtract = !Subtract;
2605 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002606 }
2607
2608 Step = NewStep;
2609 SubtractStep = Subtract;
2610 return false;
2611}
2612
Alexey Bataev9c821032015-04-30 04:23:23 +00002613bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002614 // Check init-expr for canonical loop form and save loop counter
2615 // variable - #Var and its initialization value - #LB.
2616 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2617 // var = lb
2618 // integer-type var = lb
2619 // random-access-iterator-type var = lb
2620 // pointer-type var = lb
2621 //
2622 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002623 if (EmitDiags) {
2624 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2625 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002626 return true;
2627 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002628 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002629 if (Expr *E = dyn_cast<Expr>(S))
2630 S = E->IgnoreParens();
2631 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2632 if (BO->getOpcode() == BO_Assign)
2633 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002634 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002635 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002636 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2637 if (DS->isSingleDecl()) {
2638 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00002639 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002640 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002641 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002642 SemaRef.Diag(S->getLocStart(),
2643 diag::ext_omp_loop_not_canonical_init)
2644 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002645 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002646 }
2647 }
2648 }
2649 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2650 if (CE->getOperator() == OO_Equal)
2651 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002652 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2653 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002654
Alexey Bataev9c821032015-04-30 04:23:23 +00002655 if (EmitDiags) {
2656 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2657 << S->getSourceRange();
2658 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002659 return true;
2660}
2661
Alexey Bataev23b69422014-06-18 07:08:49 +00002662/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002663/// variable (which may be the loop variable) if possible.
2664static const VarDecl *GetInitVarDecl(const Expr *E) {
2665 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002666 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002667 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002668 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2669 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002670 if ((Ctor->isCopyOrMoveConstructor() ||
2671 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2672 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002673 E = CE->getArg(0)->IgnoreParenImpCasts();
2674 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2675 if (!DRE)
2676 return nullptr;
2677 return dyn_cast<VarDecl>(DRE->getDecl());
2678}
2679
2680bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2681 // Check test-expr for canonical form, save upper-bound UB, flags for
2682 // less/greater and for strict/non-strict comparison.
2683 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2684 // var relational-op b
2685 // b relational-op var
2686 //
2687 if (!S) {
2688 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2689 return true;
2690 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002691 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002692 SourceLocation CondLoc = S->getLocStart();
2693 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2694 if (BO->isRelationalOp()) {
2695 if (GetInitVarDecl(BO->getLHS()) == Var)
2696 return SetUB(BO->getRHS(),
2697 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2698 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2699 BO->getSourceRange(), BO->getOperatorLoc());
2700 if (GetInitVarDecl(BO->getRHS()) == Var)
2701 return SetUB(BO->getLHS(),
2702 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2703 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2704 BO->getSourceRange(), BO->getOperatorLoc());
2705 }
2706 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2707 if (CE->getNumArgs() == 2) {
2708 auto Op = CE->getOperator();
2709 switch (Op) {
2710 case OO_Greater:
2711 case OO_GreaterEqual:
2712 case OO_Less:
2713 case OO_LessEqual:
2714 if (GetInitVarDecl(CE->getArg(0)) == Var)
2715 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2716 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2717 CE->getOperatorLoc());
2718 if (GetInitVarDecl(CE->getArg(1)) == Var)
2719 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2720 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2721 CE->getOperatorLoc());
2722 break;
2723 default:
2724 break;
2725 }
2726 }
2727 }
2728 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2729 << S->getSourceRange() << Var;
2730 return true;
2731}
2732
2733bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2734 // RHS of canonical loop form increment can be:
2735 // var + incr
2736 // incr + var
2737 // var - incr
2738 //
2739 RHS = RHS->IgnoreParenImpCasts();
2740 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2741 if (BO->isAdditiveOp()) {
2742 bool IsAdd = BO->getOpcode() == BO_Add;
2743 if (GetInitVarDecl(BO->getLHS()) == Var)
2744 return SetStep(BO->getRHS(), !IsAdd);
2745 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2746 return SetStep(BO->getLHS(), false);
2747 }
2748 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2749 bool IsAdd = CE->getOperator() == OO_Plus;
2750 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2751 if (GetInitVarDecl(CE->getArg(0)) == Var)
2752 return SetStep(CE->getArg(1), !IsAdd);
2753 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2754 return SetStep(CE->getArg(0), false);
2755 }
2756 }
2757 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2758 << RHS->getSourceRange() << Var;
2759 return true;
2760}
2761
2762bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2763 // Check incr-expr for canonical loop form and return true if it
2764 // does not conform.
2765 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2766 // ++var
2767 // var++
2768 // --var
2769 // var--
2770 // var += incr
2771 // var -= incr
2772 // var = var + incr
2773 // var = incr + var
2774 // var = var - incr
2775 //
2776 if (!S) {
2777 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2778 return true;
2779 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002780 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002781 S = S->IgnoreParens();
2782 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2783 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2784 return SetStep(
2785 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2786 (UO->isDecrementOp() ? -1 : 1)).get(),
2787 false);
2788 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2789 switch (BO->getOpcode()) {
2790 case BO_AddAssign:
2791 case BO_SubAssign:
2792 if (GetInitVarDecl(BO->getLHS()) == Var)
2793 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2794 break;
2795 case BO_Assign:
2796 if (GetInitVarDecl(BO->getLHS()) == Var)
2797 return CheckIncRHS(BO->getRHS());
2798 break;
2799 default:
2800 break;
2801 }
2802 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2803 switch (CE->getOperator()) {
2804 case OO_PlusPlus:
2805 case OO_MinusMinus:
2806 if (GetInitVarDecl(CE->getArg(0)) == Var)
2807 return SetStep(
2808 SemaRef.ActOnIntegerConstant(
2809 CE->getLocStart(),
2810 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2811 false);
2812 break;
2813 case OO_PlusEqual:
2814 case OO_MinusEqual:
2815 if (GetInitVarDecl(CE->getArg(0)) == Var)
2816 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2817 break;
2818 case OO_Equal:
2819 if (GetInitVarDecl(CE->getArg(0)) == Var)
2820 return CheckIncRHS(CE->getArg(1));
2821 break;
2822 default:
2823 break;
2824 }
2825 }
2826 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2827 << S->getSourceRange() << Var;
2828 return true;
2829}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002830
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002831namespace {
2832// Transform variables declared in GNU statement expressions to new ones to
2833// avoid crash on codegen.
2834class TransformToNewDefs : public TreeTransform<TransformToNewDefs> {
2835 typedef TreeTransform<TransformToNewDefs> BaseTransform;
2836
2837public:
2838 TransformToNewDefs(Sema &SemaRef) : BaseTransform(SemaRef) {}
2839
2840 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
2841 if (auto *VD = cast<VarDecl>(D))
2842 if (!isa<ParmVarDecl>(D) && !isa<VarTemplateSpecializationDecl>(D) &&
2843 !isa<ImplicitParamDecl>(D)) {
2844 auto *NewVD = VarDecl::Create(
2845 SemaRef.Context, VD->getDeclContext(), VD->getLocStart(),
2846 VD->getLocation(), VD->getIdentifier(), VD->getType(),
2847 VD->getTypeSourceInfo(), VD->getStorageClass());
2848 NewVD->setTSCSpec(VD->getTSCSpec());
2849 NewVD->setInit(VD->getInit());
2850 NewVD->setInitStyle(VD->getInitStyle());
2851 NewVD->setExceptionVariable(VD->isExceptionVariable());
2852 NewVD->setNRVOVariable(VD->isNRVOVariable());
2853 NewVD->setCXXForRangeDecl(VD->isInExternCXXContext());
2854 NewVD->setConstexpr(VD->isConstexpr());
2855 NewVD->setInitCapture(VD->isInitCapture());
2856 NewVD->setPreviousDeclInSameBlockScope(
2857 VD->isPreviousDeclInSameBlockScope());
2858 VD->getDeclContext()->addHiddenDecl(NewVD);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002859 if (VD->hasAttrs())
2860 NewVD->setAttrs(VD->getAttrs());
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002861 transformedLocalDecl(VD, NewVD);
2862 return NewVD;
2863 }
2864 return BaseTransform::TransformDefinition(Loc, D);
2865 }
2866
2867 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
2868 if (auto *NewD = TransformDecl(E->getExprLoc(), E->getDecl()))
2869 if (E->getDecl() != NewD) {
2870 NewD->setReferenced();
2871 NewD->markUsed(SemaRef.Context);
2872 return DeclRefExpr::Create(
2873 SemaRef.Context, E->getQualifierLoc(), E->getTemplateKeywordLoc(),
2874 cast<ValueDecl>(NewD), E->refersToEnclosingVariableOrCapture(),
2875 E->getNameInfo(), E->getType(), E->getValueKind());
2876 }
2877 return BaseTransform::TransformDeclRefExpr(E);
2878 }
2879};
2880}
2881
Alexander Musmana5f070a2014-10-01 06:03:56 +00002882/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002883Expr *
2884OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2885 const bool LimitedType) const {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002886 TransformToNewDefs Transform(SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002887 ExprResult Diff;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002888 auto VarType = Var->getType().getNonReferenceType();
2889 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00002890 SemaRef.getLangOpts().CPlusPlus) {
2891 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002892 auto *UBExpr = TestIsLessOp ? UB : LB;
2893 auto *LBExpr = TestIsLessOp ? LB : UB;
2894 Expr *Upper = Transform.TransformExpr(UBExpr).get();
2895 Expr *Lower = Transform.TransformExpr(LBExpr).get();
2896 if (!Upper || !Lower)
2897 return nullptr;
2898 Upper = SemaRef.PerformImplicitConversion(Upper, UBExpr->getType(),
2899 Sema::AA_Converting,
2900 /*AllowExplicit=*/true)
2901 .get();
2902 Lower = SemaRef.PerformImplicitConversion(Lower, LBExpr->getType(),
2903 Sema::AA_Converting,
2904 /*AllowExplicit=*/true)
2905 .get();
2906 if (!Upper || !Lower)
2907 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002908
2909 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2910
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002911 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002912 // BuildBinOp already emitted error, this one is to point user to upper
2913 // and lower bound, and to tell what is passed to 'operator-'.
2914 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2915 << Upper->getSourceRange() << Lower->getSourceRange();
2916 return nullptr;
2917 }
2918 }
2919
2920 if (!Diff.isUsable())
2921 return nullptr;
2922
2923 // Upper - Lower [- 1]
2924 if (TestIsStrictOp)
2925 Diff = SemaRef.BuildBinOp(
2926 S, DefaultLoc, BO_Sub, Diff.get(),
2927 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2928 if (!Diff.isUsable())
2929 return nullptr;
2930
2931 // Upper - Lower [- 1] + Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002932 auto NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
2933 if (NewStep.isInvalid())
2934 return nullptr;
2935 NewStep = SemaRef.PerformImplicitConversion(
2936 NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
2937 /*AllowExplicit=*/true);
2938 if (NewStep.isInvalid())
2939 return nullptr;
2940 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002941 if (!Diff.isUsable())
2942 return nullptr;
2943
2944 // Parentheses (for dumping/debugging purposes only).
2945 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2946 if (!Diff.isUsable())
2947 return nullptr;
2948
2949 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002950 NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
2951 if (NewStep.isInvalid())
2952 return nullptr;
2953 NewStep = SemaRef.PerformImplicitConversion(
2954 NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
2955 /*AllowExplicit=*/true);
2956 if (NewStep.isInvalid())
2957 return nullptr;
2958 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002959 if (!Diff.isUsable())
2960 return nullptr;
2961
Alexander Musman174b3ca2014-10-06 11:16:29 +00002962 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002963 QualType Type = Diff.get()->getType();
2964 auto &C = SemaRef.Context;
2965 bool UseVarType = VarType->hasIntegerRepresentation() &&
2966 C.getTypeSize(Type) > C.getTypeSize(VarType);
2967 if (!Type->isIntegerType() || UseVarType) {
2968 unsigned NewSize =
2969 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
2970 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
2971 : Type->hasSignedIntegerRepresentation();
2972 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
2973 Diff = SemaRef.PerformImplicitConversion(
2974 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
2975 if (!Diff.isUsable())
2976 return nullptr;
2977 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00002978 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00002979 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2980 if (NewSize != C.getTypeSize(Type)) {
2981 if (NewSize < C.getTypeSize(Type)) {
2982 assert(NewSize == 64 && "incorrect loop var size");
2983 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2984 << InitSrcRange << ConditionSrcRange;
2985 }
2986 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002987 NewSize, Type->hasSignedIntegerRepresentation() ||
2988 C.getTypeSize(Type) < NewSize);
Alexander Musman174b3ca2014-10-06 11:16:29 +00002989 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2990 Sema::AA_Converting, true);
2991 if (!Diff.isUsable())
2992 return nullptr;
2993 }
2994 }
2995
Alexander Musmana5f070a2014-10-01 06:03:56 +00002996 return Diff.get();
2997}
2998
Alexey Bataev62dbb972015-04-22 11:59:37 +00002999Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
3000 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3001 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3002 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003003 TransformToNewDefs Transform(SemaRef);
3004
3005 auto NewLB = Transform.TransformExpr(LB);
3006 auto NewUB = Transform.TransformExpr(UB);
3007 if (NewLB.isInvalid() || NewUB.isInvalid())
3008 return Cond;
3009 NewLB = SemaRef.PerformImplicitConversion(NewLB.get(), LB->getType(),
3010 Sema::AA_Converting,
3011 /*AllowExplicit=*/true);
3012 NewUB = SemaRef.PerformImplicitConversion(NewUB.get(), UB->getType(),
3013 Sema::AA_Converting,
3014 /*AllowExplicit=*/true);
3015 if (NewLB.isInvalid() || NewUB.isInvalid())
3016 return Cond;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003017 auto CondExpr = SemaRef.BuildBinOp(
3018 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3019 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003020 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003021 if (CondExpr.isUsable()) {
3022 CondExpr = SemaRef.PerformImplicitConversion(
3023 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3024 /*AllowExplicit=*/true);
3025 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003026 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3027 // Otherwise use original loop conditon and evaluate it in runtime.
3028 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3029}
3030
Alexander Musmana5f070a2014-10-01 06:03:56 +00003031/// \brief Build reference expression to the counter be used for codegen.
3032Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
Alexey Bataeva8899172015-08-06 12:30:57 +00003033 return buildDeclRefExpr(SemaRef, Var, Var->getType().getNonReferenceType(),
3034 DefaultLoc);
3035}
3036
3037Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
3038 if (Var && !Var->isInvalidDecl()) {
3039 auto Type = Var->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003040 auto *PrivateVar =
3041 buildVarDecl(SemaRef, DefaultLoc, Type, Var->getName(),
3042 Var->hasAttrs() ? &Var->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003043 if (PrivateVar->isInvalidDecl())
3044 return nullptr;
3045 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3046 }
3047 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003048}
3049
3050/// \brief Build initization of the counter be used for codegen.
3051Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3052
3053/// \brief Build step of the counter be used for codegen.
3054Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3055
3056/// \brief Iteration space of a single for loop.
3057struct LoopIterationSpace {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003058 /// \brief Condition of the loop.
3059 Expr *PreCond;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003060 /// \brief This expression calculates the number of iterations in the loop.
3061 /// It is always possible to calculate it before starting the loop.
3062 Expr *NumIterations;
3063 /// \brief The loop counter variable.
3064 Expr *CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00003065 /// \brief Private loop counter variable.
3066 Expr *PrivateCounterVar;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003067 /// \brief This is initializer for the initial value of #CounterVar.
3068 Expr *CounterInit;
3069 /// \brief This is step for the #CounterVar used to generate its update:
3070 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
3071 Expr *CounterStep;
3072 /// \brief Should step be subtracted?
3073 bool Subtract;
3074 /// \brief Source range of the loop init.
3075 SourceRange InitSrcRange;
3076 /// \brief Source range of the loop condition.
3077 SourceRange CondSrcRange;
3078 /// \brief Source range of the loop increment.
3079 SourceRange IncSrcRange;
3080};
3081
Alexey Bataev23b69422014-06-18 07:08:49 +00003082} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003083
Alexey Bataev9c821032015-04-30 04:23:23 +00003084void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3085 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3086 assert(Init && "Expected loop in canonical form.");
3087 unsigned CollapseIteration = DSAStack->getCollapseNumber();
3088 if (CollapseIteration > 0 &&
3089 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3090 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
3091 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3092 DSAStack->addLoopControlVariable(ISC.GetLoopVar());
3093 }
3094 DSAStack->setCollapseNumber(CollapseIteration - 1);
3095 }
3096}
3097
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003098/// \brief Called on a for stmt to check and extract its iteration space
3099/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003100static bool CheckOpenMPIterationSpace(
3101 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3102 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003103 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003104 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
3105 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003106 // OpenMP [2.6, Canonical Loop Form]
3107 // for (init-expr; test-expr; incr-expr) structured-block
3108 auto For = dyn_cast_or_null<ForStmt>(S);
3109 if (!For) {
3110 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003111 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3112 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3113 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3114 if (NestedLoopCount > 1) {
3115 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3116 SemaRef.Diag(DSA.getConstructLoc(),
3117 diag::note_omp_collapse_ordered_expr)
3118 << 2 << CollapseLoopCountExpr->getSourceRange()
3119 << OrderedLoopCountExpr->getSourceRange();
3120 else if (CollapseLoopCountExpr)
3121 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3122 diag::note_omp_collapse_ordered_expr)
3123 << 0 << CollapseLoopCountExpr->getSourceRange();
3124 else
3125 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3126 diag::note_omp_collapse_ordered_expr)
3127 << 1 << OrderedLoopCountExpr->getSourceRange();
3128 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003129 return true;
3130 }
3131 assert(For->getBody());
3132
3133 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3134
3135 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003136 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003137 if (ISC.CheckInit(Init)) {
3138 return true;
3139 }
3140
3141 bool HasErrors = false;
3142
3143 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003144 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003145
3146 // OpenMP [2.6, Canonical Loop Form]
3147 // Var is one of the following:
3148 // A variable of signed or unsigned integer type.
3149 // For C++, a variable of a random access iterator type.
3150 // For C, a variable of a pointer type.
Alexey Bataeva8899172015-08-06 12:30:57 +00003151 auto VarType = Var->getType().getNonReferenceType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003152 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3153 !VarType->isPointerType() &&
3154 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3155 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3156 << SemaRef.getLangOpts().CPlusPlus;
3157 HasErrors = true;
3158 }
3159
Alexey Bataev4acb8592014-07-07 13:01:15 +00003160 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
3161 // Construct
3162 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3163 // parallel for construct is (are) private.
3164 // The loop iteration variable in the associated for-loop of a simd construct
3165 // with just one associated for-loop is linear with a constant-linear-step
3166 // that is the increment of the associated for-loop.
3167 // Exclude loop var from the list of variables with implicitly defined data
3168 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00003169 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003170
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003171 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
3172 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00003173 // The loop iteration variable in the associated for-loop of a simd construct
3174 // with just one associated for-loop may be listed in a linear clause with a
3175 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00003176 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3177 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003178 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003179 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
3180 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3181 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003182 auto PredeterminedCKind =
3183 isOpenMPSimdDirective(DKind)
3184 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3185 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003186 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00003187 DVar.CKind != OMPC_threadprivate && DVar.CKind != PredeterminedCKind) ||
Alexander Musmanf82886e2014-09-18 05:12:34 +00003188 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
3189 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00003190 DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_threadprivate)) &&
3191 ((DVar.CKind != OMPC_private && DVar.CKind != OMPC_threadprivate) ||
3192 DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003193 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00003194 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3195 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataevf2453a02015-05-06 07:25:08 +00003196 if (DVar.RefExpr == nullptr)
3197 DVar.CKind = PredeterminedCKind;
3198 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003199 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003200 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003201 // Make the loop iteration variable private (for worksharing constructs),
3202 // linear (for simd directives with the only one associated loop) or
Alexey Bataev10e775f2015-07-30 11:36:16 +00003203 // lastprivate (for simd directives with several collapsed or ordered
3204 // loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00003205 if (DVar.CKind == OMPC_unknown)
3206 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
3207 /*FromParent=*/false);
Alexey Bataev9c821032015-04-30 04:23:23 +00003208 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003209 }
3210
Alexey Bataev7ff55242014-06-19 09:13:45 +00003211 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00003212
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003213 // Check test-expr.
3214 HasErrors |= ISC.CheckCond(For->getCond());
3215
3216 // Check incr-expr.
3217 HasErrors |= ISC.CheckInc(For->getInc());
3218
Alexander Musmana5f070a2014-10-01 06:03:56 +00003219 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003220 return HasErrors;
3221
Alexander Musmana5f070a2014-10-01 06:03:56 +00003222 // Build the loop's iteration space representation.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003223 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
Alexander Musman174b3ca2014-10-06 11:16:29 +00003224 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
3225 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
Alexander Musmana5f070a2014-10-01 06:03:56 +00003226 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
Alexey Bataeva8899172015-08-06 12:30:57 +00003227 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003228 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3229 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3230 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3231 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3232 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3233 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3234
Alexey Bataev62dbb972015-04-22 11:59:37 +00003235 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3236 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003237 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003238 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003239 ResultIterSpace.CounterInit == nullptr ||
3240 ResultIterSpace.CounterStep == nullptr);
3241
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003242 return HasErrors;
3243}
3244
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003245/// \brief Build 'VarRef = Start.
3246static ExprResult BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc,
3247 ExprResult VarRef, ExprResult Start) {
3248 TransformToNewDefs Transform(SemaRef);
3249 // Build 'VarRef = Start.
3250 auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
3251 if (NewStart.isInvalid())
3252 return ExprError();
3253 NewStart = SemaRef.PerformImplicitConversion(
3254 NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
3255 Sema::AA_Converting,
3256 /*AllowExplicit=*/true);
3257 if (NewStart.isInvalid())
3258 return ExprError();
3259 NewStart = SemaRef.PerformImplicitConversion(
3260 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3261 /*AllowExplicit=*/true);
3262 if (!NewStart.isUsable())
3263 return ExprError();
3264
3265 auto Init =
3266 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3267 return Init;
3268}
3269
Alexander Musmana5f070a2014-10-01 06:03:56 +00003270/// \brief Build 'VarRef = Start + Iter * Step'.
3271static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
3272 SourceLocation Loc, ExprResult VarRef,
3273 ExprResult Start, ExprResult Iter,
3274 ExprResult Step, bool Subtract) {
3275 // Add parentheses (for debugging purposes only).
3276 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3277 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3278 !Step.isUsable())
3279 return ExprError();
3280
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003281 TransformToNewDefs Transform(SemaRef);
3282 auto NewStep = Transform.TransformExpr(Step.get()->IgnoreImplicit());
3283 if (NewStep.isInvalid())
3284 return ExprError();
3285 NewStep = SemaRef.PerformImplicitConversion(
3286 NewStep.get(), Step.get()->IgnoreImplicit()->getType(),
3287 Sema::AA_Converting,
3288 /*AllowExplicit=*/true);
3289 if (NewStep.isInvalid())
3290 return ExprError();
3291 ExprResult Update =
3292 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003293 if (!Update.isUsable())
3294 return ExprError();
3295
3296 // Build 'VarRef = Start + Iter * Step'.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003297 auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
3298 if (NewStart.isInvalid())
3299 return ExprError();
3300 NewStart = SemaRef.PerformImplicitConversion(
3301 NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
3302 Sema::AA_Converting,
3303 /*AllowExplicit=*/true);
3304 if (NewStart.isInvalid())
3305 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003306 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003307 NewStart.get(), Update.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003308 if (!Update.isUsable())
3309 return ExprError();
3310
3311 Update = SemaRef.PerformImplicitConversion(
3312 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3313 if (!Update.isUsable())
3314 return ExprError();
3315
3316 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3317 return Update;
3318}
3319
3320/// \brief Convert integer expression \a E to make it have at least \a Bits
3321/// bits.
3322static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
3323 Sema &SemaRef) {
3324 if (E == nullptr)
3325 return ExprError();
3326 auto &C = SemaRef.Context;
3327 QualType OldType = E->getType();
3328 unsigned HasBits = C.getTypeSize(OldType);
3329 if (HasBits >= Bits)
3330 return ExprResult(E);
3331 // OK to convert to signed, because new type has more bits than old.
3332 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3333 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3334 true);
3335}
3336
3337/// \brief Check if the given expression \a E is a constant integer that fits
3338/// into \a Bits bits.
3339static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3340 if (E == nullptr)
3341 return false;
3342 llvm::APSInt Result;
3343 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3344 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3345 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003346}
3347
3348/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003349/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3350/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003351static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003352CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3353 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3354 DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003355 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003356 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003357 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003358 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003359 // Found 'collapse' clause - calculate collapse number.
3360 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003361 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003362 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003363 }
3364 if (OrderedLoopCountExpr) {
3365 // Found 'ordered' clause - calculate collapse number.
3366 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003367 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3368 if (Result.getLimitedValue() < NestedLoopCount) {
3369 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3370 diag::err_omp_wrong_ordered_loop_count)
3371 << OrderedLoopCountExpr->getSourceRange();
3372 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3373 diag::note_collapse_loop_count)
3374 << CollapseLoopCountExpr->getSourceRange();
3375 }
3376 NestedLoopCount = Result.getLimitedValue();
3377 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003378 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003379 // This is helper routine for loop directives (e.g., 'for', 'simd',
3380 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00003381 SmallVector<LoopIterationSpace, 4> IterSpaces;
3382 IterSpaces.resize(NestedLoopCount);
3383 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003384 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003385 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003386 NestedLoopCount, CollapseLoopCountExpr,
3387 OrderedLoopCountExpr, VarsWithImplicitDSA,
3388 IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003389 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003390 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003391 // OpenMP [2.8.1, simd construct, Restrictions]
3392 // All loops associated with the construct must be perfectly nested; that
3393 // is, there must be no intervening code nor any OpenMP directive between
3394 // any two loops.
3395 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003396 }
3397
Alexander Musmana5f070a2014-10-01 06:03:56 +00003398 Built.clear(/* size */ NestedLoopCount);
3399
3400 if (SemaRef.CurContext->isDependentContext())
3401 return NestedLoopCount;
3402
3403 // An example of what is generated for the following code:
3404 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003405 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003406 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003407 // for (k = 0; k < NK; ++k)
3408 // for (j = J0; j < NJ; j+=2) {
3409 // <loop body>
3410 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003411 //
3412 // We generate the code below.
3413 // Note: the loop body may be outlined in CodeGen.
3414 // Note: some counters may be C++ classes, operator- is used to find number of
3415 // iterations and operator+= to calculate counter value.
3416 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3417 // or i64 is currently supported).
3418 //
3419 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3420 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3421 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3422 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3423 // // similar updates for vars in clauses (e.g. 'linear')
3424 // <loop body (using local i and j)>
3425 // }
3426 // i = NI; // assign final values of counters
3427 // j = NJ;
3428 //
3429
3430 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3431 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003432 // Precondition tests if there is at least one iteration (all conditions are
3433 // true).
3434 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003435 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003436 ExprResult LastIteration32 = WidenIterationCount(
3437 32 /* Bits */, SemaRef.PerformImplicitConversion(
3438 N0->IgnoreImpCasts(), N0->getType(),
3439 Sema::AA_Converting, /*AllowExplicit=*/true)
3440 .get(),
3441 SemaRef);
3442 ExprResult LastIteration64 = WidenIterationCount(
3443 64 /* Bits */, SemaRef.PerformImplicitConversion(
3444 N0->IgnoreImpCasts(), N0->getType(),
3445 Sema::AA_Converting, /*AllowExplicit=*/true)
3446 .get(),
3447 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003448
3449 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3450 return NestedLoopCount;
3451
3452 auto &C = SemaRef.Context;
3453 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3454
3455 Scope *CurScope = DSA.getCurScope();
3456 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003457 if (PreCond.isUsable()) {
3458 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
3459 PreCond.get(), IterSpaces[Cnt].PreCond);
3460 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003461 auto N = IterSpaces[Cnt].NumIterations;
3462 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3463 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003464 LastIteration32 = SemaRef.BuildBinOp(
3465 CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
3466 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3467 Sema::AA_Converting,
3468 /*AllowExplicit=*/true)
3469 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003470 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003471 LastIteration64 = SemaRef.BuildBinOp(
3472 CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
3473 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3474 Sema::AA_Converting,
3475 /*AllowExplicit=*/true)
3476 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003477 }
3478
3479 // Choose either the 32-bit or 64-bit version.
3480 ExprResult LastIteration = LastIteration64;
3481 if (LastIteration32.isUsable() &&
3482 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3483 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3484 FitsInto(
3485 32 /* Bits */,
3486 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3487 LastIteration64.get(), SemaRef)))
3488 LastIteration = LastIteration32;
3489
3490 if (!LastIteration.isUsable())
3491 return 0;
3492
3493 // Save the number of iterations.
3494 ExprResult NumIterations = LastIteration;
3495 {
3496 LastIteration = SemaRef.BuildBinOp(
3497 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
3498 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3499 if (!LastIteration.isUsable())
3500 return 0;
3501 }
3502
3503 // Calculate the last iteration number beforehand instead of doing this on
3504 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3505 llvm::APSInt Result;
3506 bool IsConstant =
3507 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3508 ExprResult CalcLastIteration;
3509 if (!IsConstant) {
3510 SourceLocation SaveLoc;
3511 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00003512 buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003513 ".omp.last.iteration");
Alexey Bataev39f915b82015-05-08 10:41:21 +00003514 ExprResult SaveRef = buildDeclRefExpr(
3515 SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003516 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
3517 SaveRef.get(), LastIteration.get());
3518 LastIteration = SaveRef;
3519
3520 // Prepare SaveRef + 1.
3521 NumIterations = SemaRef.BuildBinOp(
3522 CurScope, SaveLoc, BO_Add, SaveRef.get(),
3523 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3524 if (!NumIterations.isUsable())
3525 return 0;
3526 }
3527
3528 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3529
Alexander Musmanc6388682014-12-15 07:07:06 +00003530 QualType VType = LastIteration.get()->getType();
3531 // Build variables passed into runtime, nesessary for worksharing directives.
3532 ExprResult LB, UB, IL, ST, EUB;
3533 if (isOpenMPWorksharingDirective(DKind)) {
3534 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003535 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3536 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003537 SemaRef.AddInitializerToDecl(
3538 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3539 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3540
3541 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003542 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3543 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003544 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3545 /*DirectInit*/ false,
3546 /*TypeMayContainAuto*/ false);
3547
3548 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3549 // This will be used to implement clause 'lastprivate'.
3550 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00003551 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3552 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003553 SemaRef.AddInitializerToDecl(
3554 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3555 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3556
3557 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev39f915b82015-05-08 10:41:21 +00003558 VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
3559 ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003560 SemaRef.AddInitializerToDecl(
3561 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3562 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3563
3564 // Build expression: UB = min(UB, LastIteration)
3565 // It is nesessary for CodeGen of directives with static scheduling.
3566 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3567 UB.get(), LastIteration.get());
3568 ExprResult CondOp = SemaRef.ActOnConditionalOp(
3569 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
3570 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
3571 CondOp.get());
3572 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
3573 }
3574
3575 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003576 ExprResult IV;
3577 ExprResult Init;
3578 {
Alexey Bataev39f915b82015-05-08 10:41:21 +00003579 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
3580 IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003581 Expr *RHS = isOpenMPWorksharingDirective(DKind)
3582 ? LB.get()
3583 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
3584 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
3585 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003586 }
3587
Alexander Musmanc6388682014-12-15 07:07:06 +00003588 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003589 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00003590 ExprResult Cond =
3591 isOpenMPWorksharingDirective(DKind)
3592 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
3593 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
3594 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003595
3596 // Loop increment (IV = IV + 1)
3597 SourceLocation IncLoc;
3598 ExprResult Inc =
3599 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
3600 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
3601 if (!Inc.isUsable())
3602 return 0;
3603 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00003604 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
3605 if (!Inc.isUsable())
3606 return 0;
3607
3608 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
3609 // Used for directives with static scheduling.
3610 ExprResult NextLB, NextUB;
3611 if (isOpenMPWorksharingDirective(DKind)) {
3612 // LB + ST
3613 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
3614 if (!NextLB.isUsable())
3615 return 0;
3616 // LB = LB + ST
3617 NextLB =
3618 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
3619 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
3620 if (!NextLB.isUsable())
3621 return 0;
3622 // UB + ST
3623 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
3624 if (!NextUB.isUsable())
3625 return 0;
3626 // UB = UB + ST
3627 NextUB =
3628 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
3629 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
3630 if (!NextUB.isUsable())
3631 return 0;
3632 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003633
3634 // Build updates and final values of the loop counters.
3635 bool HasErrors = false;
3636 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003637 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003638 Built.Updates.resize(NestedLoopCount);
3639 Built.Finals.resize(NestedLoopCount);
3640 {
3641 ExprResult Div;
3642 // Go from inner nested loop to outer.
3643 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
3644 LoopIterationSpace &IS = IterSpaces[Cnt];
3645 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
3646 // Build: Iter = (IV / Div) % IS.NumIters
3647 // where Div is product of previous iterations' IS.NumIters.
3648 ExprResult Iter;
3649 if (Div.isUsable()) {
3650 Iter =
3651 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
3652 } else {
3653 Iter = IV;
3654 assert((Cnt == (int)NestedLoopCount - 1) &&
3655 "unusable div expected on first iteration only");
3656 }
3657
3658 if (Cnt != 0 && Iter.isUsable())
3659 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
3660 IS.NumIterations);
3661 if (!Iter.isUsable()) {
3662 HasErrors = true;
3663 break;
3664 }
3665
Alexey Bataev39f915b82015-05-08 10:41:21 +00003666 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
3667 auto *CounterVar = buildDeclRefExpr(
3668 SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
3669 IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
3670 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003671 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
3672 IS.CounterInit);
3673 if (!Init.isUsable()) {
3674 HasErrors = true;
3675 break;
3676 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003677 ExprResult Update =
Alexey Bataev39f915b82015-05-08 10:41:21 +00003678 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003679 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
3680 if (!Update.isUsable()) {
3681 HasErrors = true;
3682 break;
3683 }
3684
3685 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
3686 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00003687 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003688 IS.NumIterations, IS.CounterStep, IS.Subtract);
3689 if (!Final.isUsable()) {
3690 HasErrors = true;
3691 break;
3692 }
3693
3694 // Build Div for the next iteration: Div <- Div * IS.NumIters
3695 if (Cnt != 0) {
3696 if (Div.isUnset())
3697 Div = IS.NumIterations;
3698 else
3699 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
3700 IS.NumIterations);
3701
3702 // Add parentheses (for debugging purposes only).
3703 if (Div.isUsable())
3704 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
3705 if (!Div.isUsable()) {
3706 HasErrors = true;
3707 break;
3708 }
3709 }
3710 if (!Update.isUsable() || !Final.isUsable()) {
3711 HasErrors = true;
3712 break;
3713 }
3714 // Save results
3715 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00003716 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003717 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003718 Built.Updates[Cnt] = Update.get();
3719 Built.Finals[Cnt] = Final.get();
3720 }
3721 }
3722
3723 if (HasErrors)
3724 return 0;
3725
3726 // Save results
3727 Built.IterationVarRef = IV.get();
3728 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00003729 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003730 Built.CalcLastIteration =
3731 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003732 Built.PreCond = PreCond.get();
3733 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003734 Built.Init = Init.get();
3735 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00003736 Built.LB = LB.get();
3737 Built.UB = UB.get();
3738 Built.IL = IL.get();
3739 Built.ST = ST.get();
3740 Built.EUB = EUB.get();
3741 Built.NLB = NextLB.get();
3742 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003743
Alexey Bataevabfc0692014-06-25 06:52:00 +00003744 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003745}
3746
Alexey Bataev10e775f2015-07-30 11:36:16 +00003747static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003748 auto CollapseClauses =
3749 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
3750 if (CollapseClauses.begin() != CollapseClauses.end())
3751 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003752 return nullptr;
3753}
3754
Alexey Bataev10e775f2015-07-30 11:36:16 +00003755static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003756 auto OrderedClauses =
3757 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
3758 if (OrderedClauses.begin() != OrderedClauses.end())
3759 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003760 return nullptr;
3761}
3762
Alexey Bataev66b15b52015-08-21 11:14:16 +00003763static bool checkSimdlenSafelenValues(Sema &S, const Expr *Simdlen,
3764 const Expr *Safelen) {
3765 llvm::APSInt SimdlenRes, SafelenRes;
3766 if (Simdlen->isValueDependent() || Simdlen->isTypeDependent() ||
3767 Simdlen->isInstantiationDependent() ||
3768 Simdlen->containsUnexpandedParameterPack())
3769 return false;
3770 if (Safelen->isValueDependent() || Safelen->isTypeDependent() ||
3771 Safelen->isInstantiationDependent() ||
3772 Safelen->containsUnexpandedParameterPack())
3773 return false;
3774 Simdlen->EvaluateAsInt(SimdlenRes, S.Context);
3775 Safelen->EvaluateAsInt(SafelenRes, S.Context);
3776 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
3777 // If both simdlen and safelen clauses are specified, the value of the simdlen
3778 // parameter must be less than or equal to the value of the safelen parameter.
3779 if (SimdlenRes > SafelenRes) {
3780 S.Diag(Simdlen->getExprLoc(), diag::err_omp_wrong_simdlen_safelen_values)
3781 << Simdlen->getSourceRange() << Safelen->getSourceRange();
3782 return true;
3783 }
3784 return false;
3785}
3786
Alexey Bataev4acb8592014-07-07 13:01:15 +00003787StmtResult Sema::ActOnOpenMPSimdDirective(
3788 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3789 SourceLocation EndLoc,
3790 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003791 if (!AStmt)
3792 return StmtError();
3793
3794 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00003795 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003796 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
3797 // define the nested loops number.
3798 unsigned NestedLoopCount = CheckOpenMPLoop(
3799 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
3800 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003801 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003802 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003803
Alexander Musmana5f070a2014-10-01 06:03:56 +00003804 assert((CurContext->isDependentContext() || B.builtAll()) &&
3805 "omp simd loop exprs were not built");
3806
Alexander Musman3276a272015-03-21 10:12:56 +00003807 if (!CurContext->isDependentContext()) {
3808 // Finalize the clauses that need pre-built expressions for CodeGen.
3809 for (auto C : Clauses) {
3810 if (auto LC = dyn_cast<OMPLinearClause>(C))
3811 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3812 B.NumIterations, *this, CurScope))
3813 return StmtError();
3814 }
3815 }
3816
Alexey Bataev66b15b52015-08-21 11:14:16 +00003817 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
3818 // If both simdlen and safelen clauses are specified, the value of the simdlen
3819 // parameter must be less than or equal to the value of the safelen parameter.
3820 OMPSafelenClause *Safelen = nullptr;
3821 OMPSimdlenClause *Simdlen = nullptr;
3822 for (auto *Clause : Clauses) {
3823 if (Clause->getClauseKind() == OMPC_safelen)
3824 Safelen = cast<OMPSafelenClause>(Clause);
3825 else if (Clause->getClauseKind() == OMPC_simdlen)
3826 Simdlen = cast<OMPSimdlenClause>(Clause);
3827 if (Safelen && Simdlen)
3828 break;
3829 }
3830 if (Simdlen && Safelen &&
3831 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
3832 Safelen->getSafelen()))
3833 return StmtError();
3834
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003835 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003836 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3837 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003838}
3839
Alexey Bataev4acb8592014-07-07 13:01:15 +00003840StmtResult Sema::ActOnOpenMPForDirective(
3841 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3842 SourceLocation EndLoc,
3843 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003844 if (!AStmt)
3845 return StmtError();
3846
3847 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00003848 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003849 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
3850 // define the nested loops number.
3851 unsigned NestedLoopCount = CheckOpenMPLoop(
3852 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
3853 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003854 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00003855 return StmtError();
3856
Alexander Musmana5f070a2014-10-01 06:03:56 +00003857 assert((CurContext->isDependentContext() || B.builtAll()) &&
3858 "omp for loop exprs were not built");
3859
Alexey Bataev54acd402015-08-04 11:18:19 +00003860 if (!CurContext->isDependentContext()) {
3861 // Finalize the clauses that need pre-built expressions for CodeGen.
3862 for (auto C : Clauses) {
3863 if (auto LC = dyn_cast<OMPLinearClause>(C))
3864 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3865 B.NumIterations, *this, CurScope))
3866 return StmtError();
3867 }
3868 }
3869
Alexey Bataevf29276e2014-06-18 04:14:57 +00003870 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003871 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003872 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00003873}
3874
Alexander Musmanf82886e2014-09-18 05:12:34 +00003875StmtResult Sema::ActOnOpenMPForSimdDirective(
3876 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3877 SourceLocation EndLoc,
3878 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003879 if (!AStmt)
3880 return StmtError();
3881
3882 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00003883 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003884 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
3885 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00003886 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00003887 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
3888 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
3889 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003890 if (NestedLoopCount == 0)
3891 return StmtError();
3892
Alexander Musmanc6388682014-12-15 07:07:06 +00003893 assert((CurContext->isDependentContext() || B.builtAll()) &&
3894 "omp for simd loop exprs were not built");
3895
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00003896 if (!CurContext->isDependentContext()) {
3897 // Finalize the clauses that need pre-built expressions for CodeGen.
3898 for (auto C : Clauses) {
3899 if (auto LC = dyn_cast<OMPLinearClause>(C))
3900 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3901 B.NumIterations, *this, CurScope))
3902 return StmtError();
3903 }
3904 }
3905
Alexey Bataev66b15b52015-08-21 11:14:16 +00003906 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
3907 // If both simdlen and safelen clauses are specified, the value of the simdlen
3908 // parameter must be less than or equal to the value of the safelen parameter.
3909 OMPSafelenClause *Safelen = nullptr;
3910 OMPSimdlenClause *Simdlen = nullptr;
3911 for (auto *Clause : Clauses) {
3912 if (Clause->getClauseKind() == OMPC_safelen)
3913 Safelen = cast<OMPSafelenClause>(Clause);
3914 else if (Clause->getClauseKind() == OMPC_simdlen)
3915 Simdlen = cast<OMPSimdlenClause>(Clause);
3916 if (Safelen && Simdlen)
3917 break;
3918 }
3919 if (Simdlen && Safelen &&
3920 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
3921 Safelen->getSafelen()))
3922 return StmtError();
3923
Alexander Musmanf82886e2014-09-18 05:12:34 +00003924 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003925 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3926 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003927}
3928
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003929StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3930 Stmt *AStmt,
3931 SourceLocation StartLoc,
3932 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003933 if (!AStmt)
3934 return StmtError();
3935
3936 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003937 auto BaseStmt = AStmt;
3938 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3939 BaseStmt = CS->getCapturedStmt();
3940 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3941 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00003942 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003943 return StmtError();
3944 // All associated statements must be '#pragma omp section' except for
3945 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00003946 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003947 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3948 if (SectionStmt)
3949 Diag(SectionStmt->getLocStart(),
3950 diag::err_omp_sections_substmt_not_section);
3951 return StmtError();
3952 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00003953 cast<OMPSectionDirective>(SectionStmt)
3954 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003955 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003956 } else {
3957 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3958 return StmtError();
3959 }
3960
3961 getCurFunction()->setHasBranchProtectedScope();
3962
Alexey Bataev25e5b442015-09-15 12:52:43 +00003963 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3964 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003965}
3966
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003967StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3968 SourceLocation StartLoc,
3969 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003970 if (!AStmt)
3971 return StmtError();
3972
3973 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003974
3975 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00003976 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003977
Alexey Bataev25e5b442015-09-15 12:52:43 +00003978 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
3979 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003980}
3981
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003982StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3983 Stmt *AStmt,
3984 SourceLocation StartLoc,
3985 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003986 if (!AStmt)
3987 return StmtError();
3988
3989 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00003990
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003991 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00003992
Alexey Bataev3255bf32015-01-19 05:20:46 +00003993 // OpenMP [2.7.3, single Construct, Restrictions]
3994 // The copyprivate clause must not be used with the nowait clause.
3995 OMPClause *Nowait = nullptr;
3996 OMPClause *Copyprivate = nullptr;
3997 for (auto *Clause : Clauses) {
3998 if (Clause->getClauseKind() == OMPC_nowait)
3999 Nowait = Clause;
4000 else if (Clause->getClauseKind() == OMPC_copyprivate)
4001 Copyprivate = Clause;
4002 if (Copyprivate && Nowait) {
4003 Diag(Copyprivate->getLocStart(),
4004 diag::err_omp_single_copyprivate_with_nowait);
4005 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4006 return StmtError();
4007 }
4008 }
4009
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004010 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4011}
4012
Alexander Musman80c22892014-07-17 08:54:58 +00004013StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4014 SourceLocation StartLoc,
4015 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004016 if (!AStmt)
4017 return StmtError();
4018
4019 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004020
4021 getCurFunction()->setHasBranchProtectedScope();
4022
4023 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4024}
4025
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004026StmtResult
4027Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
4028 Stmt *AStmt, SourceLocation StartLoc,
4029 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004030 if (!AStmt)
4031 return StmtError();
4032
4033 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004034
4035 getCurFunction()->setHasBranchProtectedScope();
4036
4037 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4038 AStmt);
4039}
4040
Alexey Bataev4acb8592014-07-07 13:01:15 +00004041StmtResult Sema::ActOnOpenMPParallelForDirective(
4042 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4043 SourceLocation EndLoc,
4044 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004045 if (!AStmt)
4046 return StmtError();
4047
Alexey Bataev4acb8592014-07-07 13:01:15 +00004048 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4049 // 1.2.2 OpenMP Language Terminology
4050 // Structured block - An executable statement with a single entry at the
4051 // top and a single exit at the bottom.
4052 // The point of exit cannot be a branch out of the structured block.
4053 // longjmp() and throw() must not violate the entry/exit criteria.
4054 CS->getCapturedDecl()->setNothrow();
4055
Alexander Musmanc6388682014-12-15 07:07:06 +00004056 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004057 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4058 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004059 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004060 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4061 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4062 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004063 if (NestedLoopCount == 0)
4064 return StmtError();
4065
Alexander Musmana5f070a2014-10-01 06:03:56 +00004066 assert((CurContext->isDependentContext() || B.builtAll()) &&
4067 "omp parallel for loop exprs were not built");
4068
Alexey Bataev54acd402015-08-04 11:18:19 +00004069 if (!CurContext->isDependentContext()) {
4070 // Finalize the clauses that need pre-built expressions for CodeGen.
4071 for (auto C : Clauses) {
4072 if (auto LC = dyn_cast<OMPLinearClause>(C))
4073 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4074 B.NumIterations, *this, CurScope))
4075 return StmtError();
4076 }
4077 }
4078
Alexey Bataev4acb8592014-07-07 13:01:15 +00004079 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004080 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004081 NestedLoopCount, Clauses, AStmt, B,
4082 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004083}
4084
Alexander Musmane4e893b2014-09-23 09:33:00 +00004085StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4086 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4087 SourceLocation EndLoc,
4088 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004089 if (!AStmt)
4090 return StmtError();
4091
Alexander Musmane4e893b2014-09-23 09:33:00 +00004092 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4093 // 1.2.2 OpenMP Language Terminology
4094 // Structured block - An executable statement with a single entry at the
4095 // top and a single exit at the bottom.
4096 // The point of exit cannot be a branch out of the structured block.
4097 // longjmp() and throw() must not violate the entry/exit criteria.
4098 CS->getCapturedDecl()->setNothrow();
4099
Alexander Musmanc6388682014-12-15 07:07:06 +00004100 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004101 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4102 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004103 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004104 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4105 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4106 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004107 if (NestedLoopCount == 0)
4108 return StmtError();
4109
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004110 if (!CurContext->isDependentContext()) {
4111 // Finalize the clauses that need pre-built expressions for CodeGen.
4112 for (auto C : Clauses) {
4113 if (auto LC = dyn_cast<OMPLinearClause>(C))
4114 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4115 B.NumIterations, *this, CurScope))
4116 return StmtError();
4117 }
4118 }
4119
Alexey Bataev66b15b52015-08-21 11:14:16 +00004120 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4121 // If both simdlen and safelen clauses are specified, the value of the simdlen
4122 // parameter must be less than or equal to the value of the safelen parameter.
4123 OMPSafelenClause *Safelen = nullptr;
4124 OMPSimdlenClause *Simdlen = nullptr;
4125 for (auto *Clause : Clauses) {
4126 if (Clause->getClauseKind() == OMPC_safelen)
4127 Safelen = cast<OMPSafelenClause>(Clause);
4128 else if (Clause->getClauseKind() == OMPC_simdlen)
4129 Simdlen = cast<OMPSimdlenClause>(Clause);
4130 if (Safelen && Simdlen)
4131 break;
4132 }
4133 if (Simdlen && Safelen &&
4134 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
4135 Safelen->getSafelen()))
4136 return StmtError();
4137
Alexander Musmane4e893b2014-09-23 09:33:00 +00004138 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004139 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004140 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004141}
4142
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004143StmtResult
4144Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4145 Stmt *AStmt, SourceLocation StartLoc,
4146 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004147 if (!AStmt)
4148 return StmtError();
4149
4150 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004151 auto BaseStmt = AStmt;
4152 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4153 BaseStmt = CS->getCapturedStmt();
4154 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4155 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004156 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004157 return StmtError();
4158 // All associated statements must be '#pragma omp section' except for
4159 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004160 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004161 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4162 if (SectionStmt)
4163 Diag(SectionStmt->getLocStart(),
4164 diag::err_omp_parallel_sections_substmt_not_section);
4165 return StmtError();
4166 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004167 cast<OMPSectionDirective>(SectionStmt)
4168 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004169 }
4170 } else {
4171 Diag(AStmt->getLocStart(),
4172 diag::err_omp_parallel_sections_not_compound_stmt);
4173 return StmtError();
4174 }
4175
4176 getCurFunction()->setHasBranchProtectedScope();
4177
Alexey Bataev25e5b442015-09-15 12:52:43 +00004178 return OMPParallelSectionsDirective::Create(
4179 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004180}
4181
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004182StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4183 Stmt *AStmt, SourceLocation StartLoc,
4184 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004185 if (!AStmt)
4186 return StmtError();
4187
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004188 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4189 // 1.2.2 OpenMP Language Terminology
4190 // Structured block - An executable statement with a single entry at the
4191 // top and a single exit at the bottom.
4192 // The point of exit cannot be a branch out of the structured block.
4193 // longjmp() and throw() must not violate the entry/exit criteria.
4194 CS->getCapturedDecl()->setNothrow();
4195
4196 getCurFunction()->setHasBranchProtectedScope();
4197
Alexey Bataev25e5b442015-09-15 12:52:43 +00004198 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4199 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004200}
4201
Alexey Bataev68446b72014-07-18 07:47:19 +00004202StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4203 SourceLocation EndLoc) {
4204 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4205}
4206
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004207StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4208 SourceLocation EndLoc) {
4209 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4210}
4211
Alexey Bataev2df347a2014-07-18 10:17:07 +00004212StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4213 SourceLocation EndLoc) {
4214 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4215}
4216
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004217StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4218 SourceLocation StartLoc,
4219 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004220 if (!AStmt)
4221 return StmtError();
4222
4223 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004224
4225 getCurFunction()->setHasBranchProtectedScope();
4226
4227 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4228}
4229
Alexey Bataev6125da92014-07-21 11:26:11 +00004230StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4231 SourceLocation StartLoc,
4232 SourceLocation EndLoc) {
4233 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4234 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4235}
4236
Alexey Bataev346265e2015-09-25 10:37:12 +00004237StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4238 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004239 SourceLocation StartLoc,
4240 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004241 if (!AStmt)
4242 return StmtError();
4243
4244 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004245
4246 getCurFunction()->setHasBranchProtectedScope();
4247
Alexey Bataev346265e2015-09-25 10:37:12 +00004248 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004249 OMPSIMDClause *SC = nullptr;
Alexey Bataev346265e2015-09-25 10:37:12 +00004250 for (auto *C: Clauses) {
4251 if (C->getClauseKind() == OMPC_threads)
4252 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004253 else if (C->getClauseKind() == OMPC_simd)
4254 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004255 }
4256
4257 // TODO: this must happen only if 'threads' clause specified or if no clauses
4258 // is specified.
4259 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4260 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4261 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) << (TC != nullptr);
4262 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4263 return StmtError();
4264 }
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004265 if (!SC && isOpenMPSimdDirective(DSAStack->getParentDirective())) {
4266 // OpenMP [2.8.1,simd Construct, Restrictions]
4267 // An ordered construct with the simd clause is the only OpenMP construct
4268 // that can appear in the simd region.
4269 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
4270 return StmtError();
4271 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004272
4273 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004274}
4275
Alexey Bataev1d160b12015-03-13 12:27:31 +00004276namespace {
4277/// \brief Helper class for checking expression in 'omp atomic [update]'
4278/// construct.
4279class OpenMPAtomicUpdateChecker {
4280 /// \brief Error results for atomic update expressions.
4281 enum ExprAnalysisErrorCode {
4282 /// \brief A statement is not an expression statement.
4283 NotAnExpression,
4284 /// \brief Expression is not builtin binary or unary operation.
4285 NotABinaryOrUnaryExpression,
4286 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4287 NotAnUnaryIncDecExpression,
4288 /// \brief An expression is not of scalar type.
4289 NotAScalarType,
4290 /// \brief A binary operation is not an assignment operation.
4291 NotAnAssignmentOp,
4292 /// \brief RHS part of the binary operation is not a binary expression.
4293 NotABinaryExpression,
4294 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4295 /// expression.
4296 NotABinaryOperator,
4297 /// \brief RHS binary operation does not have reference to the updated LHS
4298 /// part.
4299 NotAnUpdateExpression,
4300 /// \brief No errors is found.
4301 NoError
4302 };
4303 /// \brief Reference to Sema.
4304 Sema &SemaRef;
4305 /// \brief A location for note diagnostics (when error is found).
4306 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004307 /// \brief 'x' lvalue part of the source atomic expression.
4308 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004309 /// \brief 'expr' rvalue part of the source atomic expression.
4310 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004311 /// \brief Helper expression of the form
4312 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4313 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4314 Expr *UpdateExpr;
4315 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4316 /// important for non-associative operations.
4317 bool IsXLHSInRHSPart;
4318 BinaryOperatorKind Op;
4319 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004320 /// \brief true if the source expression is a postfix unary operation, false
4321 /// if it is a prefix unary operation.
4322 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004323
4324public:
4325 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00004326 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00004327 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00004328 /// \brief Check specified statement that it is suitable for 'atomic update'
4329 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00004330 /// expression. If DiagId and NoteId == 0, then only check is performed
4331 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00004332 /// \param DiagId Diagnostic which should be emitted if error is found.
4333 /// \param NoteId Diagnostic note for the main error message.
4334 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00004335 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004336 /// \brief Return the 'x' lvalue part of the source atomic expression.
4337 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00004338 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4339 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00004340 /// \brief Return the update expression used in calculation of the updated
4341 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4342 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4343 Expr *getUpdateExpr() const { return UpdateExpr; }
4344 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4345 /// false otherwise.
4346 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4347
Alexey Bataevb78ca832015-04-01 03:33:17 +00004348 /// \brief true if the source expression is a postfix unary operation, false
4349 /// if it is a prefix unary operation.
4350 bool isPostfixUpdate() const { return IsPostfixUpdate; }
4351
Alexey Bataev1d160b12015-03-13 12:27:31 +00004352private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00004353 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4354 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004355};
4356} // namespace
4357
4358bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4359 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4360 ExprAnalysisErrorCode ErrorFound = NoError;
4361 SourceLocation ErrorLoc, NoteLoc;
4362 SourceRange ErrorRange, NoteRange;
4363 // Allowed constructs are:
4364 // x = x binop expr;
4365 // x = expr binop x;
4366 if (AtomicBinOp->getOpcode() == BO_Assign) {
4367 X = AtomicBinOp->getLHS();
4368 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4369 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4370 if (AtomicInnerBinOp->isMultiplicativeOp() ||
4371 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4372 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00004373 Op = AtomicInnerBinOp->getOpcode();
4374 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004375 auto *LHS = AtomicInnerBinOp->getLHS();
4376 auto *RHS = AtomicInnerBinOp->getRHS();
4377 llvm::FoldingSetNodeID XId, LHSId, RHSId;
4378 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4379 /*Canonical=*/true);
4380 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4381 /*Canonical=*/true);
4382 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4383 /*Canonical=*/true);
4384 if (XId == LHSId) {
4385 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004386 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004387 } else if (XId == RHSId) {
4388 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004389 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004390 } else {
4391 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4392 ErrorRange = AtomicInnerBinOp->getSourceRange();
4393 NoteLoc = X->getExprLoc();
4394 NoteRange = X->getSourceRange();
4395 ErrorFound = NotAnUpdateExpression;
4396 }
4397 } else {
4398 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4399 ErrorRange = AtomicInnerBinOp->getSourceRange();
4400 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4401 NoteRange = SourceRange(NoteLoc, NoteLoc);
4402 ErrorFound = NotABinaryOperator;
4403 }
4404 } else {
4405 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4406 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4407 ErrorFound = NotABinaryExpression;
4408 }
4409 } else {
4410 ErrorLoc = AtomicBinOp->getExprLoc();
4411 ErrorRange = AtomicBinOp->getSourceRange();
4412 NoteLoc = AtomicBinOp->getOperatorLoc();
4413 NoteRange = SourceRange(NoteLoc, NoteLoc);
4414 ErrorFound = NotAnAssignmentOp;
4415 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004416 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004417 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4418 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4419 return true;
4420 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00004421 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004422 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004423}
4424
4425bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
4426 unsigned NoteId) {
4427 ExprAnalysisErrorCode ErrorFound = NoError;
4428 SourceLocation ErrorLoc, NoteLoc;
4429 SourceRange ErrorRange, NoteRange;
4430 // Allowed constructs are:
4431 // x++;
4432 // x--;
4433 // ++x;
4434 // --x;
4435 // x binop= expr;
4436 // x = x binop expr;
4437 // x = expr binop x;
4438 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
4439 AtomicBody = AtomicBody->IgnoreParenImpCasts();
4440 if (AtomicBody->getType()->isScalarType() ||
4441 AtomicBody->isInstantiationDependent()) {
4442 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
4443 AtomicBody->IgnoreParenImpCasts())) {
4444 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00004445 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00004446 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00004447 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004448 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004449 X = AtomicCompAssignOp->getLHS();
4450 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004451 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
4452 AtomicBody->IgnoreParenImpCasts())) {
4453 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00004454 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
4455 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004456 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00004457 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
4458 // Check for Unary Operation
4459 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004460 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004461 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
4462 OpLoc = AtomicUnaryOp->getOperatorLoc();
4463 X = AtomicUnaryOp->getSubExpr();
4464 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
4465 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004466 } else {
4467 ErrorFound = NotAnUnaryIncDecExpression;
4468 ErrorLoc = AtomicUnaryOp->getExprLoc();
4469 ErrorRange = AtomicUnaryOp->getSourceRange();
4470 NoteLoc = AtomicUnaryOp->getOperatorLoc();
4471 NoteRange = SourceRange(NoteLoc, NoteLoc);
4472 }
Alexey Bataev5a195472015-09-04 12:55:50 +00004473 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004474 ErrorFound = NotABinaryOrUnaryExpression;
4475 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
4476 NoteRange = ErrorRange = AtomicBody->getSourceRange();
4477 }
4478 } else {
4479 ErrorFound = NotAScalarType;
4480 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
4481 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4482 }
4483 } else {
4484 ErrorFound = NotAnExpression;
4485 NoteLoc = ErrorLoc = S->getLocStart();
4486 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4487 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004488 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004489 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4490 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4491 return true;
4492 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00004493 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004494 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00004495 // Build an update expression of form 'OpaqueValueExpr(x) binop
4496 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
4497 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
4498 auto *OVEX = new (SemaRef.getASTContext())
4499 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
4500 auto *OVEExpr = new (SemaRef.getASTContext())
4501 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
4502 auto Update =
4503 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
4504 IsXLHSInRHSPart ? OVEExpr : OVEX);
4505 if (Update.isInvalid())
4506 return true;
4507 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
4508 Sema::AA_Casting);
4509 if (Update.isInvalid())
4510 return true;
4511 UpdateExpr = Update.get();
4512 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00004513 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004514}
4515
Alexey Bataev0162e452014-07-22 10:10:35 +00004516StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
4517 Stmt *AStmt,
4518 SourceLocation StartLoc,
4519 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004520 if (!AStmt)
4521 return StmtError();
4522
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004523 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00004524 // 1.2.2 OpenMP Language Terminology
4525 // Structured block - An executable statement with a single entry at the
4526 // top and a single exit at the bottom.
4527 // The point of exit cannot be a branch out of the structured block.
4528 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00004529 OpenMPClauseKind AtomicKind = OMPC_unknown;
4530 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004531 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00004532 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00004533 C->getClauseKind() == OMPC_update ||
4534 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00004535 if (AtomicKind != OMPC_unknown) {
4536 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
4537 << SourceRange(C->getLocStart(), C->getLocEnd());
4538 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
4539 << getOpenMPClauseName(AtomicKind);
4540 } else {
4541 AtomicKind = C->getClauseKind();
4542 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004543 }
4544 }
4545 }
Alexey Bataev62cec442014-11-18 10:14:22 +00004546
Alexey Bataev459dec02014-07-24 06:46:57 +00004547 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00004548 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
4549 Body = EWC->getSubExpr();
4550
Alexey Bataev62cec442014-11-18 10:14:22 +00004551 Expr *X = nullptr;
4552 Expr *V = nullptr;
4553 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004554 Expr *UE = nullptr;
4555 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004556 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00004557 // OpenMP [2.12.6, atomic Construct]
4558 // In the next expressions:
4559 // * x and v (as applicable) are both l-value expressions with scalar type.
4560 // * During the execution of an atomic region, multiple syntactic
4561 // occurrences of x must designate the same storage location.
4562 // * Neither of v and expr (as applicable) may access the storage location
4563 // designated by x.
4564 // * Neither of x and expr (as applicable) may access the storage location
4565 // designated by v.
4566 // * expr is an expression with scalar type.
4567 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
4568 // * binop, binop=, ++, and -- are not overloaded operators.
4569 // * The expression x binop expr must be numerically equivalent to x binop
4570 // (expr). This requirement is satisfied if the operators in expr have
4571 // precedence greater than binop, or by using parentheses around expr or
4572 // subexpressions of expr.
4573 // * The expression expr binop x must be numerically equivalent to (expr)
4574 // binop x. This requirement is satisfied if the operators in expr have
4575 // precedence equal to or greater than binop, or by using parentheses around
4576 // expr or subexpressions of expr.
4577 // * For forms that allow multiple occurrences of x, the number of times
4578 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00004579 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004580 enum {
4581 NotAnExpression,
4582 NotAnAssignmentOp,
4583 NotAScalarType,
4584 NotAnLValue,
4585 NoError
4586 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00004587 SourceLocation ErrorLoc, NoteLoc;
4588 SourceRange ErrorRange, NoteRange;
4589 // If clause is read:
4590 // v = x;
4591 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
4592 auto AtomicBinOp =
4593 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4594 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
4595 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
4596 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
4597 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
4598 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
4599 if (!X->isLValue() || !V->isLValue()) {
4600 auto NotLValueExpr = X->isLValue() ? V : X;
4601 ErrorFound = NotAnLValue;
4602 ErrorLoc = AtomicBinOp->getExprLoc();
4603 ErrorRange = AtomicBinOp->getSourceRange();
4604 NoteLoc = NotLValueExpr->getExprLoc();
4605 NoteRange = NotLValueExpr->getSourceRange();
4606 }
4607 } else if (!X->isInstantiationDependent() ||
4608 !V->isInstantiationDependent()) {
4609 auto NotScalarExpr =
4610 (X->isInstantiationDependent() || X->getType()->isScalarType())
4611 ? V
4612 : X;
4613 ErrorFound = NotAScalarType;
4614 ErrorLoc = AtomicBinOp->getExprLoc();
4615 ErrorRange = AtomicBinOp->getSourceRange();
4616 NoteLoc = NotScalarExpr->getExprLoc();
4617 NoteRange = NotScalarExpr->getSourceRange();
4618 }
Alexey Bataev5a195472015-09-04 12:55:50 +00004619 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00004620 ErrorFound = NotAnAssignmentOp;
4621 ErrorLoc = AtomicBody->getExprLoc();
4622 ErrorRange = AtomicBody->getSourceRange();
4623 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4624 : AtomicBody->getExprLoc();
4625 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4626 : AtomicBody->getSourceRange();
4627 }
4628 } else {
4629 ErrorFound = NotAnExpression;
4630 NoteLoc = ErrorLoc = Body->getLocStart();
4631 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00004632 }
Alexey Bataev62cec442014-11-18 10:14:22 +00004633 if (ErrorFound != NoError) {
4634 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
4635 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00004636 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
4637 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00004638 return StmtError();
4639 } else if (CurContext->isDependentContext())
4640 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00004641 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004642 enum {
4643 NotAnExpression,
4644 NotAnAssignmentOp,
4645 NotAScalarType,
4646 NotAnLValue,
4647 NoError
4648 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00004649 SourceLocation ErrorLoc, NoteLoc;
4650 SourceRange ErrorRange, NoteRange;
4651 // If clause is write:
4652 // x = expr;
4653 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
4654 auto AtomicBinOp =
4655 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4656 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00004657 X = AtomicBinOp->getLHS();
4658 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00004659 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
4660 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
4661 if (!X->isLValue()) {
4662 ErrorFound = NotAnLValue;
4663 ErrorLoc = AtomicBinOp->getExprLoc();
4664 ErrorRange = AtomicBinOp->getSourceRange();
4665 NoteLoc = X->getExprLoc();
4666 NoteRange = X->getSourceRange();
4667 }
4668 } else if (!X->isInstantiationDependent() ||
4669 !E->isInstantiationDependent()) {
4670 auto NotScalarExpr =
4671 (X->isInstantiationDependent() || X->getType()->isScalarType())
4672 ? E
4673 : X;
4674 ErrorFound = NotAScalarType;
4675 ErrorLoc = AtomicBinOp->getExprLoc();
4676 ErrorRange = AtomicBinOp->getSourceRange();
4677 NoteLoc = NotScalarExpr->getExprLoc();
4678 NoteRange = NotScalarExpr->getSourceRange();
4679 }
Alexey Bataev5a195472015-09-04 12:55:50 +00004680 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00004681 ErrorFound = NotAnAssignmentOp;
4682 ErrorLoc = AtomicBody->getExprLoc();
4683 ErrorRange = AtomicBody->getSourceRange();
4684 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4685 : AtomicBody->getExprLoc();
4686 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4687 : AtomicBody->getSourceRange();
4688 }
4689 } else {
4690 ErrorFound = NotAnExpression;
4691 NoteLoc = ErrorLoc = Body->getLocStart();
4692 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00004693 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00004694 if (ErrorFound != NoError) {
4695 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
4696 << ErrorRange;
4697 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
4698 << NoteRange;
4699 return StmtError();
4700 } else if (CurContext->isDependentContext())
4701 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004702 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004703 // If clause is update:
4704 // x++;
4705 // x--;
4706 // ++x;
4707 // --x;
4708 // x binop= expr;
4709 // x = x binop expr;
4710 // x = expr binop x;
4711 OpenMPAtomicUpdateChecker Checker(*this);
4712 if (Checker.checkStatement(
4713 Body, (AtomicKind == OMPC_update)
4714 ? diag::err_omp_atomic_update_not_expression_statement
4715 : diag::err_omp_atomic_not_expression_statement,
4716 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00004717 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004718 if (!CurContext->isDependentContext()) {
4719 E = Checker.getExpr();
4720 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004721 UE = Checker.getUpdateExpr();
4722 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00004723 }
Alexey Bataev459dec02014-07-24 06:46:57 +00004724 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004725 enum {
4726 NotAnAssignmentOp,
4727 NotACompoundStatement,
4728 NotTwoSubstatements,
4729 NotASpecificExpression,
4730 NoError
4731 } ErrorFound = NoError;
4732 SourceLocation ErrorLoc, NoteLoc;
4733 SourceRange ErrorRange, NoteRange;
4734 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
4735 // If clause is a capture:
4736 // v = x++;
4737 // v = x--;
4738 // v = ++x;
4739 // v = --x;
4740 // v = x binop= expr;
4741 // v = x = x binop expr;
4742 // v = x = expr binop x;
4743 auto *AtomicBinOp =
4744 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4745 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
4746 V = AtomicBinOp->getLHS();
4747 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
4748 OpenMPAtomicUpdateChecker Checker(*this);
4749 if (Checker.checkStatement(
4750 Body, diag::err_omp_atomic_capture_not_expression_statement,
4751 diag::note_omp_atomic_update))
4752 return StmtError();
4753 E = Checker.getExpr();
4754 X = Checker.getX();
4755 UE = Checker.getUpdateExpr();
4756 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4757 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00004758 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004759 ErrorLoc = AtomicBody->getExprLoc();
4760 ErrorRange = AtomicBody->getSourceRange();
4761 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4762 : AtomicBody->getExprLoc();
4763 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4764 : AtomicBody->getSourceRange();
4765 ErrorFound = NotAnAssignmentOp;
4766 }
4767 if (ErrorFound != NoError) {
4768 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
4769 << ErrorRange;
4770 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4771 return StmtError();
4772 } else if (CurContext->isDependentContext()) {
4773 UE = V = E = X = nullptr;
4774 }
4775 } else {
4776 // If clause is a capture:
4777 // { v = x; x = expr; }
4778 // { v = x; x++; }
4779 // { v = x; x--; }
4780 // { v = x; ++x; }
4781 // { v = x; --x; }
4782 // { v = x; x binop= expr; }
4783 // { v = x; x = x binop expr; }
4784 // { v = x; x = expr binop x; }
4785 // { x++; v = x; }
4786 // { x--; v = x; }
4787 // { ++x; v = x; }
4788 // { --x; v = x; }
4789 // { x binop= expr; v = x; }
4790 // { x = x binop expr; v = x; }
4791 // { x = expr binop x; v = x; }
4792 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
4793 // Check that this is { expr1; expr2; }
4794 if (CS->size() == 2) {
4795 auto *First = CS->body_front();
4796 auto *Second = CS->body_back();
4797 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
4798 First = EWC->getSubExpr()->IgnoreParenImpCasts();
4799 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
4800 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
4801 // Need to find what subexpression is 'v' and what is 'x'.
4802 OpenMPAtomicUpdateChecker Checker(*this);
4803 bool IsUpdateExprFound = !Checker.checkStatement(Second);
4804 BinaryOperator *BinOp = nullptr;
4805 if (IsUpdateExprFound) {
4806 BinOp = dyn_cast<BinaryOperator>(First);
4807 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4808 }
4809 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4810 // { v = x; x++; }
4811 // { v = x; x--; }
4812 // { v = x; ++x; }
4813 // { v = x; --x; }
4814 // { v = x; x binop= expr; }
4815 // { v = x; x = x binop expr; }
4816 // { v = x; x = expr binop x; }
4817 // Check that the first expression has form v = x.
4818 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4819 llvm::FoldingSetNodeID XId, PossibleXId;
4820 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4821 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4822 IsUpdateExprFound = XId == PossibleXId;
4823 if (IsUpdateExprFound) {
4824 V = BinOp->getLHS();
4825 X = Checker.getX();
4826 E = Checker.getExpr();
4827 UE = Checker.getUpdateExpr();
4828 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00004829 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004830 }
4831 }
4832 if (!IsUpdateExprFound) {
4833 IsUpdateExprFound = !Checker.checkStatement(First);
4834 BinOp = nullptr;
4835 if (IsUpdateExprFound) {
4836 BinOp = dyn_cast<BinaryOperator>(Second);
4837 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4838 }
4839 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4840 // { x++; v = x; }
4841 // { x--; v = x; }
4842 // { ++x; v = x; }
4843 // { --x; v = x; }
4844 // { x binop= expr; v = x; }
4845 // { x = x binop expr; v = x; }
4846 // { x = expr binop x; v = x; }
4847 // Check that the second expression has form v = x.
4848 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4849 llvm::FoldingSetNodeID XId, PossibleXId;
4850 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4851 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4852 IsUpdateExprFound = XId == PossibleXId;
4853 if (IsUpdateExprFound) {
4854 V = BinOp->getLHS();
4855 X = Checker.getX();
4856 E = Checker.getExpr();
4857 UE = Checker.getUpdateExpr();
4858 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00004859 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004860 }
4861 }
4862 }
4863 if (!IsUpdateExprFound) {
4864 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00004865 auto *FirstExpr = dyn_cast<Expr>(First);
4866 auto *SecondExpr = dyn_cast<Expr>(Second);
4867 if (!FirstExpr || !SecondExpr ||
4868 !(FirstExpr->isInstantiationDependent() ||
4869 SecondExpr->isInstantiationDependent())) {
4870 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
4871 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004872 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00004873 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
4874 : First->getLocStart();
4875 NoteRange = ErrorRange = FirstBinOp
4876 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00004877 : SourceRange(ErrorLoc, ErrorLoc);
4878 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00004879 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
4880 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
4881 ErrorFound = NotAnAssignmentOp;
4882 NoteLoc = ErrorLoc = SecondBinOp
4883 ? SecondBinOp->getOperatorLoc()
4884 : Second->getLocStart();
4885 NoteRange = ErrorRange =
4886 SecondBinOp ? SecondBinOp->getSourceRange()
4887 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00004888 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00004889 auto *PossibleXRHSInFirst =
4890 FirstBinOp->getRHS()->IgnoreParenImpCasts();
4891 auto *PossibleXLHSInSecond =
4892 SecondBinOp->getLHS()->IgnoreParenImpCasts();
4893 llvm::FoldingSetNodeID X1Id, X2Id;
4894 PossibleXRHSInFirst->Profile(X1Id, Context,
4895 /*Canonical=*/true);
4896 PossibleXLHSInSecond->Profile(X2Id, Context,
4897 /*Canonical=*/true);
4898 IsUpdateExprFound = X1Id == X2Id;
4899 if (IsUpdateExprFound) {
4900 V = FirstBinOp->getLHS();
4901 X = SecondBinOp->getLHS();
4902 E = SecondBinOp->getRHS();
4903 UE = nullptr;
4904 IsXLHSInRHSPart = false;
4905 IsPostfixUpdate = true;
4906 } else {
4907 ErrorFound = NotASpecificExpression;
4908 ErrorLoc = FirstBinOp->getExprLoc();
4909 ErrorRange = FirstBinOp->getSourceRange();
4910 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
4911 NoteRange = SecondBinOp->getRHS()->getSourceRange();
4912 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004913 }
4914 }
4915 }
4916 }
4917 } else {
4918 NoteLoc = ErrorLoc = Body->getLocStart();
4919 NoteRange = ErrorRange =
4920 SourceRange(Body->getLocStart(), Body->getLocStart());
4921 ErrorFound = NotTwoSubstatements;
4922 }
4923 } else {
4924 NoteLoc = ErrorLoc = Body->getLocStart();
4925 NoteRange = ErrorRange =
4926 SourceRange(Body->getLocStart(), Body->getLocStart());
4927 ErrorFound = NotACompoundStatement;
4928 }
4929 if (ErrorFound != NoError) {
4930 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
4931 << ErrorRange;
4932 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4933 return StmtError();
4934 } else if (CurContext->isDependentContext()) {
4935 UE = V = E = X = nullptr;
4936 }
Alexey Bataev459dec02014-07-24 06:46:57 +00004937 }
Alexey Bataevdea47612014-07-23 07:46:59 +00004938 }
Alexey Bataev0162e452014-07-22 10:10:35 +00004939
4940 getCurFunction()->setHasBranchProtectedScope();
4941
Alexey Bataev62cec442014-11-18 10:14:22 +00004942 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00004943 X, V, E, UE, IsXLHSInRHSPart,
4944 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00004945}
4946
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004947StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
4948 Stmt *AStmt,
4949 SourceLocation StartLoc,
4950 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004951 if (!AStmt)
4952 return StmtError();
4953
4954 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004955
Alexey Bataev13314bf2014-10-09 04:18:56 +00004956 // OpenMP [2.16, Nesting of Regions]
4957 // If specified, a teams construct must be contained within a target
4958 // construct. That target construct must contain no statements or directives
4959 // outside of the teams construct.
4960 if (DSAStack->hasInnerTeamsRegion()) {
4961 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
4962 bool OMPTeamsFound = true;
4963 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
4964 auto I = CS->body_begin();
4965 while (I != CS->body_end()) {
4966 auto OED = dyn_cast<OMPExecutableDirective>(*I);
4967 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
4968 OMPTeamsFound = false;
4969 break;
4970 }
4971 ++I;
4972 }
4973 assert(I != CS->body_end() && "Not found statement");
4974 S = *I;
4975 }
4976 if (!OMPTeamsFound) {
4977 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
4978 Diag(DSAStack->getInnerTeamsRegionLoc(),
4979 diag::note_omp_nested_teams_construct_here);
4980 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
4981 << isa<OMPExecutableDirective>(S);
4982 return StmtError();
4983 }
4984 }
4985
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004986 getCurFunction()->setHasBranchProtectedScope();
4987
4988 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4989}
4990
Michael Wong65f367f2015-07-21 13:44:28 +00004991StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
4992 Stmt *AStmt,
4993 SourceLocation StartLoc,
4994 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004995 if (!AStmt)
4996 return StmtError();
4997
4998 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4999
Michael Wong65f367f2015-07-21 13:44:28 +00005000 getCurFunction()->setHasBranchProtectedScope();
5001
5002 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5003 AStmt);
5004}
5005
Alexey Bataev13314bf2014-10-09 04:18:56 +00005006StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5007 Stmt *AStmt, SourceLocation StartLoc,
5008 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005009 if (!AStmt)
5010 return StmtError();
5011
Alexey Bataev13314bf2014-10-09 04:18:56 +00005012 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5013 // 1.2.2 OpenMP Language Terminology
5014 // Structured block - An executable statement with a single entry at the
5015 // top and a single exit at the bottom.
5016 // The point of exit cannot be a branch out of the structured block.
5017 // longjmp() and throw() must not violate the entry/exit criteria.
5018 CS->getCapturedDecl()->setNothrow();
5019
5020 getCurFunction()->setHasBranchProtectedScope();
5021
5022 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5023}
5024
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005025StmtResult
5026Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5027 SourceLocation EndLoc,
5028 OpenMPDirectiveKind CancelRegion) {
5029 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5030 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5031 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5032 << getOpenMPDirectiveName(CancelRegion);
5033 return StmtError();
5034 }
5035 if (DSAStack->isParentNowaitRegion()) {
5036 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5037 return StmtError();
5038 }
5039 if (DSAStack->isParentOrderedRegion()) {
5040 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5041 return StmtError();
5042 }
5043 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5044 CancelRegion);
5045}
5046
Alexey Bataev87933c72015-09-18 08:07:34 +00005047StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5048 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005049 SourceLocation EndLoc,
5050 OpenMPDirectiveKind CancelRegion) {
5051 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5052 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5053 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5054 << getOpenMPDirectiveName(CancelRegion);
5055 return StmtError();
5056 }
5057 if (DSAStack->isParentNowaitRegion()) {
5058 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5059 return StmtError();
5060 }
5061 if (DSAStack->isParentOrderedRegion()) {
5062 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5063 return StmtError();
5064 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005065 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005066 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5067 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005068}
5069
Alexey Bataeved09d242014-05-28 05:53:51 +00005070OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005071 SourceLocation StartLoc,
5072 SourceLocation LParenLoc,
5073 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005074 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005075 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00005076 case OMPC_final:
5077 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
5078 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00005079 case OMPC_num_threads:
5080 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
5081 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00005082 case OMPC_safelen:
5083 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
5084 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00005085 case OMPC_simdlen:
5086 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
5087 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00005088 case OMPC_collapse:
5089 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
5090 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005091 case OMPC_ordered:
5092 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
5093 break;
Michael Wonge710d542015-08-07 16:16:36 +00005094 case OMPC_device:
5095 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
5096 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00005097 case OMPC_num_teams:
5098 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
5099 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00005100 case OMPC_thread_limit:
5101 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
5102 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005103 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005104 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005105 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005106 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005107 case OMPC_private:
5108 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00005109 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005110 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005111 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00005112 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005113 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005114 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005115 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00005116 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005117 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005118 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005119 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005120 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005121 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005122 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005123 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005124 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005125 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005126 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00005127 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005128 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00005129 case OMPC_map:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005130 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005131 llvm_unreachable("Clause is not allowed.");
5132 }
5133 return Res;
5134}
5135
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005136OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
5137 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005138 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005139 SourceLocation NameModifierLoc,
5140 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005141 SourceLocation EndLoc) {
5142 Expr *ValExpr = Condition;
5143 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
5144 !Condition->isInstantiationDependent() &&
5145 !Condition->containsUnexpandedParameterPack()) {
5146 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00005147 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005148 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005149 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005150
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005151 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005152 }
5153
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005154 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
5155 NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005156}
5157
Alexey Bataev3778b602014-07-17 07:32:53 +00005158OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
5159 SourceLocation StartLoc,
5160 SourceLocation LParenLoc,
5161 SourceLocation EndLoc) {
5162 Expr *ValExpr = Condition;
5163 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
5164 !Condition->isInstantiationDependent() &&
5165 !Condition->containsUnexpandedParameterPack()) {
5166 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
5167 Condition->getExprLoc(), Condition);
5168 if (Val.isInvalid())
5169 return nullptr;
5170
5171 ValExpr = Val.get();
5172 }
5173
5174 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
5175}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005176ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
5177 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00005178 if (!Op)
5179 return ExprError();
5180
5181 class IntConvertDiagnoser : public ICEConvertDiagnoser {
5182 public:
5183 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00005184 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00005185 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
5186 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005187 return S.Diag(Loc, diag::err_omp_not_integral) << T;
5188 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005189 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
5190 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005191 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
5192 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005193 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
5194 QualType T,
5195 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005196 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
5197 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005198 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
5199 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005200 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00005201 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00005202 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005203 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
5204 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005205 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
5206 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005207 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
5208 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005209 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00005210 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00005211 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005212 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
5213 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005214 llvm_unreachable("conversion functions are permitted");
5215 }
5216 } ConvertDiagnoser;
5217 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
5218}
5219
Kelvin Lia15fb1a2015-11-27 18:47:36 +00005220static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
5221 OpenMPClauseKind CKind) {
5222 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
5223 !ValExpr->isInstantiationDependent()) {
5224 SourceLocation Loc = ValExpr->getExprLoc();
5225 ExprResult Value =
5226 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
5227 if (Value.isInvalid())
5228 return false;
5229
5230 ValExpr = Value.get();
5231 // The expression must evaluate to a non-negative integer value.
5232 llvm::APSInt Result;
5233 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
5234 Result.isSigned() && !Result.isStrictlyPositive()) {
5235 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
5236 << getOpenMPClauseName(CKind) << ValExpr->getSourceRange();
5237 return false;
5238 }
5239 }
5240 return true;
5241}
5242
Alexey Bataev568a8332014-03-06 06:15:19 +00005243OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
5244 SourceLocation StartLoc,
5245 SourceLocation LParenLoc,
5246 SourceLocation EndLoc) {
5247 Expr *ValExpr = NumThreads;
Alexey Bataev568a8332014-03-06 06:15:19 +00005248
Kelvin Lia15fb1a2015-11-27 18:47:36 +00005249 // OpenMP [2.5, Restrictions]
5250 // The num_threads expression must evaluate to a positive integer value.
5251 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads))
5252 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00005253
Alexey Bataeved09d242014-05-28 05:53:51 +00005254 return new (Context)
5255 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00005256}
5257
Alexey Bataev62c87d22014-03-21 04:51:18 +00005258ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
5259 OpenMPClauseKind CKind) {
5260 if (!E)
5261 return ExprError();
5262 if (E->isValueDependent() || E->isTypeDependent() ||
5263 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005264 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00005265 llvm::APSInt Result;
5266 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
5267 if (ICE.isInvalid())
5268 return ExprError();
5269 if (!Result.isStrictlyPositive()) {
5270 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
5271 << getOpenMPClauseName(CKind) << E->getSourceRange();
5272 return ExprError();
5273 }
Alexander Musman09184fe2014-09-30 05:29:28 +00005274 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
5275 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
5276 << E->getSourceRange();
5277 return ExprError();
5278 }
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005279 if (CKind == OMPC_collapse)
5280 DSAStack->setCollapseNumber(Result.getExtValue());
5281 else if (CKind == OMPC_ordered)
5282 DSAStack->setCollapseNumber(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00005283 return ICE;
5284}
5285
5286OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
5287 SourceLocation LParenLoc,
5288 SourceLocation EndLoc) {
5289 // OpenMP [2.8.1, simd construct, Description]
5290 // The parameter of the safelen clause must be a constant
5291 // positive integer expression.
5292 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
5293 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005294 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00005295 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005296 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00005297}
5298
Alexey Bataev66b15b52015-08-21 11:14:16 +00005299OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
5300 SourceLocation LParenLoc,
5301 SourceLocation EndLoc) {
5302 // OpenMP [2.8.1, simd construct, Description]
5303 // The parameter of the simdlen clause must be a constant
5304 // positive integer expression.
5305 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
5306 if (Simdlen.isInvalid())
5307 return nullptr;
5308 return new (Context)
5309 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
5310}
5311
Alexander Musman64d33f12014-06-04 07:53:32 +00005312OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
5313 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00005314 SourceLocation LParenLoc,
5315 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00005316 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00005317 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00005318 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00005319 // The parameter of the collapse clause must be a constant
5320 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00005321 ExprResult NumForLoopsResult =
5322 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
5323 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00005324 return nullptr;
5325 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00005326 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00005327}
5328
Alexey Bataev10e775f2015-07-30 11:36:16 +00005329OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
5330 SourceLocation EndLoc,
5331 SourceLocation LParenLoc,
5332 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00005333 // OpenMP [2.7.1, loop construct, Description]
5334 // OpenMP [2.8.1, simd construct, Description]
5335 // OpenMP [2.9.6, distribute construct, Description]
5336 // The parameter of the ordered clause must be a constant
5337 // positive integer expression if any.
5338 if (NumForLoops && LParenLoc.isValid()) {
5339 ExprResult NumForLoopsResult =
5340 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
5341 if (NumForLoopsResult.isInvalid())
5342 return nullptr;
5343 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00005344 } else
5345 NumForLoops = nullptr;
5346 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00005347 return new (Context)
5348 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
5349}
5350
Alexey Bataeved09d242014-05-28 05:53:51 +00005351OMPClause *Sema::ActOnOpenMPSimpleClause(
5352 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
5353 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005354 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005355 switch (Kind) {
5356 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00005357 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00005358 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
5359 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005360 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005361 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00005362 Res = ActOnOpenMPProcBindClause(
5363 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
5364 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005365 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005366 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00005367 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00005368 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00005369 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005370 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00005371 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005372 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005373 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005374 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00005375 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00005376 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005377 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00005378 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005379 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005380 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005381 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005382 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00005383 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005384 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005385 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005386 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005387 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005388 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005389 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005390 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005391 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005392 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005393 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00005394 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00005395 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005396 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00005397 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00005398 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00005399 case OMPC_thread_limit:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005400 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005401 llvm_unreachable("Clause is not allowed.");
5402 }
5403 return Res;
5404}
5405
5406OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
5407 SourceLocation KindKwLoc,
5408 SourceLocation StartLoc,
5409 SourceLocation LParenLoc,
5410 SourceLocation EndLoc) {
5411 if (Kind == OMPC_DEFAULT_unknown) {
5412 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005413 static_assert(OMPC_DEFAULT_unknown > 0,
5414 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00005415 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005416 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005417 Values += "'";
5418 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
5419 Values += "'";
5420 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005421 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005422 Values += " or ";
5423 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005424 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005425 break;
5426 default:
5427 Values += Sep;
5428 break;
5429 }
5430 }
5431 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00005432 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005433 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005434 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00005435 switch (Kind) {
5436 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005437 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005438 break;
5439 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005440 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005441 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005442 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005443 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00005444 break;
5445 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005446 return new (Context)
5447 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005448}
5449
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005450OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
5451 SourceLocation KindKwLoc,
5452 SourceLocation StartLoc,
5453 SourceLocation LParenLoc,
5454 SourceLocation EndLoc) {
5455 if (Kind == OMPC_PROC_BIND_unknown) {
5456 std::string Values;
5457 std::string Sep(", ");
5458 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
5459 Values += "'";
5460 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
5461 Values += "'";
5462 switch (i) {
5463 case OMPC_PROC_BIND_unknown - 2:
5464 Values += " or ";
5465 break;
5466 case OMPC_PROC_BIND_unknown - 1:
5467 break;
5468 default:
5469 Values += Sep;
5470 break;
5471 }
5472 }
5473 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00005474 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005475 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005476 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005477 return new (Context)
5478 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005479}
5480
Alexey Bataev56dafe82014-06-20 07:16:17 +00005481OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
5482 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
5483 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005484 SourceLocation ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00005485 SourceLocation EndLoc) {
5486 OMPClause *Res = nullptr;
5487 switch (Kind) {
5488 case OMPC_schedule:
5489 Res = ActOnOpenMPScheduleClause(
5490 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005491 LParenLoc, ArgumentLoc, DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00005492 break;
5493 case OMPC_if:
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005494 Res =
5495 ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument), Expr,
5496 StartLoc, LParenLoc, ArgumentLoc, DelimLoc, EndLoc);
5497 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00005498 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005499 case OMPC_num_threads:
5500 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005501 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005502 case OMPC_collapse:
5503 case OMPC_default:
5504 case OMPC_proc_bind:
5505 case OMPC_private:
5506 case OMPC_firstprivate:
5507 case OMPC_lastprivate:
5508 case OMPC_shared:
5509 case OMPC_reduction:
5510 case OMPC_linear:
5511 case OMPC_aligned:
5512 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005513 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005514 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00005515 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005516 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005517 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005518 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005519 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005520 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005521 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005522 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005523 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005524 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005525 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00005526 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00005527 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005528 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00005529 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00005530 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00005531 case OMPC_thread_limit:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005532 case OMPC_unknown:
5533 llvm_unreachable("Clause is not allowed.");
5534 }
5535 return Res;
5536}
5537
5538OMPClause *Sema::ActOnOpenMPScheduleClause(
5539 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
5540 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
5541 SourceLocation EndLoc) {
5542 if (Kind == OMPC_SCHEDULE_unknown) {
5543 std::string Values;
5544 std::string Sep(", ");
5545 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
5546 Values += "'";
5547 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
5548 Values += "'";
5549 switch (i) {
5550 case OMPC_SCHEDULE_unknown - 2:
5551 Values += " or ";
5552 break;
5553 case OMPC_SCHEDULE_unknown - 1:
5554 break;
5555 default:
5556 Values += Sep;
5557 break;
5558 }
5559 }
5560 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
5561 << Values << getOpenMPClauseName(OMPC_schedule);
5562 return nullptr;
5563 }
5564 Expr *ValExpr = ChunkSize;
Alexey Bataev040d5402015-05-12 08:35:28 +00005565 Expr *HelperValExpr = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00005566 if (ChunkSize) {
5567 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
5568 !ChunkSize->isInstantiationDependent() &&
5569 !ChunkSize->containsUnexpandedParameterPack()) {
5570 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
5571 ExprResult Val =
5572 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
5573 if (Val.isInvalid())
5574 return nullptr;
5575
5576 ValExpr = Val.get();
5577
5578 // OpenMP [2.7.1, Restrictions]
5579 // chunk_size must be a loop invariant integer expression with a positive
5580 // value.
5581 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00005582 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
5583 if (Result.isSigned() && !Result.isStrictlyPositive()) {
5584 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
5585 << "schedule" << ChunkSize->getSourceRange();
5586 return nullptr;
5587 }
5588 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
5589 auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
5590 ChunkSize->getType(), ".chunk.");
5591 auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
5592 ChunkSize->getExprLoc(),
5593 /*RefersToCapture=*/true);
5594 HelperValExpr = ImpVarRef;
Alexey Bataev56dafe82014-06-20 07:16:17 +00005595 }
5596 }
5597 }
5598
5599 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
Alexey Bataev040d5402015-05-12 08:35:28 +00005600 EndLoc, Kind, ValExpr, HelperValExpr);
Alexey Bataev56dafe82014-06-20 07:16:17 +00005601}
5602
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005603OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
5604 SourceLocation StartLoc,
5605 SourceLocation EndLoc) {
5606 OMPClause *Res = nullptr;
5607 switch (Kind) {
5608 case OMPC_ordered:
5609 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
5610 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00005611 case OMPC_nowait:
5612 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
5613 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005614 case OMPC_untied:
5615 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
5616 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005617 case OMPC_mergeable:
5618 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
5619 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005620 case OMPC_read:
5621 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
5622 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00005623 case OMPC_write:
5624 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
5625 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005626 case OMPC_update:
5627 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
5628 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00005629 case OMPC_capture:
5630 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
5631 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005632 case OMPC_seq_cst:
5633 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
5634 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00005635 case OMPC_threads:
5636 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
5637 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005638 case OMPC_simd:
5639 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
5640 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005641 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00005642 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005643 case OMPC_num_threads:
5644 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005645 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005646 case OMPC_collapse:
5647 case OMPC_schedule:
5648 case OMPC_private:
5649 case OMPC_firstprivate:
5650 case OMPC_lastprivate:
5651 case OMPC_shared:
5652 case OMPC_reduction:
5653 case OMPC_linear:
5654 case OMPC_aligned:
5655 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005656 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005657 case OMPC_default:
5658 case OMPC_proc_bind:
5659 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005660 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005661 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00005662 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00005663 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00005664 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00005665 case OMPC_thread_limit:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005666 case OMPC_unknown:
5667 llvm_unreachable("Clause is not allowed.");
5668 }
5669 return Res;
5670}
5671
Alexey Bataev236070f2014-06-20 11:19:47 +00005672OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
5673 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005674 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00005675 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
5676}
5677
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005678OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
5679 SourceLocation EndLoc) {
5680 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
5681}
5682
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005683OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
5684 SourceLocation EndLoc) {
5685 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
5686}
5687
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005688OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
5689 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005690 return new (Context) OMPReadClause(StartLoc, EndLoc);
5691}
5692
Alexey Bataevdea47612014-07-23 07:46:59 +00005693OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
5694 SourceLocation EndLoc) {
5695 return new (Context) OMPWriteClause(StartLoc, EndLoc);
5696}
5697
Alexey Bataev67a4f222014-07-23 10:25:33 +00005698OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
5699 SourceLocation EndLoc) {
5700 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
5701}
5702
Alexey Bataev459dec02014-07-24 06:46:57 +00005703OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
5704 SourceLocation EndLoc) {
5705 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
5706}
5707
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005708OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
5709 SourceLocation EndLoc) {
5710 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
5711}
5712
Alexey Bataev346265e2015-09-25 10:37:12 +00005713OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
5714 SourceLocation EndLoc) {
5715 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
5716}
5717
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005718OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
5719 SourceLocation EndLoc) {
5720 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
5721}
5722
Alexey Bataevc5e02582014-06-16 07:08:35 +00005723OMPClause *Sema::ActOnOpenMPVarListClause(
5724 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
5725 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
5726 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005727 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Kelvin Li0bff7af2015-11-23 05:32:03 +00005728 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
5729 OpenMPMapClauseKind MapType, SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005730 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005731 switch (Kind) {
5732 case OMPC_private:
5733 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5734 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005735 case OMPC_firstprivate:
5736 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5737 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005738 case OMPC_lastprivate:
5739 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5740 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00005741 case OMPC_shared:
5742 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
5743 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005744 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00005745 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
5746 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005747 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00005748 case OMPC_linear:
5749 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00005750 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00005751 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005752 case OMPC_aligned:
5753 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
5754 ColonLoc, EndLoc);
5755 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005756 case OMPC_copyin:
5757 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
5758 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00005759 case OMPC_copyprivate:
5760 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5761 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00005762 case OMPC_flush:
5763 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
5764 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005765 case OMPC_depend:
Kelvin Li0bff7af2015-11-23 05:32:03 +00005766 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
5767 StartLoc, LParenLoc, EndLoc);
5768 break;
5769 case OMPC_map:
5770 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, DepLinMapLoc, ColonLoc,
5771 VarList, StartLoc, LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005772 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005773 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00005774 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00005775 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00005776 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005777 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00005778 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005779 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005780 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005781 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005782 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00005783 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005784 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005785 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005786 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005787 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005788 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005789 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005790 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005791 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00005792 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00005793 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005794 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00005795 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00005796 case OMPC_thread_limit:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005797 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005798 llvm_unreachable("Clause is not allowed.");
5799 }
5800 return Res;
5801}
5802
5803OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
5804 SourceLocation StartLoc,
5805 SourceLocation LParenLoc,
5806 SourceLocation EndLoc) {
5807 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00005808 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00005809 for (auto &RefExpr : VarList) {
5810 assert(RefExpr && "NULL expr in OpenMP private clause.");
5811 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005812 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005813 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005814 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005815 continue;
5816 }
5817
Alexey Bataeved09d242014-05-28 05:53:51 +00005818 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005819 // OpenMP [2.1, C/C++]
5820 // A list item is a variable name.
5821 // OpenMP [2.9.3.3, Restrictions, p.1]
5822 // A variable that is part of another variable (as an array or
5823 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005824 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005825 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005826 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005827 continue;
5828 }
5829 Decl *D = DE->getDecl();
5830 VarDecl *VD = cast<VarDecl>(D);
5831
5832 QualType Type = VD->getType();
5833 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5834 // It will be analyzed later.
5835 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005836 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005837 continue;
5838 }
5839
5840 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5841 // A variable that appears in a private clause must not have an incomplete
5842 // type or a reference type.
5843 if (RequireCompleteType(ELoc, Type,
5844 diag::err_omp_private_incomplete_type)) {
5845 continue;
5846 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00005847 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005848
Alexey Bataev758e55e2013-09-06 18:03:48 +00005849 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5850 // in a Construct]
5851 // Variables with the predetermined data-sharing attributes may not be
5852 // listed in data-sharing attributes clauses, except for the cases
5853 // listed below. For these exceptions only, listing a predetermined
5854 // variable in a data-sharing attribute clause is allowed and overrides
5855 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005856 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005857 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005858 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5859 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005860 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005861 continue;
5862 }
5863
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005864 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00005865 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005866 DSAStack->getCurrentDirective() == OMPD_task) {
5867 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5868 << getOpenMPClauseName(OMPC_private) << Type
5869 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5870 bool IsDecl =
5871 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5872 Diag(VD->getLocation(),
5873 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5874 << VD;
5875 continue;
5876 }
5877
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005878 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
5879 // A variable of class type (or array thereof) that appears in a private
5880 // clause requires an accessible, unambiguous default constructor for the
5881 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00005882 // Generate helper private variable and initialize it with the default
5883 // value. The address of the original variable is replaced by the address of
5884 // the new private variable in CodeGen. This new variable is not added to
5885 // IdResolver, so the code in the OpenMP region uses original variable for
5886 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005887 Type = Type.getUnqualifiedType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00005888 auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName(),
5889 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005890 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005891 if (VDPrivate->isInvalidDecl())
5892 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005893 auto VDPrivateRefExpr = buildDeclRefExpr(
5894 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev03b340a2014-10-21 03:16:40 +00005895
Alexey Bataev758e55e2013-09-06 18:03:48 +00005896 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005897 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005898 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005899 }
5900
Alexey Bataeved09d242014-05-28 05:53:51 +00005901 if (Vars.empty())
5902 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005903
Alexey Bataev03b340a2014-10-21 03:16:40 +00005904 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
5905 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005906}
5907
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005908namespace {
5909class DiagsUninitializedSeveretyRAII {
5910private:
5911 DiagnosticsEngine &Diags;
5912 SourceLocation SavedLoc;
5913 bool IsIgnored;
5914
5915public:
5916 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
5917 bool IsIgnored)
5918 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
5919 if (!IsIgnored) {
5920 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
5921 /*Map*/ diag::Severity::Ignored, Loc);
5922 }
5923 }
5924 ~DiagsUninitializedSeveretyRAII() {
5925 if (!IsIgnored)
5926 Diags.popMappings(SavedLoc);
5927 }
5928};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005929}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005930
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005931OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
5932 SourceLocation StartLoc,
5933 SourceLocation LParenLoc,
5934 SourceLocation EndLoc) {
5935 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005936 SmallVector<Expr *, 8> PrivateCopies;
5937 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005938 bool IsImplicitClause =
5939 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
5940 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
5941
Alexey Bataeved09d242014-05-28 05:53:51 +00005942 for (auto &RefExpr : VarList) {
5943 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
5944 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005945 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005946 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005947 PrivateCopies.push_back(nullptr);
5948 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005949 continue;
5950 }
5951
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005952 SourceLocation ELoc =
5953 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005954 // OpenMP [2.1, C/C++]
5955 // A list item is a variable name.
5956 // OpenMP [2.9.3.3, Restrictions, p.1]
5957 // A variable that is part of another variable (as an array or
5958 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005959 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005960 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005961 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005962 continue;
5963 }
5964 Decl *D = DE->getDecl();
5965 VarDecl *VD = cast<VarDecl>(D);
5966
5967 QualType Type = VD->getType();
5968 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5969 // It will be analyzed later.
5970 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005971 PrivateCopies.push_back(nullptr);
5972 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005973 continue;
5974 }
5975
5976 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5977 // A variable that appears in a private clause must not have an incomplete
5978 // type or a reference type.
5979 if (RequireCompleteType(ELoc, Type,
5980 diag::err_omp_firstprivate_incomplete_type)) {
5981 continue;
5982 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00005983 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005984
5985 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
5986 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00005987 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005988 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005989 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005990
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005991 // If an implicit firstprivate variable found it was checked already.
5992 if (!IsImplicitClause) {
5993 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005994 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005995 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
5996 // A list item that specifies a given variable may not appear in more
5997 // than one clause on the same directive, except that a variable may be
5998 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005999 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00006000 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006001 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00006002 << getOpenMPClauseName(DVar.CKind)
6003 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006004 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006005 continue;
6006 }
6007
6008 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
6009 // in a Construct]
6010 // Variables with the predetermined data-sharing attributes may not be
6011 // listed in data-sharing attributes clauses, except for the cases
6012 // listed below. For these exceptions only, listing a predetermined
6013 // variable in a data-sharing attribute clause is allowed and overrides
6014 // the variable's predetermined data-sharing attributes.
6015 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
6016 // in a Construct, C/C++, p.2]
6017 // Variables with const-qualified type having no mutable member may be
6018 // listed in a firstprivate clause, even if they are static data members.
6019 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
6020 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
6021 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00006022 << getOpenMPClauseName(DVar.CKind)
6023 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006024 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006025 continue;
6026 }
6027
Alexey Bataevf29276e2014-06-18 04:14:57 +00006028 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006029 // OpenMP [2.9.3.4, Restrictions, p.2]
6030 // A list item that is private within a parallel region must not appear
6031 // in a firstprivate clause on a worksharing construct if any of the
6032 // worksharing regions arising from the worksharing construct ever bind
6033 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00006034 if (isOpenMPWorksharingDirective(CurrDir) &&
6035 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006036 DVar = DSAStack->getImplicitDSA(VD, true);
6037 if (DVar.CKind != OMPC_shared &&
6038 (isOpenMPParallelDirective(DVar.DKind) ||
6039 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00006040 Diag(ELoc, diag::err_omp_required_access)
6041 << getOpenMPClauseName(OMPC_firstprivate)
6042 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006043 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006044 continue;
6045 }
6046 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006047 // OpenMP [2.9.3.4, Restrictions, p.3]
6048 // A list item that appears in a reduction clause of a parallel construct
6049 // must not appear in a firstprivate clause on a worksharing or task
6050 // construct if any of the worksharing or task regions arising from the
6051 // worksharing or task construct ever bind to any of the parallel regions
6052 // arising from the parallel construct.
6053 // OpenMP [2.9.3.4, Restrictions, p.4]
6054 // A list item that appears in a reduction clause in worksharing
6055 // construct must not appear in a firstprivate clause in a task construct
6056 // encountered during execution of any of the worksharing regions arising
6057 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006058 if (CurrDir == OMPD_task) {
6059 DVar =
6060 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
6061 [](OpenMPDirectiveKind K) -> bool {
6062 return isOpenMPParallelDirective(K) ||
6063 isOpenMPWorksharingDirective(K);
6064 },
6065 false);
6066 if (DVar.CKind == OMPC_reduction &&
6067 (isOpenMPParallelDirective(DVar.DKind) ||
6068 isOpenMPWorksharingDirective(DVar.DKind))) {
6069 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
6070 << getOpenMPDirectiveName(DVar.DKind);
6071 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6072 continue;
6073 }
6074 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006075 }
6076
Alexey Bataevccb59ec2015-05-19 08:44:56 +00006077 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00006078 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataevccb59ec2015-05-19 08:44:56 +00006079 DSAStack->getCurrentDirective() == OMPD_task) {
6080 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
6081 << getOpenMPClauseName(OMPC_firstprivate) << Type
6082 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
6083 bool IsDecl =
6084 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6085 Diag(VD->getLocation(),
6086 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6087 << VD;
6088 continue;
6089 }
6090
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006091 Type = Type.getUnqualifiedType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00006092 auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName(),
6093 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006094 // Generate helper private variable and initialize it with the value of the
6095 // original variable. The address of the original variable is replaced by
6096 // the address of the new private variable in the CodeGen. This new variable
6097 // is not added to IdResolver, so the code in the OpenMP region uses
6098 // original variable for proper diagnostics and variable capturing.
6099 Expr *VDInitRefExpr = nullptr;
6100 // For arrays generate initializer for single element and replace it by the
6101 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006102 if (Type->isArrayType()) {
6103 auto VDInit =
6104 buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
6105 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006106 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006107 ElemType = ElemType.getUnqualifiedType();
6108 auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
6109 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00006110 InitializedEntity Entity =
6111 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006112 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
6113
6114 InitializationSequence InitSeq(*this, Entity, Kind, Init);
6115 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
6116 if (Result.isInvalid())
6117 VDPrivate->setInvalidDecl();
6118 else
6119 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006120 // Remove temp variable declaration.
6121 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006122 } else {
Alexey Bataev69c62a92015-04-15 04:52:20 +00006123 auto *VDInit =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006124 buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006125 VDInitRefExpr =
6126 buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00006127 AddInitializerToDecl(VDPrivate,
6128 DefaultLvalueConversion(VDInitRefExpr).get(),
6129 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006130 }
6131 if (VDPrivate->isInvalidDecl()) {
6132 if (IsImplicitClause) {
6133 Diag(DE->getExprLoc(),
6134 diag::note_omp_task_predetermined_firstprivate_here);
6135 }
6136 continue;
6137 }
6138 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00006139 auto VDPrivateRefExpr = buildDeclRefExpr(
6140 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006141 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
6142 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006143 PrivateCopies.push_back(VDPrivateRefExpr);
6144 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006145 }
6146
Alexey Bataeved09d242014-05-28 05:53:51 +00006147 if (Vars.empty())
6148 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006149
6150 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006151 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006152}
6153
Alexander Musman1bb328c2014-06-04 13:06:39 +00006154OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
6155 SourceLocation StartLoc,
6156 SourceLocation LParenLoc,
6157 SourceLocation EndLoc) {
6158 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00006159 SmallVector<Expr *, 8> SrcExprs;
6160 SmallVector<Expr *, 8> DstExprs;
6161 SmallVector<Expr *, 8> AssignmentOps;
Alexander Musman1bb328c2014-06-04 13:06:39 +00006162 for (auto &RefExpr : VarList) {
6163 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
6164 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6165 // It will be analyzed later.
6166 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00006167 SrcExprs.push_back(nullptr);
6168 DstExprs.push_back(nullptr);
6169 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006170 continue;
6171 }
6172
6173 SourceLocation ELoc = RefExpr->getExprLoc();
6174 // OpenMP [2.1, C/C++]
6175 // A list item is a variable name.
6176 // OpenMP [2.14.3.5, Restrictions, p.1]
6177 // A variable that is part of another variable (as an array or structure
6178 // element) cannot appear in a lastprivate clause.
6179 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
6180 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6181 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6182 continue;
6183 }
6184 Decl *D = DE->getDecl();
6185 VarDecl *VD = cast<VarDecl>(D);
6186
6187 QualType Type = VD->getType();
6188 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6189 // It will be analyzed later.
6190 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00006191 SrcExprs.push_back(nullptr);
6192 DstExprs.push_back(nullptr);
6193 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006194 continue;
6195 }
6196
6197 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
6198 // A variable that appears in a lastprivate clause must not have an
6199 // incomplete type or a reference type.
6200 if (RequireCompleteType(ELoc, Type,
6201 diag::err_omp_lastprivate_incomplete_type)) {
6202 continue;
6203 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006204 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00006205
6206 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
6207 // in a Construct]
6208 // Variables with the predetermined data-sharing attributes may not be
6209 // listed in data-sharing attributes clauses, except for the cases
6210 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006211 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006212 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
6213 DVar.CKind != OMPC_firstprivate &&
6214 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
6215 Diag(ELoc, diag::err_omp_wrong_dsa)
6216 << getOpenMPClauseName(DVar.CKind)
6217 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006218 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006219 continue;
6220 }
6221
Alexey Bataevf29276e2014-06-18 04:14:57 +00006222 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
6223 // OpenMP [2.14.3.5, Restrictions, p.2]
6224 // A list item that is private within a parallel region, or that appears in
6225 // the reduction clause of a parallel construct, must not appear in a
6226 // lastprivate clause on a worksharing construct if any of the corresponding
6227 // worksharing regions ever binds to any of the corresponding parallel
6228 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00006229 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00006230 if (isOpenMPWorksharingDirective(CurrDir) &&
6231 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006232 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006233 if (DVar.CKind != OMPC_shared) {
6234 Diag(ELoc, diag::err_omp_required_access)
6235 << getOpenMPClauseName(OMPC_lastprivate)
6236 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006237 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006238 continue;
6239 }
6240 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00006241 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00006242 // A variable of class type (or array thereof) that appears in a
6243 // lastprivate clause requires an accessible, unambiguous default
6244 // constructor for the class type, unless the list item is also specified
6245 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00006246 // A variable of class type (or array thereof) that appears in a
6247 // lastprivate clause requires an accessible, unambiguous copy assignment
6248 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00006249 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00006250 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00006251 Type.getUnqualifiedType(), ".lastprivate.src",
6252 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00006253 auto *PseudoSrcExpr = buildDeclRefExpr(
6254 *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00006255 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00006256 buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst",
6257 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00006258 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006259 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00006260 // For arrays generate assignment operation for single element and replace
6261 // it by the original array element in CodeGen.
6262 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6263 PseudoDstExpr, PseudoSrcExpr);
6264 if (AssignmentOp.isInvalid())
6265 continue;
6266 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6267 /*DiscardedValue=*/true);
6268 if (AssignmentOp.isInvalid())
6269 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00006270
Alexey Bataev39f915b82015-05-08 10:41:21 +00006271 if (TopDVar.CKind != OMPC_firstprivate)
Alexey Bataevf29276e2014-06-18 04:14:57 +00006272 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006273 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00006274 SrcExprs.push_back(PseudoSrcExpr);
6275 DstExprs.push_back(PseudoDstExpr);
6276 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00006277 }
6278
6279 if (Vars.empty())
6280 return nullptr;
6281
6282 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00006283 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006284}
6285
Alexey Bataev758e55e2013-09-06 18:03:48 +00006286OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
6287 SourceLocation StartLoc,
6288 SourceLocation LParenLoc,
6289 SourceLocation EndLoc) {
6290 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00006291 for (auto &RefExpr : VarList) {
6292 assert(RefExpr && "NULL expr in OpenMP shared clause.");
6293 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00006294 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006295 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006296 continue;
6297 }
6298
Alexey Bataeved09d242014-05-28 05:53:51 +00006299 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00006300 // OpenMP [2.1, C/C++]
6301 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00006302 // OpenMP [2.14.3.2, Restrictions, p.1]
6303 // A variable that is part of another variable (as an array or structure
6304 // element) cannot appear in a shared unless it is a static data member
6305 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00006306 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006307 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00006308 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00006309 continue;
6310 }
6311 Decl *D = DE->getDecl();
6312 VarDecl *VD = cast<VarDecl>(D);
6313
6314 QualType Type = VD->getType();
6315 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6316 // It will be analyzed later.
6317 Vars.push_back(DE);
6318 continue;
6319 }
6320
6321 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
6322 // in a Construct]
6323 // Variables with the predetermined data-sharing attributes may not be
6324 // listed in data-sharing attributes clauses, except for the cases
6325 // listed below. For these exceptions only, listing a predetermined
6326 // variable in a data-sharing attribute clause is allowed and overrides
6327 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006328 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00006329 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
6330 DVar.RefExpr) {
6331 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
6332 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006333 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006334 continue;
6335 }
6336
6337 DSAStack->addDSA(VD, DE, OMPC_shared);
6338 Vars.push_back(DE);
6339 }
6340
Alexey Bataeved09d242014-05-28 05:53:51 +00006341 if (Vars.empty())
6342 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00006343
6344 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
6345}
6346
Alexey Bataevc5e02582014-06-16 07:08:35 +00006347namespace {
6348class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
6349 DSAStackTy *Stack;
6350
6351public:
6352 bool VisitDeclRefExpr(DeclRefExpr *E) {
6353 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006354 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006355 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
6356 return false;
6357 if (DVar.CKind != OMPC_unknown)
6358 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00006359 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006360 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006361 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00006362 return true;
6363 return false;
6364 }
6365 return false;
6366 }
6367 bool VisitStmt(Stmt *S) {
6368 for (auto Child : S->children()) {
6369 if (Child && Visit(Child))
6370 return true;
6371 }
6372 return false;
6373 }
Alexey Bataev23b69422014-06-18 07:08:49 +00006374 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00006375};
Alexey Bataev23b69422014-06-18 07:08:49 +00006376} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00006377
6378OMPClause *Sema::ActOnOpenMPReductionClause(
6379 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
6380 SourceLocation ColonLoc, SourceLocation EndLoc,
6381 CXXScopeSpec &ReductionIdScopeSpec,
6382 const DeclarationNameInfo &ReductionId) {
6383 // TODO: Allow scope specification search when 'declare reduction' is
6384 // supported.
6385 assert(ReductionIdScopeSpec.isEmpty() &&
6386 "No support for scoped reduction identifiers yet.");
6387
6388 auto DN = ReductionId.getName();
6389 auto OOK = DN.getCXXOverloadedOperator();
6390 BinaryOperatorKind BOK = BO_Comma;
6391
6392 // OpenMP [2.14.3.6, reduction clause]
6393 // C
6394 // reduction-identifier is either an identifier or one of the following
6395 // operators: +, -, *, &, |, ^, && and ||
6396 // C++
6397 // reduction-identifier is either an id-expression or one of the following
6398 // operators: +, -, *, &, |, ^, && and ||
6399 // FIXME: Only 'min' and 'max' identifiers are supported for now.
6400 switch (OOK) {
6401 case OO_Plus:
6402 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006403 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006404 break;
6405 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006406 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006407 break;
6408 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006409 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006410 break;
6411 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006412 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006413 break;
6414 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006415 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006416 break;
6417 case OO_AmpAmp:
6418 BOK = BO_LAnd;
6419 break;
6420 case OO_PipePipe:
6421 BOK = BO_LOr;
6422 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006423 case OO_New:
6424 case OO_Delete:
6425 case OO_Array_New:
6426 case OO_Array_Delete:
6427 case OO_Slash:
6428 case OO_Percent:
6429 case OO_Tilde:
6430 case OO_Exclaim:
6431 case OO_Equal:
6432 case OO_Less:
6433 case OO_Greater:
6434 case OO_LessEqual:
6435 case OO_GreaterEqual:
6436 case OO_PlusEqual:
6437 case OO_MinusEqual:
6438 case OO_StarEqual:
6439 case OO_SlashEqual:
6440 case OO_PercentEqual:
6441 case OO_CaretEqual:
6442 case OO_AmpEqual:
6443 case OO_PipeEqual:
6444 case OO_LessLess:
6445 case OO_GreaterGreater:
6446 case OO_LessLessEqual:
6447 case OO_GreaterGreaterEqual:
6448 case OO_EqualEqual:
6449 case OO_ExclaimEqual:
6450 case OO_PlusPlus:
6451 case OO_MinusMinus:
6452 case OO_Comma:
6453 case OO_ArrowStar:
6454 case OO_Arrow:
6455 case OO_Call:
6456 case OO_Subscript:
6457 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00006458 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006459 case NUM_OVERLOADED_OPERATORS:
6460 llvm_unreachable("Unexpected reduction identifier");
6461 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006462 if (auto II = DN.getAsIdentifierInfo()) {
6463 if (II->isStr("max"))
6464 BOK = BO_GT;
6465 else if (II->isStr("min"))
6466 BOK = BO_LT;
6467 }
6468 break;
6469 }
6470 SourceRange ReductionIdRange;
6471 if (ReductionIdScopeSpec.isValid()) {
6472 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
6473 }
6474 ReductionIdRange.setEnd(ReductionId.getEndLoc());
6475 if (BOK == BO_Comma) {
6476 // Not allowed reduction identifier is found.
6477 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
6478 << ReductionIdRange;
6479 return nullptr;
6480 }
6481
6482 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006483 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006484 SmallVector<Expr *, 8> LHSs;
6485 SmallVector<Expr *, 8> RHSs;
6486 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006487 for (auto RefExpr : VarList) {
6488 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
6489 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6490 // It will be analyzed later.
6491 Vars.push_back(RefExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006492 Privates.push_back(nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006493 LHSs.push_back(nullptr);
6494 RHSs.push_back(nullptr);
6495 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006496 continue;
6497 }
6498
6499 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
6500 RefExpr->isInstantiationDependent() ||
6501 RefExpr->containsUnexpandedParameterPack()) {
6502 // It will be analyzed later.
6503 Vars.push_back(RefExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006504 Privates.push_back(nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006505 LHSs.push_back(nullptr);
6506 RHSs.push_back(nullptr);
6507 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006508 continue;
6509 }
6510
6511 auto ELoc = RefExpr->getExprLoc();
6512 auto ERange = RefExpr->getSourceRange();
6513 // OpenMP [2.1, C/C++]
6514 // A list item is a variable or array section, subject to the restrictions
6515 // specified in Section 2.4 on page 42 and in each of the sections
6516 // describing clauses and directives for which a list appears.
6517 // OpenMP [2.14.3.3, Restrictions, p.1]
6518 // A variable that is part of another variable (as an array or
6519 // structure element) cannot appear in a private clause.
Alexey Bataeva1764212015-09-30 09:22:36 +00006520 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
6521 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr);
6522 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr);
6523 if (!ASE && !OASE && (!DE || !isa<VarDecl>(DE->getDecl()))) {
6524 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item) << ERange;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006525 continue;
6526 }
Alexey Bataeva1764212015-09-30 09:22:36 +00006527 QualType Type;
6528 VarDecl *VD = nullptr;
6529 if (DE) {
6530 auto D = DE->getDecl();
6531 VD = cast<VarDecl>(D);
6532 Type = VD->getType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006533 } else if (ASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006534 Type = ASE->getType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006535 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
6536 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
6537 Base = TempASE->getBase()->IgnoreParenImpCasts();
6538 DE = dyn_cast<DeclRefExpr>(Base);
6539 if (DE)
6540 VD = dyn_cast<VarDecl>(DE->getDecl());
6541 if (!VD) {
6542 Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name)
6543 << 0 << Base->getSourceRange();
6544 continue;
6545 }
6546 } else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006547 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
6548 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
6549 Type = ATy->getElementType();
6550 else
6551 Type = BaseType->getPointeeType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006552 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
6553 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
6554 Base = TempOASE->getBase()->IgnoreParenImpCasts();
6555 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
6556 Base = TempASE->getBase()->IgnoreParenImpCasts();
6557 DE = dyn_cast<DeclRefExpr>(Base);
6558 if (DE)
6559 VD = dyn_cast<VarDecl>(DE->getDecl());
6560 if (!VD) {
6561 Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name)
6562 << 1 << Base->getSourceRange();
6563 continue;
6564 }
Alexey Bataeva1764212015-09-30 09:22:36 +00006565 }
6566
Alexey Bataevc5e02582014-06-16 07:08:35 +00006567 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
6568 // A variable that appears in a private clause must not have an incomplete
6569 // type or a reference type.
6570 if (RequireCompleteType(ELoc, Type,
6571 diag::err_omp_reduction_incomplete_type))
6572 continue;
6573 // OpenMP [2.14.3.6, reduction clause, Restrictions]
6574 // Arrays may not appear in a reduction clause.
6575 if (Type.getNonReferenceType()->isArrayType()) {
6576 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006577 if (!ASE && !OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006578 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6579 VarDecl::DeclarationOnly;
6580 Diag(VD->getLocation(),
6581 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6582 << VD;
6583 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006584 continue;
6585 }
6586 // OpenMP [2.14.3.6, reduction clause, Restrictions]
6587 // A list item that appears in a reduction clause must not be
6588 // const-qualified.
6589 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006590 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00006591 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006592 if (!ASE && !OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006593 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6594 VarDecl::DeclarationOnly;
6595 Diag(VD->getLocation(),
6596 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6597 << VD;
6598 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006599 continue;
6600 }
6601 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
6602 // If a list-item is a reference type then it must bind to the same object
6603 // for all threads of the team.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006604 if (!ASE && !OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006605 VarDecl *VDDef = VD->getDefinition();
6606 if (Type->isReferenceType() && VDDef) {
6607 DSARefChecker Check(DSAStack);
6608 if (Check.Visit(VDDef->getInit())) {
6609 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
6610 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
6611 continue;
6612 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006613 }
6614 }
6615 // OpenMP [2.14.3.6, reduction clause, Restrictions]
6616 // The type of a list item that appears in a reduction clause must be valid
6617 // for the reduction-identifier. For a max or min reduction in C, the type
6618 // of the list item must be an allowed arithmetic data type: char, int,
6619 // float, double, or _Bool, possibly modified with long, short, signed, or
6620 // unsigned. For a max or min reduction in C++, the type of the list item
6621 // must be an allowed arithmetic data type: char, wchar_t, int, float,
6622 // double, or bool, possibly modified with long, short, signed, or unsigned.
6623 if ((BOK == BO_GT || BOK == BO_LT) &&
6624 !(Type->isScalarType() ||
6625 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
6626 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
6627 << getLangOpts().CPlusPlus;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006628 if (!ASE && !OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006629 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6630 VarDecl::DeclarationOnly;
6631 Diag(VD->getLocation(),
6632 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6633 << VD;
6634 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006635 continue;
6636 }
6637 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
6638 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
6639 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006640 if (!ASE && !OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006641 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6642 VarDecl::DeclarationOnly;
6643 Diag(VD->getLocation(),
6644 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6645 << VD;
6646 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006647 continue;
6648 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006649 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
6650 // in a Construct]
6651 // Variables with the predetermined data-sharing attributes may not be
6652 // listed in data-sharing attributes clauses, except for the cases
6653 // listed below. For these exceptions only, listing a predetermined
6654 // variable in a data-sharing attribute clause is allowed and overrides
6655 // the variable's predetermined data-sharing attributes.
6656 // OpenMP [2.14.3.6, Restrictions, p.3]
6657 // Any number of reduction clauses can be specified on the directive,
6658 // but a list item can appear only once in the reduction clauses for that
6659 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00006660 DSAStackTy::DSAVarData DVar;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006661 DVar = DSAStack->getTopDSA(VD, false);
6662 if (DVar.CKind == OMPC_reduction) {
6663 Diag(ELoc, diag::err_omp_once_referenced)
6664 << getOpenMPClauseName(OMPC_reduction);
6665 if (DVar.RefExpr) {
6666 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006667 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006668 } else if (DVar.CKind != OMPC_unknown) {
6669 Diag(ELoc, diag::err_omp_wrong_dsa)
6670 << getOpenMPClauseName(DVar.CKind)
6671 << getOpenMPClauseName(OMPC_reduction);
6672 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6673 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006674 }
6675
6676 // OpenMP [2.14.3.6, Restrictions, p.1]
6677 // A list item that appears in a reduction clause of a worksharing
6678 // construct must be shared in the parallel regions to which any of the
6679 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006680 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
6681 if (isOpenMPWorksharingDirective(CurrDir) &&
6682 !isOpenMPParallelDirective(CurrDir)) {
6683 DVar = DSAStack->getImplicitDSA(VD, true);
6684 if (DVar.CKind != OMPC_shared) {
6685 Diag(ELoc, diag::err_omp_required_access)
6686 << getOpenMPClauseName(OMPC_reduction)
6687 << getOpenMPClauseName(OMPC_shared);
6688 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6689 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00006690 }
6691 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006692
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006693 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006694 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
6695 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6696 auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName(),
6697 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6698 auto PrivateTy = Type;
6699 if (OASE) {
6700 // For array sections only:
6701 // Create pseudo array type for private copy. The size for this array will
6702 // be generated during codegen.
6703 // For array subscripts or single variables Private Ty is the same as Type
6704 // (type of the variable or single array element).
6705 PrivateTy = Context.getVariableArrayType(
6706 Type, new (Context) OpaqueValueExpr(SourceLocation(),
6707 Context.getSizeType(), VK_RValue),
6708 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
6709 }
6710 // Private copy.
6711 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, VD->getName(),
6712 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006713 // Add initializer for private variable.
6714 Expr *Init = nullptr;
6715 switch (BOK) {
6716 case BO_Add:
6717 case BO_Xor:
6718 case BO_Or:
6719 case BO_LOr:
6720 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
6721 if (Type->isScalarType() || Type->isAnyComplexType()) {
6722 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00006723 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006724 break;
6725 case BO_Mul:
6726 case BO_LAnd:
6727 if (Type->isScalarType() || Type->isAnyComplexType()) {
6728 // '*' and '&&' reduction ops - initializer is '1'.
6729 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
6730 }
6731 break;
6732 case BO_And: {
6733 // '&' reduction op - initializer is '~0'.
6734 QualType OrigType = Type;
6735 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
6736 Type = ComplexTy->getElementType();
6737 }
6738 if (Type->isRealFloatingType()) {
6739 llvm::APFloat InitValue =
6740 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
6741 /*isIEEE=*/true);
6742 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
6743 Type, ELoc);
6744 } else if (Type->isScalarType()) {
6745 auto Size = Context.getTypeSize(Type);
6746 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
6747 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
6748 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
6749 }
6750 if (Init && OrigType->isAnyComplexType()) {
6751 // Init = 0xFFFF + 0xFFFFi;
6752 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
6753 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
6754 }
6755 Type = OrigType;
6756 break;
6757 }
6758 case BO_LT:
6759 case BO_GT: {
6760 // 'min' reduction op - initializer is 'Largest representable number in
6761 // the reduction list item type'.
6762 // 'max' reduction op - initializer is 'Least representable number in
6763 // the reduction list item type'.
6764 if (Type->isIntegerType() || Type->isPointerType()) {
6765 bool IsSigned = Type->hasSignedIntegerRepresentation();
6766 auto Size = Context.getTypeSize(Type);
6767 QualType IntTy =
6768 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
6769 llvm::APInt InitValue =
6770 (BOK != BO_LT)
6771 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
6772 : llvm::APInt::getMinValue(Size)
6773 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
6774 : llvm::APInt::getMaxValue(Size);
6775 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
6776 if (Type->isPointerType()) {
6777 // Cast to pointer type.
6778 auto CastExpr = BuildCStyleCastExpr(
6779 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
6780 SourceLocation(), Init);
6781 if (CastExpr.isInvalid())
6782 continue;
6783 Init = CastExpr.get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00006784 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006785 } else if (Type->isRealFloatingType()) {
6786 llvm::APFloat InitValue = llvm::APFloat::getLargest(
6787 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
6788 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
6789 Type, ELoc);
6790 }
6791 break;
6792 }
6793 case BO_PtrMemD:
6794 case BO_PtrMemI:
6795 case BO_MulAssign:
6796 case BO_Div:
6797 case BO_Rem:
6798 case BO_Sub:
6799 case BO_Shl:
6800 case BO_Shr:
6801 case BO_LE:
6802 case BO_GE:
6803 case BO_EQ:
6804 case BO_NE:
6805 case BO_AndAssign:
6806 case BO_XorAssign:
6807 case BO_OrAssign:
6808 case BO_Assign:
6809 case BO_AddAssign:
6810 case BO_SubAssign:
6811 case BO_DivAssign:
6812 case BO_RemAssign:
6813 case BO_ShlAssign:
6814 case BO_ShrAssign:
6815 case BO_Comma:
6816 llvm_unreachable("Unexpected reduction operation");
6817 }
6818 if (Init) {
6819 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
6820 /*TypeMayContainAuto=*/false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006821 } else
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006822 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006823 if (!RHSVD->hasInit()) {
6824 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
6825 << ReductionIdRange;
Alexey Bataeva1764212015-09-30 09:22:36 +00006826 if (VD) {
6827 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6828 VarDecl::DeclarationOnly;
6829 Diag(VD->getLocation(),
6830 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6831 << VD;
6832 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006833 continue;
6834 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006835 // Store initializer for single element in private copy. Will be used during
6836 // codegen.
6837 PrivateVD->setInit(RHSVD->getInit());
6838 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataev39f915b82015-05-08 10:41:21 +00006839 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
6840 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006841 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006842 ExprResult ReductionOp =
6843 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
6844 LHSDRE, RHSDRE);
6845 if (ReductionOp.isUsable()) {
Alexey Bataev69a47792015-05-07 03:54:03 +00006846 if (BOK != BO_LT && BOK != BO_GT) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006847 ReductionOp =
6848 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
6849 BO_Assign, LHSDRE, ReductionOp.get());
6850 } else {
6851 auto *ConditionalOp = new (Context) ConditionalOperator(
6852 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
6853 RHSDRE, Type, VK_LValue, OK_Ordinary);
6854 ReductionOp =
6855 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
6856 BO_Assign, LHSDRE, ConditionalOp);
6857 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006858 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00006859 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006860 if (ReductionOp.isInvalid())
6861 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006862
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006863 DSAStack->addDSA(VD, DE, OMPC_reduction);
Alexey Bataeva1764212015-09-30 09:22:36 +00006864 Vars.push_back(RefExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006865 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006866 LHSs.push_back(LHSDRE);
6867 RHSs.push_back(RHSDRE);
6868 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00006869 }
6870
6871 if (Vars.empty())
6872 return nullptr;
6873
6874 return OMPReductionClause::Create(
6875 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006876 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
6877 LHSs, RHSs, ReductionOps);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006878}
6879
Alexey Bataev182227b2015-08-20 10:54:39 +00006880OMPClause *Sema::ActOnOpenMPLinearClause(
6881 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
6882 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
6883 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00006884 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006885 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00006886 SmallVector<Expr *, 8> Inits;
Alexey Bataev182227b2015-08-20 10:54:39 +00006887 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
6888 LinKind == OMPC_LINEAR_unknown) {
6889 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
6890 LinKind = OMPC_LINEAR_val;
6891 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006892 for (auto &RefExpr : VarList) {
6893 assert(RefExpr && "NULL expr in OpenMP linear clause.");
6894 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00006895 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006896 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006897 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00006898 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00006899 continue;
6900 }
6901
6902 // OpenMP [2.14.3.7, linear clause]
6903 // A list item that appears in a linear clause is subject to the private
6904 // clause semantics described in Section 2.14.3.3 on page 159 except as
6905 // noted. In addition, the value of the new list item on each iteration
6906 // of the associated loop(s) corresponds to the value of the original
6907 // list item before entering the construct plus the logical number of
6908 // the iteration times linear-step.
6909
Alexey Bataeved09d242014-05-28 05:53:51 +00006910 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00006911 // OpenMP [2.1, C/C++]
6912 // A list item is a variable name.
6913 // OpenMP [2.14.3.3, Restrictions, p.1]
6914 // A variable that is part of another variable (as an array or
6915 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00006916 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00006917 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00006918 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00006919 continue;
6920 }
6921
6922 VarDecl *VD = cast<VarDecl>(DE->getDecl());
6923
6924 // OpenMP [2.14.3.7, linear clause]
6925 // A list-item cannot appear in more than one linear clause.
6926 // A list-item that appears in a linear clause cannot appear in any
6927 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006928 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00006929 if (DVar.RefExpr) {
6930 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
6931 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006932 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00006933 continue;
6934 }
6935
6936 QualType QType = VD->getType();
6937 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
6938 // It will be analyzed later.
6939 Vars.push_back(DE);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006940 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00006941 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00006942 continue;
6943 }
6944
6945 // A variable must not have an incomplete type or a reference type.
6946 if (RequireCompleteType(ELoc, QType,
6947 diag::err_omp_linear_incomplete_type)) {
6948 continue;
6949 }
Alexey Bataev1185e192015-08-20 12:15:57 +00006950 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
6951 !QType->isReferenceType()) {
6952 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
6953 << QType << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
6954 continue;
6955 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006956 QType = QType.getNonReferenceType();
Alexander Musman8dba6642014-04-22 13:09:42 +00006957
6958 // A list item must not be const-qualified.
6959 if (QType.isConstant(Context)) {
6960 Diag(ELoc, diag::err_omp_const_variable)
6961 << getOpenMPClauseName(OMPC_linear);
6962 bool IsDecl =
6963 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6964 Diag(VD->getLocation(),
6965 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6966 << VD;
6967 continue;
6968 }
6969
6970 // A list item must be of integral or pointer type.
6971 QType = QType.getUnqualifiedType().getCanonicalType();
6972 const Type *Ty = QType.getTypePtrOrNull();
6973 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
6974 !Ty->isPointerType())) {
6975 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
6976 bool IsDecl =
6977 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6978 Diag(VD->getLocation(),
6979 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6980 << VD;
6981 continue;
6982 }
6983
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006984 // Build private copy of original var.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00006985 auto *Private = buildVarDecl(*this, ELoc, QType, VD->getName(),
6986 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006987 auto *PrivateRef = buildDeclRefExpr(
6988 *this, Private, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexander Musman3276a272015-03-21 10:12:56 +00006989 // Build var to save initial value.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006990 VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00006991 Expr *InitExpr;
6992 if (LinKind == OMPC_LINEAR_uval)
6993 InitExpr = VD->getInit();
6994 else
6995 InitExpr = DE;
6996 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Alexander Musman3276a272015-03-21 10:12:56 +00006997 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006998 auto InitRef = buildDeclRefExpr(
6999 *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexander Musman8dba6642014-04-22 13:09:42 +00007000 DSAStack->addDSA(VD, DE, OMPC_linear);
7001 Vars.push_back(DE);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007002 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00007003 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00007004 }
7005
7006 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007007 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00007008
7009 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00007010 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00007011 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
7012 !Step->isInstantiationDependent() &&
7013 !Step->containsUnexpandedParameterPack()) {
7014 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007015 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00007016 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007017 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007018 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00007019
Alexander Musman3276a272015-03-21 10:12:56 +00007020 // Build var to save the step value.
7021 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00007022 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00007023 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00007024 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00007025 ExprResult CalcStep =
7026 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007027 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00007028
Alexander Musman8dba6642014-04-22 13:09:42 +00007029 // Warn about zero linear step (it would be probably better specified as
7030 // making corresponding variables 'const').
7031 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00007032 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
7033 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00007034 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
7035 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00007036 if (!IsConstant && CalcStep.isUsable()) {
7037 // Calculate the step beforehand instead of doing this on each iteration.
7038 // (This is not used if the number of iterations may be kfold-ed).
7039 CalcStepExpr = CalcStep.get();
7040 }
Alexander Musman8dba6642014-04-22 13:09:42 +00007041 }
7042
Alexey Bataev182227b2015-08-20 10:54:39 +00007043 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
7044 ColonLoc, EndLoc, Vars, Privates, Inits,
7045 StepExpr, CalcStepExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00007046}
7047
7048static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
7049 Expr *NumIterations, Sema &SemaRef,
7050 Scope *S) {
7051 // Walk the vars and build update/final expressions for the CodeGen.
7052 SmallVector<Expr *, 8> Updates;
7053 SmallVector<Expr *, 8> Finals;
7054 Expr *Step = Clause.getStep();
7055 Expr *CalcStep = Clause.getCalcStep();
7056 // OpenMP [2.14.3.7, linear clause]
7057 // If linear-step is not specified it is assumed to be 1.
7058 if (Step == nullptr)
7059 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7060 else if (CalcStep)
7061 Step = cast<BinaryOperator>(CalcStep)->getLHS();
7062 bool HasErrors = false;
7063 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007064 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00007065 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00007066 for (auto &RefExpr : Clause.varlists()) {
7067 Expr *InitExpr = *CurInit;
7068
7069 // Build privatized reference to the current linear var.
7070 auto DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00007071 Expr *CapturedRef;
7072 if (LinKind == OMPC_LINEAR_uval)
7073 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
7074 else
7075 CapturedRef =
7076 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
7077 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
7078 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00007079
7080 // Build update: Var = InitExpr + IV * Step
7081 ExprResult Update =
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007082 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexander Musman3276a272015-03-21 10:12:56 +00007083 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007084 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
7085 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00007086
7087 // Build final: Var = InitExpr + NumIterations * Step
7088 ExprResult Final =
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007089 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataev39f915b82015-05-08 10:41:21 +00007090 InitExpr, NumIterations, Step, /* Subtract */ false);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007091 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
7092 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00007093 if (!Update.isUsable() || !Final.isUsable()) {
7094 Updates.push_back(nullptr);
7095 Finals.push_back(nullptr);
7096 HasErrors = true;
7097 } else {
7098 Updates.push_back(Update.get());
7099 Finals.push_back(Final.get());
7100 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007101 ++CurInit, ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00007102 }
7103 Clause.setUpdates(Updates);
7104 Clause.setFinals(Finals);
7105 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00007106}
7107
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007108OMPClause *Sema::ActOnOpenMPAlignedClause(
7109 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
7110 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
7111
7112 SmallVector<Expr *, 8> Vars;
7113 for (auto &RefExpr : VarList) {
7114 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
7115 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7116 // It will be analyzed later.
7117 Vars.push_back(RefExpr);
7118 continue;
7119 }
7120
7121 SourceLocation ELoc = RefExpr->getExprLoc();
7122 // OpenMP [2.1, C/C++]
7123 // A list item is a variable name.
7124 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7125 if (!DE || !isa<VarDecl>(DE->getDecl())) {
7126 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7127 continue;
7128 }
7129
7130 VarDecl *VD = cast<VarDecl>(DE->getDecl());
7131
7132 // OpenMP [2.8.1, simd construct, Restrictions]
7133 // The type of list items appearing in the aligned clause must be
7134 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007135 QualType QType = VD->getType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007136 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007137 const Type *Ty = QType.getTypePtrOrNull();
7138 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
7139 !Ty->isPointerType())) {
7140 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
7141 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
7142 bool IsDecl =
7143 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7144 Diag(VD->getLocation(),
7145 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7146 << VD;
7147 continue;
7148 }
7149
7150 // OpenMP [2.8.1, simd construct, Restrictions]
7151 // A list-item cannot appear in more than one aligned clause.
7152 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
7153 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
7154 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
7155 << getOpenMPClauseName(OMPC_aligned);
7156 continue;
7157 }
7158
7159 Vars.push_back(DE);
7160 }
7161
7162 // OpenMP [2.8.1, simd construct, Description]
7163 // The parameter of the aligned clause, alignment, must be a constant
7164 // positive integer expression.
7165 // If no optional parameter is specified, implementation-defined default
7166 // alignments for SIMD instructions on the target platforms are assumed.
7167 if (Alignment != nullptr) {
7168 ExprResult AlignResult =
7169 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
7170 if (AlignResult.isInvalid())
7171 return nullptr;
7172 Alignment = AlignResult.get();
7173 }
7174 if (Vars.empty())
7175 return nullptr;
7176
7177 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
7178 EndLoc, Vars, Alignment);
7179}
7180
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007181OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
7182 SourceLocation StartLoc,
7183 SourceLocation LParenLoc,
7184 SourceLocation EndLoc) {
7185 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007186 SmallVector<Expr *, 8> SrcExprs;
7187 SmallVector<Expr *, 8> DstExprs;
7188 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00007189 for (auto &RefExpr : VarList) {
7190 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
7191 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007192 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007193 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007194 SrcExprs.push_back(nullptr);
7195 DstExprs.push_back(nullptr);
7196 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007197 continue;
7198 }
7199
Alexey Bataeved09d242014-05-28 05:53:51 +00007200 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007201 // OpenMP [2.1, C/C++]
7202 // A list item is a variable name.
7203 // OpenMP [2.14.4.1, Restrictions, p.1]
7204 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00007205 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007206 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007207 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007208 continue;
7209 }
7210
7211 Decl *D = DE->getDecl();
7212 VarDecl *VD = cast<VarDecl>(D);
7213
7214 QualType Type = VD->getType();
7215 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
7216 // It will be analyzed later.
7217 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007218 SrcExprs.push_back(nullptr);
7219 DstExprs.push_back(nullptr);
7220 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007221 continue;
7222 }
7223
7224 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
7225 // A list item that appears in a copyin clause must be threadprivate.
7226 if (!DSAStack->isThreadPrivate(VD)) {
7227 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00007228 << getOpenMPClauseName(OMPC_copyin)
7229 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007230 continue;
7231 }
7232
7233 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
7234 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00007235 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007236 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007237 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007238 auto *SrcVD =
7239 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
7240 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007241 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007242 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
7243 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007244 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
7245 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007246 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007247 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007248 // For arrays generate assignment operation for single element and replace
7249 // it by the original array element in CodeGen.
7250 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
7251 PseudoDstExpr, PseudoSrcExpr);
7252 if (AssignmentOp.isInvalid())
7253 continue;
7254 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
7255 /*DiscardedValue=*/true);
7256 if (AssignmentOp.isInvalid())
7257 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007258
7259 DSAStack->addDSA(VD, DE, OMPC_copyin);
7260 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007261 SrcExprs.push_back(PseudoSrcExpr);
7262 DstExprs.push_back(PseudoDstExpr);
7263 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007264 }
7265
Alexey Bataeved09d242014-05-28 05:53:51 +00007266 if (Vars.empty())
7267 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007268
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007269 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7270 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007271}
7272
Alexey Bataevbae9a792014-06-27 10:37:06 +00007273OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
7274 SourceLocation StartLoc,
7275 SourceLocation LParenLoc,
7276 SourceLocation EndLoc) {
7277 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00007278 SmallVector<Expr *, 8> SrcExprs;
7279 SmallVector<Expr *, 8> DstExprs;
7280 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007281 for (auto &RefExpr : VarList) {
7282 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
7283 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7284 // It will be analyzed later.
7285 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007286 SrcExprs.push_back(nullptr);
7287 DstExprs.push_back(nullptr);
7288 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007289 continue;
7290 }
7291
7292 SourceLocation ELoc = RefExpr->getExprLoc();
7293 // OpenMP [2.1, C/C++]
7294 // A list item is a variable name.
7295 // OpenMP [2.14.4.1, Restrictions, p.1]
7296 // A list item that appears in a copyin clause must be threadprivate.
7297 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7298 if (!DE || !isa<VarDecl>(DE->getDecl())) {
7299 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7300 continue;
7301 }
7302
7303 Decl *D = DE->getDecl();
7304 VarDecl *VD = cast<VarDecl>(D);
7305
7306 QualType Type = VD->getType();
7307 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
7308 // It will be analyzed later.
7309 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007310 SrcExprs.push_back(nullptr);
7311 DstExprs.push_back(nullptr);
7312 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007313 continue;
7314 }
7315
7316 // OpenMP [2.14.4.2, Restrictions, p.2]
7317 // A list item that appears in a copyprivate clause may not appear in a
7318 // private or firstprivate clause on the single construct.
7319 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007320 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007321 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
7322 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00007323 Diag(ELoc, diag::err_omp_wrong_dsa)
7324 << getOpenMPClauseName(DVar.CKind)
7325 << getOpenMPClauseName(OMPC_copyprivate);
7326 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7327 continue;
7328 }
7329
7330 // OpenMP [2.11.4.2, Restrictions, p.1]
7331 // All list items that appear in a copyprivate clause must be either
7332 // threadprivate or private in the enclosing context.
7333 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007334 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007335 if (DVar.CKind == OMPC_shared) {
7336 Diag(ELoc, diag::err_omp_required_access)
7337 << getOpenMPClauseName(OMPC_copyprivate)
7338 << "threadprivate or private in the enclosing context";
7339 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7340 continue;
7341 }
7342 }
7343 }
7344
Alexey Bataev7a3e5852015-05-19 08:19:24 +00007345 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007346 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00007347 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007348 << getOpenMPClauseName(OMPC_copyprivate) << Type
7349 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00007350 bool IsDecl =
7351 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7352 Diag(VD->getLocation(),
7353 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7354 << VD;
7355 continue;
7356 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007357
Alexey Bataevbae9a792014-06-27 10:37:06 +00007358 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
7359 // A variable of class type (or array thereof) that appears in a
7360 // copyin clause requires an accessible, unambiguous copy assignment
7361 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007362 Type = Context.getBaseElementType(Type.getNonReferenceType())
7363 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00007364 auto *SrcVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007365 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src",
7366 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev420d45b2015-04-14 05:11:24 +00007367 auto *PseudoSrcExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00007368 buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
Alexey Bataev420d45b2015-04-14 05:11:24 +00007369 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007370 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst",
7371 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev420d45b2015-04-14 05:11:24 +00007372 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00007373 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataeva63048e2015-03-23 06:18:07 +00007374 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
7375 PseudoDstExpr, PseudoSrcExpr);
7376 if (AssignmentOp.isInvalid())
7377 continue;
7378 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
7379 /*DiscardedValue=*/true);
7380 if (AssignmentOp.isInvalid())
7381 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007382
7383 // No need to mark vars as copyprivate, they are already threadprivate or
7384 // implicitly private.
7385 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007386 SrcExprs.push_back(PseudoSrcExpr);
7387 DstExprs.push_back(PseudoDstExpr);
7388 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00007389 }
7390
7391 if (Vars.empty())
7392 return nullptr;
7393
Alexey Bataeva63048e2015-03-23 06:18:07 +00007394 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
7395 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007396}
7397
Alexey Bataev6125da92014-07-21 11:26:11 +00007398OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
7399 SourceLocation StartLoc,
7400 SourceLocation LParenLoc,
7401 SourceLocation EndLoc) {
7402 if (VarList.empty())
7403 return nullptr;
7404
7405 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
7406}
Alexey Bataevdea47612014-07-23 07:46:59 +00007407
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007408OMPClause *
7409Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
7410 SourceLocation DepLoc, SourceLocation ColonLoc,
7411 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
7412 SourceLocation LParenLoc, SourceLocation EndLoc) {
7413 if (DepKind == OMPC_DEPEND_unknown) {
7414 std::string Values;
7415 std::string Sep(", ");
7416 for (unsigned i = 0; i < OMPC_DEPEND_unknown; ++i) {
7417 Values += "'";
7418 Values += getOpenMPSimpleClauseTypeName(OMPC_depend, i);
7419 Values += "'";
7420 switch (i) {
7421 case OMPC_DEPEND_unknown - 2:
7422 Values += " or ";
7423 break;
7424 case OMPC_DEPEND_unknown - 1:
7425 break;
7426 default:
7427 Values += Sep;
7428 break;
7429 }
7430 }
7431 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
7432 << Values << getOpenMPClauseName(OMPC_depend);
7433 return nullptr;
7434 }
7435 SmallVector<Expr *, 8> Vars;
7436 for (auto &RefExpr : VarList) {
7437 assert(RefExpr && "NULL expr in OpenMP shared clause.");
7438 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7439 // It will be analyzed later.
7440 Vars.push_back(RefExpr);
7441 continue;
7442 }
7443
7444 SourceLocation ELoc = RefExpr->getExprLoc();
7445 // OpenMP [2.11.1.1, Restrictions, p.3]
7446 // A variable that is part of another variable (such as a field of a
7447 // structure) but is not an array element or an array section cannot appear
7448 // in a depend clause.
7449 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007450 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
7451 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
7452 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
7453 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
7454 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007455 (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
7456 !ASE->getBase()->getType()->isArrayType())) {
7457 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
7458 << RefExpr->getSourceRange();
7459 continue;
7460 }
7461
7462 Vars.push_back(RefExpr->IgnoreParenImpCasts());
7463 }
7464
7465 if (Vars.empty())
7466 return nullptr;
7467
7468 return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind,
7469 DepLoc, ColonLoc, Vars);
7470}
Michael Wonge710d542015-08-07 16:16:36 +00007471
7472OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
7473 SourceLocation LParenLoc,
7474 SourceLocation EndLoc) {
7475 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +00007476
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007477 // OpenMP [2.9.1, Restrictions]
7478 // The device expression must evaluate to a non-negative integer value.
7479 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device))
7480 return nullptr;
7481
Michael Wonge710d542015-08-07 16:16:36 +00007482 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7483}
Kelvin Li0bff7af2015-11-23 05:32:03 +00007484
7485static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
7486 DSAStackTy *Stack, CXXRecordDecl *RD) {
7487 if (!RD || RD->isInvalidDecl())
7488 return true;
7489
7490 auto QTy = SemaRef.Context.getRecordType(RD);
7491 if (RD->isDynamicClass()) {
7492 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
7493 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
7494 return false;
7495 }
7496 auto *DC = RD;
7497 bool IsCorrect = true;
7498 for (auto *I : DC->decls()) {
7499 if (I) {
7500 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
7501 if (MD->isStatic()) {
7502 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
7503 SemaRef.Diag(MD->getLocation(),
7504 diag::note_omp_static_member_in_target);
7505 IsCorrect = false;
7506 }
7507 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
7508 if (VD->isStaticDataMember()) {
7509 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
7510 SemaRef.Diag(VD->getLocation(),
7511 diag::note_omp_static_member_in_target);
7512 IsCorrect = false;
7513 }
7514 }
7515 }
7516 }
7517
7518 for (auto &I : RD->bases()) {
7519 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
7520 I.getType()->getAsCXXRecordDecl()))
7521 IsCorrect = false;
7522 }
7523 return IsCorrect;
7524}
7525
7526static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
7527 DSAStackTy *Stack, QualType QTy) {
7528 NamedDecl *ND;
7529 if (QTy->isIncompleteType(&ND)) {
7530 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
7531 return false;
7532 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
7533 if (!RD->isInvalidDecl() &&
7534 !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
7535 return false;
7536 }
7537 return true;
7538}
7539
7540OMPClause *Sema::ActOnOpenMPMapClause(
7541 OpenMPMapClauseKind MapTypeModifier, OpenMPMapClauseKind MapType,
7542 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
7543 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
7544 SmallVector<Expr *, 4> Vars;
7545
7546 for (auto &RE : VarList) {
7547 assert(RE && "Null expr in omp map");
7548 if (isa<DependentScopeDeclRefExpr>(RE)) {
7549 // It will be analyzed later.
7550 Vars.push_back(RE);
7551 continue;
7552 }
7553 SourceLocation ELoc = RE->getExprLoc();
7554
7555 // OpenMP [2.14.5, Restrictions]
7556 // A variable that is part of another variable (such as field of a
7557 // structure) but is not an array element or an array section cannot appear
7558 // in a map clause.
7559 auto *VE = RE->IgnoreParenLValueCasts();
7560
7561 if (VE->isValueDependent() || VE->isTypeDependent() ||
7562 VE->isInstantiationDependent() ||
7563 VE->containsUnexpandedParameterPack()) {
7564 // It will be analyzed later.
7565 Vars.push_back(RE);
7566 continue;
7567 }
7568
7569 auto *SimpleExpr = RE->IgnoreParenCasts();
7570 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
7571 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
7572 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
7573
7574 if (!RE->IgnoreParenImpCasts()->isLValue() ||
7575 (!OASE && !ASE && !DE) ||
7576 (DE && !isa<VarDecl>(DE->getDecl())) ||
7577 (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
7578 !ASE->getBase()->getType()->isArrayType())) {
7579 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
7580 << RE->getSourceRange();
7581 continue;
7582 }
7583
7584 Decl *D = nullptr;
7585 if (DE) {
7586 D = DE->getDecl();
7587 } else if (ASE) {
7588 auto *B = ASE->getBase()->IgnoreParenCasts();
7589 D = dyn_cast<DeclRefExpr>(B)->getDecl();
7590 } else if (OASE) {
7591 auto *B = OASE->getBase();
7592 D = dyn_cast<DeclRefExpr>(B)->getDecl();
7593 }
7594 assert(D && "Null decl on map clause.");
7595 auto *VD = cast<VarDecl>(D);
7596
7597 // OpenMP [2.14.5, Restrictions, p.8]
7598 // threadprivate variables cannot appear in a map clause.
7599 if (DSAStack->isThreadPrivate(VD)) {
7600 auto DVar = DSAStack->getTopDSA(VD, false);
7601 Diag(ELoc, diag::err_omp_threadprivate_in_map);
7602 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7603 continue;
7604 }
7605
7606 // OpenMP [2.14.5, Restrictions, p.2]
7607 // At most one list item can be an array item derived from a given variable
7608 // in map clauses of the same construct.
7609 // OpenMP [2.14.5, Restrictions, p.3]
7610 // List items of map clauses in the same construct must not share original
7611 // storage.
7612 // OpenMP [2.14.5, Restrictions, C/C++, p.2]
7613 // A variable for which the type is pointer, reference to array, or
7614 // reference to pointer and an array section derived from that variable
7615 // must not appear as list items of map clauses of the same construct.
7616 DSAStackTy::MapInfo MI = DSAStack->IsMappedInCurrentRegion(VD);
7617 if (MI.RefExpr) {
7618 Diag(ELoc, diag::err_omp_map_shared_storage) << ELoc;
7619 Diag(MI.RefExpr->getExprLoc(), diag::note_used_here)
7620 << MI.RefExpr->getSourceRange();
7621 continue;
7622 }
7623
7624 // OpenMP [2.14.5, Restrictions, C/C++, p.3,4]
7625 // A variable for which the type is pointer, reference to array, or
7626 // reference to pointer must not appear as a list item if the enclosing
7627 // device data environment already contains an array section derived from
7628 // that variable.
7629 // An array section derived from a variable for which the type is pointer,
7630 // reference to array, or reference to pointer must not appear as a list
7631 // item if the enclosing device data environment already contains that
7632 // variable.
7633 QualType Type = VD->getType();
7634 MI = DSAStack->getMapInfoForVar(VD);
7635 if (MI.RefExpr && (isa<DeclRefExpr>(MI.RefExpr->IgnoreParenLValueCasts()) !=
7636 isa<DeclRefExpr>(VE)) &&
7637 (Type->isPointerType() || Type->isReferenceType())) {
7638 Diag(ELoc, diag::err_omp_map_shared_storage) << ELoc;
7639 Diag(MI.RefExpr->getExprLoc(), diag::note_used_here)
7640 << MI.RefExpr->getSourceRange();
7641 continue;
7642 }
7643
7644 // OpenMP [2.14.5, Restrictions, C/C++, p.7]
7645 // A list item must have a mappable type.
7646 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), *this,
7647 DSAStack, Type))
7648 continue;
7649
7650 Vars.push_back(RE);
7651 MI.RefExpr = RE;
7652 DSAStack->addMapInfoForVar(VD, MI);
7653 }
7654 if (Vars.empty())
7655 return nullptr;
7656
7657 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7658 MapTypeModifier, MapType, MapLoc);
7659}
Kelvin Li099bb8c2015-11-24 20:50:12 +00007660
7661OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
7662 SourceLocation StartLoc,
7663 SourceLocation LParenLoc,
7664 SourceLocation EndLoc) {
7665 Expr *ValExpr = NumTeams;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007666
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007667 // OpenMP [teams Constrcut, Restrictions]
7668 // The num_teams expression must evaluate to a positive integer value.
7669 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams))
7670 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007671
7672 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7673}
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007674
7675OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
7676 SourceLocation StartLoc,
7677 SourceLocation LParenLoc,
7678 SourceLocation EndLoc) {
7679 Expr *ValExpr = ThreadLimit;
7680
7681 // OpenMP [teams Constrcut, Restrictions]
7682 // The thread_limit expression must evaluate to a positive integer value.
7683 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit))
7684 return nullptr;
7685
7686 return new (Context) OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc,
7687 EndLoc);
7688}