blob: 7c32fab5b585f9af4d34b9783dd7ceaa13fc221c [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 {
Alexey Bataevf29276e2014-06-18 04:14:57 +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
Alexey Bataev758e55e2013-09-06 18:03:48 +000080private:
81 struct DSAInfo {
82 OpenMPClauseKind Attributes;
83 DeclRefExpr *RefExpr;
84 };
85 typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000086 typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
Alexey Bataev9c821032015-04-30 04:23:23 +000087 typedef llvm::DenseSet<VarDecl *> LoopControlVariablesSetTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000088
89 struct SharingMapTy {
90 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000091 AlignedMapTy AlignedMap;
Alexey Bataev9c821032015-04-30 04:23:23 +000092 LoopControlVariablesSetTy LCVSet;
Alexey Bataev758e55e2013-09-06 18:03:48 +000093 DefaultDataSharingAttributes DefaultAttr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000094 SourceLocation DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +000095 OpenMPDirectiveKind Directive;
96 DeclarationNameInfo DirectiveName;
97 Scope *CurScope;
Alexey Bataevbae9a792014-06-27 10:37:06 +000098 SourceLocation ConstructLoc;
Alexey Bataev346265e2015-09-25 10:37:12 +000099 /// \brief first argument (Expr *) contains optional argument of the
100 /// 'ordered' clause, the second one is true if the regions has 'ordered'
101 /// clause, false otherwise.
102 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000103 bool NowaitRegion;
Alexey Bataev25e5b442015-09-15 12:52:43 +0000104 bool CancelRegion;
Alexey Bataev9c821032015-04-30 04:23:23 +0000105 unsigned CollapseNumber;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000106 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000107 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000108 Scope *CurScope, SourceLocation Loc)
Alexey Bataev9c821032015-04-30 04:23:23 +0000109 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000110 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
Alexey Bataev346265e2015-09-25 10:37:12 +0000111 ConstructLoc(Loc), OrderedRegion(), NowaitRegion(false),
Alexey Bataev25e5b442015-09-15 12:52:43 +0000112 CancelRegion(false), CollapseNumber(1), InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000113 SharingMapTy()
Alexey Bataev9c821032015-04-30 04:23:23 +0000114 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000115 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
Alexey Bataev346265e2015-09-25 10:37:12 +0000116 ConstructLoc(), OrderedRegion(), NowaitRegion(false),
Alexey Bataev25e5b442015-09-15 12:52:43 +0000117 CancelRegion(false), CollapseNumber(1), InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000118 };
119
120 typedef SmallVector<SharingMapTy, 64> StackTy;
121
122 /// \brief Stack of used declaration and their data-sharing attributes.
123 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000124 /// \brief true, if check for DSA must be from parent directive, false, if
125 /// from current directive.
Alexey Bataevaac108a2015-06-23 04:51:00 +0000126 OpenMPClauseKind ClauseKindMode;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000127 Sema &SemaRef;
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000128 bool ForceCapturing;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000129
130 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
131
132 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000133
134 /// \brief Checks if the variable is a local for OpenMP region.
135 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000136
Alexey Bataev758e55e2013-09-06 18:03:48 +0000137public:
Alexey Bataevaac108a2015-06-23 04:51:00 +0000138 explicit DSAStackTy(Sema &S)
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000139 : Stack(1), ClauseKindMode(OMPC_unknown), SemaRef(S),
140 ForceCapturing(false) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000141
Alexey Bataevaac108a2015-06-23 04:51:00 +0000142 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
143 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000144
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000145 bool isForceVarCapturing() const { return ForceCapturing; }
146 void setForceVarCapturing(bool V) { ForceCapturing = V; }
147
Alexey Bataev758e55e2013-09-06 18:03:48 +0000148 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000149 Scope *CurScope, SourceLocation Loc) {
150 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
151 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000152 }
153
154 void pop() {
155 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
156 Stack.pop_back();
157 }
158
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000159 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000160 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000161 /// for diagnostics.
162 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
163
Alexey Bataev9c821032015-04-30 04:23:23 +0000164 /// \brief Register specified variable as loop control variable.
165 void addLoopControlVariable(VarDecl *D);
166 /// \brief Check if the specified variable is a loop control variable for
167 /// current region.
168 bool isLoopControlVariable(VarDecl *D);
169
Alexey Bataev758e55e2013-09-06 18:03:48 +0000170 /// \brief Adds explicit data sharing attribute to the specified declaration.
171 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
172
Alexey Bataev758e55e2013-09-06 18:03:48 +0000173 /// \brief Returns data sharing attributes from top of the stack for the
174 /// specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000175 DSAVarData getTopDSA(VarDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000176 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000177 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000178 /// \brief Checks if the specified variables has data-sharing attributes which
179 /// match specified \a CPred predicate in any directive which matches \a DPred
180 /// predicate.
181 template <class ClausesPredicate, class DirectivesPredicate>
182 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000183 DirectivesPredicate DPred, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000184 /// \brief Checks if the specified variables has data-sharing attributes which
185 /// match specified \a CPred predicate in any innermost directive which
186 /// matches \a DPred predicate.
187 template <class ClausesPredicate, class DirectivesPredicate>
188 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000189 DirectivesPredicate DPred,
190 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000191 /// \brief Checks if the specified variables has explicit data-sharing
192 /// attributes which match specified \a CPred predicate at the specified
193 /// OpenMP region.
194 bool hasExplicitDSA(VarDecl *D,
195 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
196 unsigned Level);
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000197 /// \brief Finds a directive which matches specified \a DPred predicate.
198 template <class NamedDirectivesPredicate>
199 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000200
Alexey Bataev758e55e2013-09-06 18:03:48 +0000201 /// \brief Returns currently analyzed directive.
202 OpenMPDirectiveKind getCurrentDirective() const {
203 return Stack.back().Directive;
204 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000205 /// \brief Returns parent directive.
206 OpenMPDirectiveKind getParentDirective() const {
207 if (Stack.size() > 2)
208 return Stack[Stack.size() - 2].Directive;
209 return OMPD_unknown;
210 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000211
212 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000213 void setDefaultDSANone(SourceLocation Loc) {
214 Stack.back().DefaultAttr = DSA_none;
215 Stack.back().DefaultAttrLoc = Loc;
216 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000217 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000218 void setDefaultDSAShared(SourceLocation Loc) {
219 Stack.back().DefaultAttr = DSA_shared;
220 Stack.back().DefaultAttrLoc = Loc;
221 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000222
223 DefaultDataSharingAttributes getDefaultDSA() const {
224 return Stack.back().DefaultAttr;
225 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000226 SourceLocation getDefaultDSALocation() const {
227 return Stack.back().DefaultAttrLoc;
228 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000229
Alexey Bataevf29276e2014-06-18 04:14:57 +0000230 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000231 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000232 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000233 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000234 }
235
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000236 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000237 void setOrderedRegion(bool IsOrdered, Expr *Param) {
238 Stack.back().OrderedRegion.setInt(IsOrdered);
239 Stack.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000240 }
241 /// \brief Returns true, if parent region is ordered (has associated
242 /// 'ordered' clause), false - otherwise.
243 bool isParentOrderedRegion() const {
244 if (Stack.size() > 2)
Alexey Bataev346265e2015-09-25 10:37:12 +0000245 return Stack[Stack.size() - 2].OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000246 return false;
247 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000248 /// \brief Returns optional parameter for the ordered region.
249 Expr *getParentOrderedRegionParam() const {
250 if (Stack.size() > 2)
251 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
252 return nullptr;
253 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000254 /// \brief Marks current region as nowait (it has a 'nowait' clause).
255 void setNowaitRegion(bool IsNowait = true) {
256 Stack.back().NowaitRegion = IsNowait;
257 }
258 /// \brief Returns true, if parent region is nowait (has associated
259 /// 'nowait' clause), false - otherwise.
260 bool isParentNowaitRegion() const {
261 if (Stack.size() > 2)
262 return Stack[Stack.size() - 2].NowaitRegion;
263 return false;
264 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000265 /// \brief Marks parent region as cancel region.
266 void setParentCancelRegion(bool Cancel = true) {
267 if (Stack.size() > 2)
268 Stack[Stack.size() - 2].CancelRegion =
269 Stack[Stack.size() - 2].CancelRegion || Cancel;
270 }
271 /// \brief Return true if current region has inner cancel construct.
272 bool isCancelRegion() const {
273 return Stack.back().CancelRegion;
274 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000275
Alexey Bataev9c821032015-04-30 04:23:23 +0000276 /// \brief Set collapse value for the region.
277 void setCollapseNumber(unsigned Val) { Stack.back().CollapseNumber = Val; }
278 /// \brief Return collapse value for region.
279 unsigned getCollapseNumber() const {
280 return Stack.back().CollapseNumber;
281 }
282
Alexey Bataev13314bf2014-10-09 04:18:56 +0000283 /// \brief Marks current target region as one with closely nested teams
284 /// region.
285 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
286 if (Stack.size() > 2)
287 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
288 }
289 /// \brief Returns true, if current region has closely nested teams region.
290 bool hasInnerTeamsRegion() const {
291 return getInnerTeamsRegionLoc().isValid();
292 }
293 /// \brief Returns location of the nested teams region (if any).
294 SourceLocation getInnerTeamsRegionLoc() const {
295 if (Stack.size() > 1)
296 return Stack.back().InnerTeamsRegionLoc;
297 return SourceLocation();
298 }
299
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000300 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000301 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000302 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000303};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000304bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
305 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
Alexey Bataev13314bf2014-10-09 04:18:56 +0000306 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000307}
Alexey Bataeved09d242014-05-28 05:53:51 +0000308} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000309
310DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
311 VarDecl *D) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000312 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000313 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000314 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000315 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
316 // in a region but not in construct]
317 // File-scope or namespace-scope variables referenced in called routines
318 // in the region are shared unless they appear in a threadprivate
319 // directive.
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000320 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000321 DVar.CKind = OMPC_shared;
322
323 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
324 // in a region but not in construct]
325 // Variables with static storage duration that are declared in called
326 // routines in the region are shared.
327 if (D->hasGlobalStorage())
328 DVar.CKind = OMPC_shared;
329
Alexey Bataev758e55e2013-09-06 18:03:48 +0000330 return DVar;
331 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000332
Alexey Bataev758e55e2013-09-06 18:03:48 +0000333 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000334 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
335 // in a Construct, C/C++, predetermined, p.1]
336 // Variables with automatic storage duration that are declared in a scope
337 // inside the construct are private.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000338 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
339 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
340 DVar.CKind = OMPC_private;
341 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000342 }
343
Alexey Bataev758e55e2013-09-06 18:03:48 +0000344 // Explicitly specified attributes and local variables with predetermined
345 // attributes.
346 if (Iter->SharingMap.count(D)) {
347 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
348 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000349 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000350 return DVar;
351 }
352
353 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
354 // in a Construct, C/C++, implicitly determined, p.1]
355 // In a parallel or task construct, the data-sharing attributes of these
356 // variables are determined by the default clause, if present.
357 switch (Iter->DefaultAttr) {
358 case DSA_shared:
359 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000360 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000361 return DVar;
362 case DSA_none:
363 return DVar;
364 case DSA_unspecified:
365 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
366 // in a Construct, implicitly determined, p.2]
367 // In a parallel construct, if no default clause is present, these
368 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000369 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000370 if (isOpenMPParallelDirective(DVar.DKind) ||
371 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000372 DVar.CKind = OMPC_shared;
373 return DVar;
374 }
375
376 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
377 // in a Construct, implicitly determined, p.4]
378 // In a task construct, if no default clause is present, a variable that in
379 // the enclosing context is determined to be shared by all implicit tasks
380 // bound to the current team is shared.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000381 if (DVar.DKind == OMPD_task) {
382 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000383 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000384 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000385 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
386 // Referenced
Alexey Bataev758e55e2013-09-06 18:03:48 +0000387 // in a Construct, implicitly determined, p.6]
388 // In a task construct, if no default clause is present, a variable
389 // whose data-sharing attribute is not determined by the rules above is
390 // firstprivate.
391 DVarTemp = getDSA(I, D);
392 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000393 DVar.RefExpr = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000394 DVar.DKind = OMPD_task;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000395 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000396 return DVar;
397 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000398 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000399 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000400 }
401 DVar.DKind = OMPD_task;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000402 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000403 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000404 return DVar;
405 }
406 }
407 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
408 // in a Construct, implicitly determined, p.3]
409 // For constructs other than task, if no default clause is present, these
410 // variables inherit their data-sharing attributes from the enclosing
411 // context.
Benjamin Kramer167e9992014-03-02 12:20:24 +0000412 return getDSA(std::next(Iter), D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000413}
414
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000415DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
416 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000417 D = D->getCanonicalDecl();
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000418 auto It = Stack.back().AlignedMap.find(D);
419 if (It == Stack.back().AlignedMap.end()) {
420 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
421 Stack.back().AlignedMap[D] = NewDE;
422 return nullptr;
423 } else {
424 assert(It->second && "Unexpected nullptr expr in the aligned map");
425 return It->second;
426 }
427 return nullptr;
428}
429
Alexey Bataev9c821032015-04-30 04:23:23 +0000430void DSAStackTy::addLoopControlVariable(VarDecl *D) {
431 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
432 D = D->getCanonicalDecl();
433 Stack.back().LCVSet.insert(D);
434}
435
436bool DSAStackTy::isLoopControlVariable(VarDecl *D) {
437 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
438 D = D->getCanonicalDecl();
439 return Stack.back().LCVSet.count(D) > 0;
440}
441
Alexey Bataev758e55e2013-09-06 18:03:48 +0000442void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000443 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000444 if (A == OMPC_threadprivate) {
445 Stack[0].SharingMap[D].Attributes = A;
446 Stack[0].SharingMap[D].RefExpr = E;
447 } else {
448 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
449 Stack.back().SharingMap[D].Attributes = A;
450 Stack.back().SharingMap[D].RefExpr = E;
451 }
452}
453
Alexey Bataeved09d242014-05-28 05:53:51 +0000454bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000455 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000456 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000457 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000458 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000459 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000460 ++I;
461 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000462 if (I == E)
463 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000464 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000465 Scope *CurScope = getCurScope();
466 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000467 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000468 }
469 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000470 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000471 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000472}
473
Alexey Bataev39f915b82015-05-08 10:41:21 +0000474/// \brief Build a variable declaration for OpenMP loop iteration variable.
475static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000476 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000477 DeclContext *DC = SemaRef.CurContext;
478 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
479 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
480 VarDecl *Decl =
481 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000482 if (Attrs) {
483 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
484 I != E; ++I)
485 Decl->addAttr(*I);
486 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000487 Decl->setImplicit();
488 return Decl;
489}
490
491static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
492 SourceLocation Loc,
493 bool RefersToCapture = false) {
494 D->setReferenced();
495 D->markUsed(S.Context);
496 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
497 SourceLocation(), D, RefersToCapture, Loc, Ty,
498 VK_LValue);
499}
500
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000501DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000502 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000503 DSAVarData DVar;
504
505 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
506 // in a Construct, C/C++, predetermined, p.1]
507 // Variables appearing in threadprivate directives are threadprivate.
Samuel Antaof8b50122015-07-13 22:54:53 +0000508 if ((D->getTLSKind() != VarDecl::TLS_None &&
509 !(D->hasAttr<OMPThreadPrivateDeclAttr>() &&
510 SemaRef.getLangOpts().OpenMPUseTLS &&
511 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +0000512 (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() &&
513 !D->isLocalVarDecl())) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000514 addDSA(D, buildDeclRefExpr(SemaRef, D, D->getType().getNonReferenceType(),
515 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000516 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000517 }
518 if (Stack[0].SharingMap.count(D)) {
519 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
520 DVar.CKind = OMPC_threadprivate;
521 return DVar;
522 }
523
524 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
525 // in a Construct, C/C++, predetermined, p.1]
526 // Variables with automatic storage duration that are declared in a scope
527 // inside the construct are private.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000528 OpenMPDirectiveKind Kind =
529 FromParent ? getParentDirective() : getCurrentDirective();
530 auto StartI = std::next(Stack.rbegin());
531 auto EndI = std::prev(Stack.rend());
532 if (FromParent && StartI != EndI) {
533 StartI = std::next(StartI);
534 }
535 if (!isParallelOrTaskRegion(Kind)) {
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000536 if (isOpenMPLocal(D, StartI) &&
537 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
538 D->getStorageClass() == SC_None)) ||
539 isa<ParmVarDecl>(D))) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000540 DVar.CKind = OMPC_private;
541 return DVar;
Alexander Musman8dba6642014-04-22 13:09:42 +0000542 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000543
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000544 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
545 // in a Construct, C/C++, predetermined, p.4]
546 // Static data members are shared.
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000547 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
548 // in a Construct, C/C++, predetermined, p.7]
549 // Variables with static storage duration that are declared in a scope
550 // inside the construct are shared.
Kelvin Li4eea8c62015-09-15 18:56:58 +0000551 if (D->isStaticDataMember()) {
Alexey Bataev42971a32015-01-20 07:03:46 +0000552 DSAVarData DVarTemp =
553 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
554 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
555 return DVar;
556
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000557 DVar.CKind = OMPC_shared;
558 return DVar;
559 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000560 }
561
562 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000563 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
564 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000565 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
566 // in a Construct, C/C++, predetermined, p.6]
567 // Variables with const qualified type having no mutable member are
568 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000569 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000570 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000571 if (IsConstant &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000572 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000573 // Variables with const-qualified type having no mutable member may be
574 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000575 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
576 MatchesAlways(), FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000577 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
578 return DVar;
579
Alexey Bataev758e55e2013-09-06 18:03:48 +0000580 DVar.CKind = OMPC_shared;
581 return DVar;
582 }
583
Alexey Bataev758e55e2013-09-06 18:03:48 +0000584 // Explicitly specified attributes and local variables with predetermined
585 // attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000586 auto I = std::prev(StartI);
587 if (I->SharingMap.count(D)) {
588 DVar.RefExpr = I->SharingMap[D].RefExpr;
589 DVar.CKind = I->SharingMap[D].Attributes;
590 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000591 }
592
593 return DVar;
594}
595
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000596DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000597 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000598 auto StartI = Stack.rbegin();
599 auto EndI = std::prev(Stack.rend());
600 if (FromParent && StartI != EndI) {
601 StartI = std::next(StartI);
602 }
603 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000604}
605
Alexey Bataevf29276e2014-06-18 04:14:57 +0000606template <class ClausesPredicate, class DirectivesPredicate>
607DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000608 DirectivesPredicate DPred,
609 bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000610 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000611 auto StartI = std::next(Stack.rbegin());
612 auto EndI = std::prev(Stack.rend());
613 if (FromParent && StartI != EndI) {
614 StartI = std::next(StartI);
615 }
616 for (auto I = StartI, EE = EndI; I != EE; ++I) {
617 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000618 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000619 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000620 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000621 return DVar;
622 }
623 return DSAVarData();
624}
625
Alexey Bataevf29276e2014-06-18 04:14:57 +0000626template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000627DSAStackTy::DSAVarData
628DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
629 DirectivesPredicate DPred, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000630 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000631 auto StartI = std::next(Stack.rbegin());
632 auto EndI = std::prev(Stack.rend());
633 if (FromParent && StartI != EndI) {
634 StartI = std::next(StartI);
635 }
636 for (auto I = StartI, EE = EndI; I != EE; ++I) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000637 if (!DPred(I->Directive))
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000638 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +0000639 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000640 if (CPred(DVar.CKind))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000641 return DVar;
642 return DSAVarData();
643 }
644 return DSAVarData();
645}
646
Alexey Bataevaac108a2015-06-23 04:51:00 +0000647bool DSAStackTy::hasExplicitDSA(
648 VarDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
649 unsigned Level) {
650 if (CPred(ClauseKindMode))
651 return true;
652 if (isClauseParsingMode())
653 ++Level;
654 D = D->getCanonicalDecl();
655 auto StartI = Stack.rbegin();
656 auto EndI = std::prev(Stack.rend());
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000657 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000658 return false;
659 std::advance(StartI, Level);
660 return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr &&
661 CPred(StartI->SharingMap[D].Attributes);
662}
663
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000664template <class NamedDirectivesPredicate>
665bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
666 auto StartI = std::next(Stack.rbegin());
667 auto EndI = std::prev(Stack.rend());
668 if (FromParent && StartI != EndI) {
669 StartI = std::next(StartI);
670 }
671 for (auto I = StartI, EE = EndI; I != EE; ++I) {
672 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
673 return true;
674 }
675 return false;
676}
677
Alexey Bataev758e55e2013-09-06 18:03:48 +0000678void Sema::InitDataSharingAttributesStack() {
679 VarDataSharingAttributesStack = new DSAStackTy(*this);
680}
681
682#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
683
Alexey Bataevf841bd92014-12-16 07:00:22 +0000684bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
685 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000686 VD = VD->getCanonicalDecl();
Alexey Bataev48977c32015-08-04 08:10:48 +0000687 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
688 (!DSAStack->isClauseParsingMode() ||
689 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000690 if (DSAStack->isLoopControlVariable(VD) ||
691 (VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000692 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
693 DSAStack->isForceVarCapturing())
Alexey Bataev9c821032015-04-30 04:23:23 +0000694 return true;
Alexey Bataevaac108a2015-06-23 04:51:00 +0000695 auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000696 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
697 return true;
698 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
Alexey Bataevaac108a2015-06-23 04:51:00 +0000699 DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000700 return DVarPrivate.CKind != OMPC_unknown;
701 }
702 return false;
703}
704
Alexey Bataevaac108a2015-06-23 04:51:00 +0000705bool Sema::isOpenMPPrivateVar(VarDecl *VD, unsigned Level) {
706 assert(LangOpts.OpenMP && "OpenMP is not allowed");
707 return DSAStack->hasExplicitDSA(
708 VD, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
709}
710
Alexey Bataeved09d242014-05-28 05:53:51 +0000711void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000712
713void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
714 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000715 Scope *CurScope, SourceLocation Loc) {
716 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000717 PushExpressionEvaluationContext(PotentiallyEvaluated);
718}
719
Alexey Bataevaac108a2015-06-23 04:51:00 +0000720void Sema::StartOpenMPClause(OpenMPClauseKind K) {
721 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000722}
723
Alexey Bataevaac108a2015-06-23 04:51:00 +0000724void Sema::EndOpenMPClause() {
725 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000726}
727
Alexey Bataev758e55e2013-09-06 18:03:48 +0000728void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000729 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
730 // A variable of class type (or array thereof) that appears in a lastprivate
731 // clause requires an accessible, unambiguous default constructor for the
732 // class type, unless the list item is also specified in a firstprivate
733 // clause.
734 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000735 for (auto *C : D->clauses()) {
736 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
737 SmallVector<Expr *, 8> PrivateCopies;
738 for (auto *DE : Clause->varlists()) {
739 if (DE->isValueDependent() || DE->isTypeDependent()) {
740 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000741 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +0000742 }
743 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000744 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000745 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000746 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000747 // Generate helper private variable and initialize it with the
748 // default value. The address of the original variable is replaced
749 // by the address of the new private variable in CodeGen. This new
750 // variable is not added to IdResolver, so the code in the OpenMP
751 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000752 auto *VDPrivate = buildVarDecl(
753 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
754 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +0000755 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
756 if (VDPrivate->isInvalidDecl())
757 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000758 PrivateCopies.push_back(buildDeclRefExpr(
759 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +0000760 } else {
761 // The variable is also a firstprivate, so initialization sequence
762 // for private copy is generated already.
763 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000764 }
765 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000766 // Set initializers to private copies if no errors were found.
767 if (PrivateCopies.size() == Clause->varlist_size()) {
768 Clause->setPrivateCopies(PrivateCopies);
769 }
Alexey Bataevf29276e2014-06-18 04:14:57 +0000770 }
771 }
772 }
773
Alexey Bataev758e55e2013-09-06 18:03:48 +0000774 DSAStack->pop();
775 DiscardCleanupsInEvaluationContext();
776 PopExpressionEvaluationContext();
777}
778
Alexander Musman3276a272015-03-21 10:12:56 +0000779static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
780 Expr *NumIterations, Sema &SemaRef,
781 Scope *S);
782
Alexey Bataeva769e072013-03-22 06:34:35 +0000783namespace {
784
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000785class VarDeclFilterCCC : public CorrectionCandidateCallback {
786private:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000787 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +0000788
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000789public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000790 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +0000791 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000792 NamedDecl *ND = Candidate.getCorrectionDecl();
793 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
794 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000795 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
796 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +0000797 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000798 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +0000799 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000800};
Alexey Bataeved09d242014-05-28 05:53:51 +0000801} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000802
803ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
804 CXXScopeSpec &ScopeSpec,
805 const DeclarationNameInfo &Id) {
806 LookupResult Lookup(*this, Id, LookupOrdinaryName);
807 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
808
809 if (Lookup.isAmbiguous())
810 return ExprError();
811
812 VarDecl *VD;
813 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000814 if (TypoCorrection Corrected = CorrectTypo(
815 Id, LookupOrdinaryName, CurScope, nullptr,
816 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000817 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000818 PDiag(Lookup.empty()
819 ? diag::err_undeclared_var_use_suggest
820 : diag::err_omp_expected_var_arg_suggest)
821 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +0000822 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000823 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000824 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
825 : diag::err_omp_expected_var_arg)
826 << Id.getName();
827 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000828 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000829 } else {
830 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000831 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000832 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
833 return ExprError();
834 }
835 }
836 Lookup.suppressDiagnostics();
837
838 // OpenMP [2.9.2, Syntax, C/C++]
839 // Variables must be file-scope, namespace-scope, or static block-scope.
840 if (!VD->hasGlobalStorage()) {
841 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000842 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
843 bool IsDecl =
844 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000845 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +0000846 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
847 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000848 return ExprError();
849 }
850
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000851 VarDecl *CanonicalVD = VD->getCanonicalDecl();
852 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000853 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
854 // A threadprivate directive for file-scope variables must appear outside
855 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000856 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
857 !getCurLexicalContext()->isTranslationUnit()) {
858 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000859 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
860 bool IsDecl =
861 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
862 Diag(VD->getLocation(),
863 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
864 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000865 return ExprError();
866 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000867 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
868 // A threadprivate directive for static class member variables must appear
869 // in the class definition, in the same scope in which the member
870 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000871 if (CanonicalVD->isStaticDataMember() &&
872 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
873 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000874 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
875 bool IsDecl =
876 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
877 Diag(VD->getLocation(),
878 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
879 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000880 return ExprError();
881 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000882 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
883 // A threadprivate directive for namespace-scope variables must appear
884 // outside any definition or declaration other than the namespace
885 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000886 if (CanonicalVD->getDeclContext()->isNamespace() &&
887 (!getCurLexicalContext()->isFileContext() ||
888 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
889 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000890 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
891 bool IsDecl =
892 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
893 Diag(VD->getLocation(),
894 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
895 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000896 return ExprError();
897 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000898 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
899 // A threadprivate directive for static block-scope variables must appear
900 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000901 if (CanonicalVD->isStaticLocal() && CurScope &&
902 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000903 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000904 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
905 bool IsDecl =
906 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
907 Diag(VD->getLocation(),
908 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
909 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000910 return ExprError();
911 }
912
913 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
914 // A threadprivate directive must lexically precede all references to any
915 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000916 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000917 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +0000918 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000919 return ExprError();
920 }
921
922 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +0000923 ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000924 return DE;
925}
926
Alexey Bataeved09d242014-05-28 05:53:51 +0000927Sema::DeclGroupPtrTy
928Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
929 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000930 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000931 CurContext->addDecl(D);
932 return DeclGroupPtrTy::make(DeclGroupRef(D));
933 }
934 return DeclGroupPtrTy();
935}
936
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000937namespace {
938class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
939 Sema &SemaRef;
940
941public:
942 bool VisitDeclRefExpr(const DeclRefExpr *E) {
943 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
944 if (VD->hasLocalStorage()) {
945 SemaRef.Diag(E->getLocStart(),
946 diag::err_omp_local_var_in_threadprivate_init)
947 << E->getSourceRange();
948 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
949 << VD << VD->getSourceRange();
950 return true;
951 }
952 }
953 return false;
954 }
955 bool VisitStmt(const Stmt *S) {
956 for (auto Child : S->children()) {
957 if (Child && Visit(Child))
958 return true;
959 }
960 return false;
961 }
Alexey Bataev23b69422014-06-18 07:08:49 +0000962 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000963};
964} // namespace
965
Alexey Bataeved09d242014-05-28 05:53:51 +0000966OMPThreadPrivateDecl *
967Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000968 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +0000969 for (auto &RefExpr : VarList) {
970 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000971 VarDecl *VD = cast<VarDecl>(DE->getDecl());
972 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +0000973
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000974 QualType QType = VD->getType();
975 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
976 // It will be analyzed later.
977 Vars.push_back(DE);
978 continue;
979 }
980
Alexey Bataeva769e072013-03-22 06:34:35 +0000981 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
982 // A threadprivate variable must not have an incomplete type.
983 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000984 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000985 continue;
986 }
987
988 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
989 // A threadprivate variable must not have a reference type.
990 if (VD->getType()->isReferenceType()) {
991 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000992 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
993 bool IsDecl =
994 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
995 Diag(VD->getLocation(),
996 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
997 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000998 continue;
999 }
1000
Samuel Antaof8b50122015-07-13 22:54:53 +00001001 // Check if this is a TLS variable. If TLS is not being supported, produce
1002 // the corresponding diagnostic.
1003 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1004 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1005 getLangOpts().OpenMPUseTLS &&
1006 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001007 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1008 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001009 Diag(ILoc, diag::err_omp_var_thread_local)
1010 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001011 bool IsDecl =
1012 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1013 Diag(VD->getLocation(),
1014 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1015 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001016 continue;
1017 }
1018
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001019 // Check if initial value of threadprivate variable reference variable with
1020 // local storage (it is not supported by runtime).
1021 if (auto Init = VD->getAnyInitializer()) {
1022 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001023 if (Checker.Visit(Init))
1024 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001025 }
1026
Alexey Bataeved09d242014-05-28 05:53:51 +00001027 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001028 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001029 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1030 Context, SourceRange(Loc, Loc)));
1031 if (auto *ML = Context.getASTMutationListener())
1032 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001033 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001034 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001035 if (!Vars.empty()) {
1036 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1037 Vars);
1038 D->setAccess(AS_public);
1039 }
1040 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001041}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001042
Alexey Bataev7ff55242014-06-19 09:13:45 +00001043static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1044 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
1045 bool IsLoopIterVar = false) {
1046 if (DVar.RefExpr) {
1047 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1048 << getOpenMPClauseName(DVar.CKind);
1049 return;
1050 }
1051 enum {
1052 PDSA_StaticMemberShared,
1053 PDSA_StaticLocalVarShared,
1054 PDSA_LoopIterVarPrivate,
1055 PDSA_LoopIterVarLinear,
1056 PDSA_LoopIterVarLastprivate,
1057 PDSA_ConstVarShared,
1058 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001059 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001060 PDSA_LocalVarPrivate,
1061 PDSA_Implicit
1062 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001063 bool ReportHint = false;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001064 auto ReportLoc = VD->getLocation();
Alexey Bataev7ff55242014-06-19 09:13:45 +00001065 if (IsLoopIterVar) {
1066 if (DVar.CKind == OMPC_private)
1067 Reason = PDSA_LoopIterVarPrivate;
1068 else if (DVar.CKind == OMPC_lastprivate)
1069 Reason = PDSA_LoopIterVarLastprivate;
1070 else
1071 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001072 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
1073 Reason = PDSA_TaskVarFirstprivate;
1074 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001075 } else if (VD->isStaticLocal())
1076 Reason = PDSA_StaticLocalVarShared;
1077 else if (VD->isStaticDataMember())
1078 Reason = PDSA_StaticMemberShared;
1079 else if (VD->isFileVarDecl())
1080 Reason = PDSA_GlobalVarShared;
1081 else if (VD->getType().isConstant(SemaRef.getASTContext()))
1082 Reason = PDSA_ConstVarShared;
Alexey Bataevbae9a792014-06-27 10:37:06 +00001083 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001084 ReportHint = true;
1085 Reason = PDSA_LocalVarPrivate;
1086 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001087 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001088 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001089 << Reason << ReportHint
1090 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1091 } else if (DVar.ImplicitDSALoc.isValid()) {
1092 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1093 << getOpenMPClauseName(DVar.CKind);
1094 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001095}
1096
Alexey Bataev758e55e2013-09-06 18:03:48 +00001097namespace {
1098class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1099 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001100 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001101 bool ErrorFound;
1102 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001103 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001104 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001105
Alexey Bataev758e55e2013-09-06 18:03:48 +00001106public:
1107 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001108 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001109 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001110 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1111 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001112
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001113 auto DVar = Stack->getTopDSA(VD, false);
1114 // Check if the variable has explicit DSA set and stop analysis if it so.
1115 if (DVar.RefExpr) return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001116
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001117 auto ELoc = E->getExprLoc();
1118 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001119 // The default(none) clause requires that each variable that is referenced
1120 // in the construct, and does not have a predetermined data-sharing
1121 // attribute, must have its data-sharing attribute explicitly determined
1122 // by being listed in a data-sharing attribute clause.
1123 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001124 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001125 VarsWithInheritedDSA.count(VD) == 0) {
1126 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001127 return;
1128 }
1129
1130 // OpenMP [2.9.3.6, Restrictions, p.2]
1131 // A list item that appears in a reduction clause of the innermost
1132 // enclosing worksharing or parallel construct may not be accessed in an
1133 // explicit task.
Alexey Bataevf29276e2014-06-18 04:14:57 +00001134 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001135 [](OpenMPDirectiveKind K) -> bool {
1136 return isOpenMPParallelDirective(K) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001137 isOpenMPWorksharingDirective(K) ||
1138 isOpenMPTeamsDirective(K);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001139 },
1140 false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001141 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1142 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001143 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1144 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001145 return;
1146 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001147
1148 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001149 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001150 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001151 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001152 }
1153 }
1154 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001155 for (auto *C : S->clauses()) {
1156 // Skip analysis of arguments of implicitly defined firstprivate clause
1157 // for task directives.
1158 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1159 for (auto *CC : C->children()) {
1160 if (CC)
1161 Visit(CC);
1162 }
1163 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001164 }
1165 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001166 for (auto *C : S->children()) {
1167 if (C && !isa<OMPExecutableDirective>(C))
1168 Visit(C);
1169 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001170 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001171
1172 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001173 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001174 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1175 return VarsWithInheritedDSA;
1176 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001177
Alexey Bataev7ff55242014-06-19 09:13:45 +00001178 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1179 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001180};
Alexey Bataeved09d242014-05-28 05:53:51 +00001181} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001182
Alexey Bataevbae9a792014-06-27 10:37:06 +00001183void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001184 switch (DKind) {
1185 case OMPD_parallel: {
1186 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001187 QualType KmpInt32PtrTy =
1188 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001189 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001190 std::make_pair(".global_tid.", KmpInt32PtrTy),
1191 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1192 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001193 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001194 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1195 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001196 break;
1197 }
1198 case OMPD_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001199 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001200 std::make_pair(StringRef(), QualType()) // __context with shared vars
1201 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001202 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1203 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001204 break;
1205 }
1206 case OMPD_for: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001207 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001208 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001209 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001210 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1211 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001212 break;
1213 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001214 case OMPD_for_simd: {
1215 Sema::CapturedParamNameType Params[] = {
1216 std::make_pair(StringRef(), QualType()) // __context with shared vars
1217 };
1218 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1219 Params);
1220 break;
1221 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001222 case OMPD_sections: {
1223 Sema::CapturedParamNameType Params[] = {
1224 std::make_pair(StringRef(), QualType()) // __context with shared vars
1225 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001226 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1227 Params);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001228 break;
1229 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001230 case OMPD_section: {
1231 Sema::CapturedParamNameType Params[] = {
1232 std::make_pair(StringRef(), QualType()) // __context with shared vars
1233 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001234 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1235 Params);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001236 break;
1237 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001238 case OMPD_single: {
1239 Sema::CapturedParamNameType Params[] = {
1240 std::make_pair(StringRef(), QualType()) // __context with shared vars
1241 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001242 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1243 Params);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001244 break;
1245 }
Alexander Musman80c22892014-07-17 08:54:58 +00001246 case OMPD_master: {
1247 Sema::CapturedParamNameType Params[] = {
1248 std::make_pair(StringRef(), QualType()) // __context with shared vars
1249 };
1250 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1251 Params);
1252 break;
1253 }
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001254 case OMPD_critical: {
1255 Sema::CapturedParamNameType Params[] = {
1256 std::make_pair(StringRef(), QualType()) // __context with shared vars
1257 };
1258 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1259 Params);
1260 break;
1261 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001262 case OMPD_parallel_for: {
1263 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001264 QualType KmpInt32PtrTy =
1265 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataev4acb8592014-07-07 13:01:15 +00001266 Sema::CapturedParamNameType Params[] = {
1267 std::make_pair(".global_tid.", KmpInt32PtrTy),
1268 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1269 std::make_pair(StringRef(), QualType()) // __context with shared vars
1270 };
1271 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1272 Params);
1273 break;
1274 }
Alexander Musmane4e893b2014-09-23 09:33:00 +00001275 case OMPD_parallel_for_simd: {
1276 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001277 QualType KmpInt32PtrTy =
1278 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexander Musmane4e893b2014-09-23 09:33:00 +00001279 Sema::CapturedParamNameType Params[] = {
1280 std::make_pair(".global_tid.", KmpInt32PtrTy),
1281 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1282 std::make_pair(StringRef(), QualType()) // __context with shared vars
1283 };
1284 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1285 Params);
1286 break;
1287 }
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001288 case OMPD_parallel_sections: {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001289 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001290 QualType KmpInt32PtrTy =
1291 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001292 Sema::CapturedParamNameType Params[] = {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001293 std::make_pair(".global_tid.", KmpInt32PtrTy),
1294 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001295 std::make_pair(StringRef(), QualType()) // __context with shared vars
1296 };
1297 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1298 Params);
1299 break;
1300 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001301 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001302 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001303 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1304 FunctionProtoType::ExtProtoInfo EPI;
1305 EPI.Variadic = true;
1306 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001307 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001308 std::make_pair(".global_tid.", KmpInt32Ty),
1309 std::make_pair(".part_id.", KmpInt32Ty),
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001310 std::make_pair(".privates.",
1311 Context.VoidPtrTy.withConst().withRestrict()),
1312 std::make_pair(
1313 ".copy_fn.",
1314 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001315 std::make_pair(StringRef(), QualType()) // __context with shared vars
1316 };
1317 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1318 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001319 // Mark this captured region as inlined, because we don't use outlined
1320 // function directly.
1321 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1322 AlwaysInlineAttr::CreateImplicit(
1323 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001324 break;
1325 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001326 case OMPD_ordered: {
1327 Sema::CapturedParamNameType Params[] = {
1328 std::make_pair(StringRef(), QualType()) // __context with shared vars
1329 };
1330 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1331 Params);
1332 break;
1333 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001334 case OMPD_atomic: {
1335 Sema::CapturedParamNameType Params[] = {
1336 std::make_pair(StringRef(), QualType()) // __context with shared vars
1337 };
1338 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1339 Params);
1340 break;
1341 }
Michael Wong65f367f2015-07-21 13:44:28 +00001342 case OMPD_target_data:
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001343 case OMPD_target: {
1344 Sema::CapturedParamNameType Params[] = {
1345 std::make_pair(StringRef(), QualType()) // __context with shared vars
1346 };
1347 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1348 Params);
1349 break;
1350 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001351 case OMPD_teams: {
1352 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001353 QualType KmpInt32PtrTy =
1354 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataev13314bf2014-10-09 04:18:56 +00001355 Sema::CapturedParamNameType Params[] = {
1356 std::make_pair(".global_tid.", KmpInt32PtrTy),
1357 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1358 std::make_pair(StringRef(), QualType()) // __context with shared vars
1359 };
1360 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1361 Params);
1362 break;
1363 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001364 case OMPD_taskgroup: {
1365 Sema::CapturedParamNameType Params[] = {
1366 std::make_pair(StringRef(), QualType()) // __context with shared vars
1367 };
1368 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1369 Params);
1370 break;
1371 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001372 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001373 case OMPD_taskyield:
1374 case OMPD_barrier:
1375 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001376 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001377 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001378 case OMPD_flush:
Alexey Bataev9959db52014-05-06 10:08:46 +00001379 llvm_unreachable("OpenMP Directive is not allowed");
1380 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001381 llvm_unreachable("Unknown OpenMP directive");
1382 }
1383}
1384
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001385StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1386 ArrayRef<OMPClause *> Clauses) {
1387 if (!S.isUsable()) {
1388 ActOnCapturedRegionError();
1389 return StmtError();
1390 }
Alexey Bataev040d5402015-05-12 08:35:28 +00001391 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001392 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001393 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001394 Clause->getClauseKind() == OMPC_copyprivate ||
1395 (getLangOpts().OpenMPUseTLS &&
1396 getASTContext().getTargetInfo().isTLSSupported() &&
1397 Clause->getClauseKind() == OMPC_copyin)) {
1398 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001399 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001400 for (auto *VarRef : Clause->children()) {
1401 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001402 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001403 }
1404 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001405 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev040d5402015-05-12 08:35:28 +00001406 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
1407 Clause->getClauseKind() == OMPC_schedule) {
1408 // Mark all variables in private list clauses as used in inner region.
1409 // Required for proper codegen of combined directives.
1410 // TODO: add processing for other clauses.
1411 if (auto *E = cast_or_null<Expr>(
1412 cast<OMPScheduleClause>(Clause)->getHelperChunkSize())) {
1413 MarkDeclarationsReferencedInExpr(E);
1414 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001415 }
1416 }
1417 return ActOnCapturedRegionEnd(S.get());
1418}
1419
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001420static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1421 OpenMPDirectiveKind CurrentRegion,
1422 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001423 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001424 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001425 // Allowed nesting of constructs
1426 // +------------------+-----------------+------------------------------------+
1427 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1428 // +------------------+-----------------+------------------------------------+
1429 // | parallel | parallel | * |
1430 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001431 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001432 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001433 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001434 // | parallel | simd | * |
1435 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001436 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001437 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001438 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001439 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001440 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001441 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001442 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001443 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001444 // | parallel | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001445 // | parallel | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001446 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001447 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001448 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001449 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001450 // | parallel | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001451 // | parallel | cancellation | |
1452 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001453 // | parallel | cancel | ! |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001454 // +------------------+-----------------+------------------------------------+
1455 // | for | parallel | * |
1456 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001457 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001458 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001459 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001460 // | for | simd | * |
1461 // | for | sections | + |
1462 // | for | section | + |
1463 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001464 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001465 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001466 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001467 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001468 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001469 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001470 // | for | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001471 // | for | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001472 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001473 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001474 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001475 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001476 // | for | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001477 // | for | cancellation | |
1478 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001479 // | for | cancel | ! |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001480 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001481 // | master | parallel | * |
1482 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001483 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001484 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001485 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001486 // | master | simd | * |
1487 // | master | sections | + |
1488 // | master | section | + |
1489 // | master | single | + |
1490 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001491 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001492 // | master |parallel sections| * |
1493 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001494 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001495 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001496 // | master | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001497 // | master | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001498 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001499 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001500 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001501 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001502 // | master | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001503 // | master | cancellation | |
1504 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001505 // | master | cancel | |
Alexander Musman80c22892014-07-17 08:54:58 +00001506 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001507 // | critical | parallel | * |
1508 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001509 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001510 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001511 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001512 // | critical | simd | * |
1513 // | critical | sections | + |
1514 // | critical | section | + |
1515 // | critical | single | + |
1516 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001517 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001518 // | critical |parallel sections| * |
1519 // | critical | task | * |
1520 // | critical | taskyield | * |
1521 // | critical | barrier | + |
1522 // | critical | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001523 // | critical | taskgroup | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001524 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001525 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001526 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001527 // | critical | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001528 // | critical | cancellation | |
1529 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001530 // | critical | cancel | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001531 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001532 // | simd | parallel | |
1533 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001534 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001535 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001536 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001537 // | simd | simd | |
1538 // | simd | sections | |
1539 // | simd | section | |
1540 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001541 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001542 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001543 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001544 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001545 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001546 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001547 // | simd | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001548 // | simd | taskgroup | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001549 // | simd | flush | |
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001550 // | simd | ordered | + (with simd clause) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001551 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001552 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001553 // | simd | teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001554 // | simd | cancellation | |
1555 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001556 // | simd | cancel | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001557 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001558 // | for simd | parallel | |
1559 // | for simd | for | |
1560 // | for simd | for simd | |
1561 // | for simd | master | |
1562 // | for simd | critical | |
1563 // | for simd | simd | |
1564 // | for simd | sections | |
1565 // | for simd | section | |
1566 // | for simd | single | |
1567 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001568 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001569 // | for simd |parallel sections| |
1570 // | for simd | task | |
1571 // | for simd | taskyield | |
1572 // | for simd | barrier | |
1573 // | for simd | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001574 // | for simd | taskgroup | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001575 // | for simd | flush | |
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001576 // | for simd | ordered | + (with simd clause) |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001577 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001578 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001579 // | for simd | teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001580 // | for simd | cancellation | |
1581 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001582 // | for simd | cancel | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001583 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001584 // | parallel for simd| parallel | |
1585 // | parallel for simd| for | |
1586 // | parallel for simd| for simd | |
1587 // | parallel for simd| master | |
1588 // | parallel for simd| critical | |
1589 // | parallel for simd| simd | |
1590 // | parallel for simd| sections | |
1591 // | parallel for simd| section | |
1592 // | parallel for simd| single | |
1593 // | parallel for simd| parallel for | |
1594 // | parallel for simd|parallel for simd| |
1595 // | parallel for simd|parallel sections| |
1596 // | parallel for simd| task | |
1597 // | parallel for simd| taskyield | |
1598 // | parallel for simd| barrier | |
1599 // | parallel for simd| taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001600 // | parallel for simd| taskgroup | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001601 // | parallel for simd| flush | |
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001602 // | parallel for simd| ordered | + (with simd clause) |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001603 // | parallel for simd| atomic | |
1604 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001605 // | parallel for simd| teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001606 // | parallel for simd| cancellation | |
1607 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001608 // | parallel for simd| cancel | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001609 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001610 // | sections | parallel | * |
1611 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001612 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001613 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001614 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001615 // | sections | simd | * |
1616 // | sections | sections | + |
1617 // | sections | section | * |
1618 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001619 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001620 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001621 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001622 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001623 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001624 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001625 // | sections | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001626 // | sections | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001627 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001628 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001629 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001630 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001631 // | sections | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001632 // | sections | cancellation | |
1633 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001634 // | sections | cancel | ! |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001635 // +------------------+-----------------+------------------------------------+
1636 // | section | parallel | * |
1637 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001638 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001639 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001640 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001641 // | section | simd | * |
1642 // | section | sections | + |
1643 // | section | section | + |
1644 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001645 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001646 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001647 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001648 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001649 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001650 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001651 // | section | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001652 // | section | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001653 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001654 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001655 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001656 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001657 // | section | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001658 // | section | cancellation | |
1659 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001660 // | section | cancel | ! |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001661 // +------------------+-----------------+------------------------------------+
1662 // | single | parallel | * |
1663 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001664 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001665 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001666 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001667 // | single | simd | * |
1668 // | single | sections | + |
1669 // | single | section | + |
1670 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001671 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001672 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001673 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001674 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001675 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001676 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001677 // | single | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001678 // | single | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001679 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001680 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001681 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001682 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001683 // | single | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001684 // | single | cancellation | |
1685 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001686 // | single | cancel | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001687 // +------------------+-----------------+------------------------------------+
1688 // | parallel for | parallel | * |
1689 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001690 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001691 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001692 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001693 // | parallel for | simd | * |
1694 // | parallel for | sections | + |
1695 // | parallel for | section | + |
1696 // | parallel for | single | + |
1697 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001698 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001699 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001700 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001701 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001702 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001703 // | parallel for | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001704 // | parallel for | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001705 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001706 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001707 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001708 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001709 // | parallel for | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001710 // | parallel for | cancellation | |
1711 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001712 // | parallel for | cancel | ! |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001713 // +------------------+-----------------+------------------------------------+
1714 // | parallel sections| parallel | * |
1715 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001716 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001717 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001718 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001719 // | parallel sections| simd | * |
1720 // | parallel sections| sections | + |
1721 // | parallel sections| section | * |
1722 // | parallel sections| single | + |
1723 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001724 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001725 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001726 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001727 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001728 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001729 // | parallel sections| taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001730 // | parallel sections| taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001731 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001732 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001733 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001734 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001735 // | parallel sections| teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001736 // | parallel sections| cancellation | |
1737 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001738 // | parallel sections| cancel | ! |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001739 // +------------------+-----------------+------------------------------------+
1740 // | task | parallel | * |
1741 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001742 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001743 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001744 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001745 // | task | simd | * |
1746 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001747 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001748 // | task | single | + |
1749 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001750 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001751 // | task |parallel sections| * |
1752 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001753 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001754 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001755 // | task | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001756 // | task | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001757 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001758 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001759 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001760 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001761 // | task | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001762 // | task | cancellation | |
Alexey Bataev80909872015-07-02 11:25:17 +00001763 // | | point | ! |
1764 // | task | cancel | ! |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001765 // +------------------+-----------------+------------------------------------+
1766 // | ordered | parallel | * |
1767 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001768 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001769 // | ordered | master | * |
1770 // | ordered | critical | * |
1771 // | ordered | simd | * |
1772 // | ordered | sections | + |
1773 // | ordered | section | + |
1774 // | ordered | single | + |
1775 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001776 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001777 // | ordered |parallel sections| * |
1778 // | ordered | task | * |
1779 // | ordered | taskyield | * |
1780 // | ordered | barrier | + |
1781 // | ordered | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001782 // | ordered | taskgroup | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001783 // | ordered | flush | * |
1784 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001785 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001786 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001787 // | ordered | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001788 // | ordered | cancellation | |
1789 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001790 // | ordered | cancel | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001791 // +------------------+-----------------+------------------------------------+
1792 // | atomic | parallel | |
1793 // | atomic | for | |
1794 // | atomic | for simd | |
1795 // | atomic | master | |
1796 // | atomic | critical | |
1797 // | atomic | simd | |
1798 // | atomic | sections | |
1799 // | atomic | section | |
1800 // | atomic | single | |
1801 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001802 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001803 // | atomic |parallel sections| |
1804 // | atomic | task | |
1805 // | atomic | taskyield | |
1806 // | atomic | barrier | |
1807 // | atomic | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001808 // | atomic | taskgroup | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001809 // | atomic | flush | |
1810 // | atomic | ordered | |
1811 // | atomic | atomic | |
1812 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001813 // | atomic | teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001814 // | atomic | cancellation | |
1815 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001816 // | atomic | cancel | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001817 // +------------------+-----------------+------------------------------------+
1818 // | target | parallel | * |
1819 // | target | for | * |
1820 // | target | for simd | * |
1821 // | target | master | * |
1822 // | target | critical | * |
1823 // | target | simd | * |
1824 // | target | sections | * |
1825 // | target | section | * |
1826 // | target | single | * |
1827 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001828 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001829 // | target |parallel sections| * |
1830 // | target | task | * |
1831 // | target | taskyield | * |
1832 // | target | barrier | * |
1833 // | target | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001834 // | target | taskgroup | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001835 // | target | flush | * |
1836 // | target | ordered | * |
1837 // | target | atomic | * |
1838 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001839 // | target | teams | * |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001840 // | target | cancellation | |
1841 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001842 // | target | cancel | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001843 // +------------------+-----------------+------------------------------------+
1844 // | teams | parallel | * |
1845 // | teams | for | + |
1846 // | teams | for simd | + |
1847 // | teams | master | + |
1848 // | teams | critical | + |
1849 // | teams | simd | + |
1850 // | teams | sections | + |
1851 // | teams | section | + |
1852 // | teams | single | + |
1853 // | teams | parallel for | * |
1854 // | teams |parallel for simd| * |
1855 // | teams |parallel sections| * |
1856 // | teams | task | + |
1857 // | teams | taskyield | + |
1858 // | teams | barrier | + |
1859 // | teams | taskwait | + |
Alexey Bataev80909872015-07-02 11:25:17 +00001860 // | teams | taskgroup | + |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001861 // | teams | flush | + |
1862 // | teams | ordered | + |
1863 // | teams | atomic | + |
1864 // | teams | target | + |
1865 // | teams | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001866 // | teams | cancellation | |
1867 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001868 // | teams | cancel | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001869 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00001870 if (Stack->getCurScope()) {
1871 auto ParentRegion = Stack->getParentDirective();
1872 bool NestingProhibited = false;
1873 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001874 enum {
1875 NoRecommend,
1876 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001877 ShouldBeInOrderedRegion,
1878 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001879 } Recommend = NoRecommend;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001880 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001881 // OpenMP [2.16, Nesting of Regions]
1882 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001883 // OpenMP [2.8.1,simd Construct, Restrictions]
1884 // An ordered construct with the simd clause is the only OpenMP construct
1885 // that can appear in the simd region.
Alexey Bataev549210e2014-06-24 04:39:47 +00001886 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1887 return true;
1888 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001889 if (ParentRegion == OMPD_atomic) {
1890 // OpenMP [2.16, Nesting of Regions]
1891 // OpenMP constructs may not be nested inside an atomic region.
1892 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1893 return true;
1894 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001895 if (CurrentRegion == OMPD_section) {
1896 // OpenMP [2.7.2, sections Construct, Restrictions]
1897 // Orphaned section directives are prohibited. That is, the section
1898 // directives must appear within the sections construct and must not be
1899 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001900 if (ParentRegion != OMPD_sections &&
1901 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001902 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1903 << (ParentRegion != OMPD_unknown)
1904 << getOpenMPDirectiveName(ParentRegion);
1905 return true;
1906 }
1907 return false;
1908 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001909 // Allow some constructs to be orphaned (they could be used in functions,
1910 // called from OpenMP regions with the required preconditions).
1911 if (ParentRegion == OMPD_unknown)
1912 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00001913 if (CurrentRegion == OMPD_cancellation_point ||
1914 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001915 // OpenMP [2.16, Nesting of Regions]
1916 // A cancellation point construct for which construct-type-clause is
1917 // taskgroup must be nested inside a task construct. A cancellation
1918 // point construct for which construct-type-clause is not taskgroup must
1919 // be closely nested inside an OpenMP construct that matches the type
1920 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00001921 // A cancel construct for which construct-type-clause is taskgroup must be
1922 // nested inside a task construct. A cancel construct for which
1923 // construct-type-clause is not taskgroup must be closely nested inside an
1924 // OpenMP construct that matches the type specified in
1925 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001926 NestingProhibited =
1927 !((CancelRegion == OMPD_parallel && ParentRegion == OMPD_parallel) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00001928 (CancelRegion == OMPD_for &&
1929 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001930 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
1931 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00001932 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
1933 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001934 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00001935 // OpenMP [2.16, Nesting of Regions]
1936 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001937 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001938 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1939 ParentRegion == OMPD_task;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001940 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1941 // OpenMP [2.16, Nesting of Regions]
1942 // A critical region may not be nested (closely or otherwise) inside a
1943 // critical region with the same name. Note that this restriction is not
1944 // sufficient to prevent deadlock.
1945 SourceLocation PreviousCriticalLoc;
1946 bool DeadLock =
1947 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1948 OpenMPDirectiveKind K,
1949 const DeclarationNameInfo &DNI,
1950 SourceLocation Loc)
1951 ->bool {
1952 if (K == OMPD_critical &&
1953 DNI.getName() == CurrentName.getName()) {
1954 PreviousCriticalLoc = Loc;
1955 return true;
1956 } else
1957 return false;
1958 },
1959 false /* skip top directive */);
1960 if (DeadLock) {
1961 SemaRef.Diag(StartLoc,
1962 diag::err_omp_prohibited_region_critical_same_name)
1963 << CurrentName.getName();
1964 if (PreviousCriticalLoc.isValid())
1965 SemaRef.Diag(PreviousCriticalLoc,
1966 diag::note_omp_previous_critical_region);
1967 return true;
1968 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001969 } else if (CurrentRegion == OMPD_barrier) {
1970 // OpenMP [2.16, Nesting of Regions]
1971 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001972 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001973 NestingProhibited =
1974 isOpenMPWorksharingDirective(ParentRegion) ||
1975 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1976 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001977 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00001978 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001979 // OpenMP [2.16, Nesting of Regions]
1980 // A worksharing region may not be closely nested inside a worksharing,
1981 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001982 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00001983 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001984 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1985 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1986 Recommend = ShouldBeInParallelRegion;
1987 } else if (CurrentRegion == OMPD_ordered) {
1988 // OpenMP [2.16, Nesting of Regions]
1989 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00001990 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001991 // An ordered region must be closely nested inside a loop region (or
1992 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001993 // OpenMP [2.8.1,simd Construct, Restrictions]
1994 // An ordered construct with the simd clause is the only OpenMP construct
1995 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001996 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00001997 ParentRegion == OMPD_task ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001998 !(isOpenMPSimdDirective(ParentRegion) ||
1999 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002000 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002001 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
2002 // OpenMP [2.16, Nesting of Regions]
2003 // If specified, a teams construct must be contained within a target
2004 // construct.
2005 NestingProhibited = ParentRegion != OMPD_target;
2006 Recommend = ShouldBeInTargetRegion;
2007 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2008 }
2009 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
2010 // OpenMP [2.16, Nesting of Regions]
2011 // distribute, parallel, parallel sections, parallel workshare, and the
2012 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2013 // constructs that can be closely nested in the teams region.
2014 // TODO: add distribute directive.
2015 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
2016 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002017 }
2018 if (NestingProhibited) {
2019 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002020 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
2021 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00002022 return true;
2023 }
2024 }
2025 return false;
2026}
2027
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002028static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2029 ArrayRef<OMPClause *> Clauses,
2030 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2031 bool ErrorFound = false;
2032 unsigned NamedModifiersNumber = 0;
2033 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2034 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002035 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002036 for (const auto *C : Clauses) {
2037 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2038 // At most one if clause without a directive-name-modifier can appear on
2039 // the directive.
2040 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2041 if (FoundNameModifiers[CurNM]) {
2042 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2043 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2044 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2045 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002046 } else if (CurNM != OMPD_unknown) {
2047 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002048 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002049 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002050 FoundNameModifiers[CurNM] = IC;
2051 if (CurNM == OMPD_unknown)
2052 continue;
2053 // Check if the specified name modifier is allowed for the current
2054 // directive.
2055 // At most one if clause with the particular directive-name-modifier can
2056 // appear on the directive.
2057 bool MatchFound = false;
2058 for (auto NM : AllowedNameModifiers) {
2059 if (CurNM == NM) {
2060 MatchFound = true;
2061 break;
2062 }
2063 }
2064 if (!MatchFound) {
2065 S.Diag(IC->getNameModifierLoc(),
2066 diag::err_omp_wrong_if_directive_name_modifier)
2067 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2068 ErrorFound = true;
2069 }
2070 }
2071 }
2072 // If any if clause on the directive includes a directive-name-modifier then
2073 // all if clauses on the directive must include a directive-name-modifier.
2074 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2075 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2076 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2077 diag::err_omp_no_more_if_clause);
2078 } else {
2079 std::string Values;
2080 std::string Sep(", ");
2081 unsigned AllowedCnt = 0;
2082 unsigned TotalAllowedNum =
2083 AllowedNameModifiers.size() - NamedModifiersNumber;
2084 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2085 ++Cnt) {
2086 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2087 if (!FoundNameModifiers[NM]) {
2088 Values += "'";
2089 Values += getOpenMPDirectiveName(NM);
2090 Values += "'";
2091 if (AllowedCnt + 2 == TotalAllowedNum)
2092 Values += " or ";
2093 else if (AllowedCnt + 1 != TotalAllowedNum)
2094 Values += Sep;
2095 ++AllowedCnt;
2096 }
2097 }
2098 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2099 diag::err_omp_unnamed_if_clause)
2100 << (TotalAllowedNum > 1) << Values;
2101 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002102 for (auto Loc : NameModifierLoc) {
2103 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2104 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002105 ErrorFound = true;
2106 }
2107 return ErrorFound;
2108}
2109
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002110StmtResult Sema::ActOnOpenMPExecutableDirective(
2111 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2112 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2113 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002114 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002115 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2116 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002117 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002118
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002119 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00002120 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002121 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002122 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002123 if (AStmt) {
2124 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2125
2126 // Check default data sharing attributes for referenced variables.
2127 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2128 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2129 if (DSAChecker.isErrorFound())
2130 return StmtError();
2131 // Generate list of implicitly defined firstprivate variables.
2132 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002133
2134 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2135 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2136 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2137 SourceLocation(), SourceLocation())) {
2138 ClausesWithImplicit.push_back(Implicit);
2139 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2140 DSAChecker.getImplicitFirstprivate().size();
2141 } else
2142 ErrorFound = true;
2143 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002144 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002145
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002146 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002147 switch (Kind) {
2148 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002149 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2150 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002151 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002152 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002153 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002154 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2155 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002156 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002157 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002158 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2159 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002160 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002161 case OMPD_for_simd:
2162 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2163 EndLoc, VarsWithInheritedDSA);
2164 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002165 case OMPD_sections:
2166 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2167 EndLoc);
2168 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002169 case OMPD_section:
2170 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002171 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002172 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2173 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002174 case OMPD_single:
2175 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2176 EndLoc);
2177 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002178 case OMPD_master:
2179 assert(ClausesWithImplicit.empty() &&
2180 "No clauses are allowed for 'omp master' directive");
2181 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2182 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002183 case OMPD_critical:
2184 assert(ClausesWithImplicit.empty() &&
2185 "No clauses are allowed for 'omp critical' directive");
2186 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
2187 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002188 case OMPD_parallel_for:
2189 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2190 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002191 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002192 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002193 case OMPD_parallel_for_simd:
2194 Res = ActOnOpenMPParallelForSimdDirective(
2195 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002196 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002197 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002198 case OMPD_parallel_sections:
2199 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2200 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002201 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002202 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002203 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002204 Res =
2205 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002206 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002207 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002208 case OMPD_taskyield:
2209 assert(ClausesWithImplicit.empty() &&
2210 "No clauses are allowed for 'omp taskyield' directive");
2211 assert(AStmt == nullptr &&
2212 "No associated statement allowed for 'omp taskyield' directive");
2213 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2214 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002215 case OMPD_barrier:
2216 assert(ClausesWithImplicit.empty() &&
2217 "No clauses are allowed for 'omp barrier' directive");
2218 assert(AStmt == nullptr &&
2219 "No associated statement allowed for 'omp barrier' directive");
2220 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2221 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002222 case OMPD_taskwait:
2223 assert(ClausesWithImplicit.empty() &&
2224 "No clauses are allowed for 'omp taskwait' directive");
2225 assert(AStmt == nullptr &&
2226 "No associated statement allowed for 'omp taskwait' directive");
2227 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2228 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002229 case OMPD_taskgroup:
2230 assert(ClausesWithImplicit.empty() &&
2231 "No clauses are allowed for 'omp taskgroup' directive");
2232 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2233 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002234 case OMPD_flush:
2235 assert(AStmt == nullptr &&
2236 "No associated statement allowed for 'omp flush' directive");
2237 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2238 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002239 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002240 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2241 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002242 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002243 case OMPD_atomic:
2244 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2245 EndLoc);
2246 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002247 case OMPD_teams:
2248 Res =
2249 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2250 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002251 case OMPD_target:
2252 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2253 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002254 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002255 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002256 case OMPD_cancellation_point:
2257 assert(ClausesWithImplicit.empty() &&
2258 "No clauses are allowed for 'omp cancellation point' directive");
2259 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2260 "cancellation point' directive");
2261 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2262 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002263 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002264 assert(AStmt == nullptr &&
2265 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002266 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2267 CancelRegion);
2268 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002269 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002270 case OMPD_target_data:
2271 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2272 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002273 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002274 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002275 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002276 llvm_unreachable("OpenMP Directive is not allowed");
2277 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002278 llvm_unreachable("Unknown OpenMP directive");
2279 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002280
Alexey Bataev4acb8592014-07-07 13:01:15 +00002281 for (auto P : VarsWithInheritedDSA) {
2282 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2283 << P.first << P.second->getSourceRange();
2284 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002285 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2286
2287 if (!AllowedNameModifiers.empty())
2288 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2289 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002290
Alexey Bataeved09d242014-05-28 05:53:51 +00002291 if (ErrorFound)
2292 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002293 return Res;
2294}
2295
2296StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2297 Stmt *AStmt,
2298 SourceLocation StartLoc,
2299 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002300 if (!AStmt)
2301 return StmtError();
2302
Alexey Bataev9959db52014-05-06 10:08:46 +00002303 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2304 // 1.2.2 OpenMP Language Terminology
2305 // Structured block - An executable statement with a single entry at the
2306 // top and a single exit at the bottom.
2307 // The point of exit cannot be a branch out of the structured block.
2308 // longjmp() and throw() must not violate the entry/exit criteria.
2309 CS->getCapturedDecl()->setNothrow();
2310
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002311 getCurFunction()->setHasBranchProtectedScope();
2312
Alexey Bataev25e5b442015-09-15 12:52:43 +00002313 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2314 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002315}
2316
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002317namespace {
2318/// \brief Helper class for checking canonical form of the OpenMP loops and
2319/// extracting iteration space of each loop in the loop nest, that will be used
2320/// for IR generation.
2321class OpenMPIterationSpaceChecker {
2322 /// \brief Reference to Sema.
2323 Sema &SemaRef;
2324 /// \brief A location for diagnostics (when there is no some better location).
2325 SourceLocation DefaultLoc;
2326 /// \brief A location for diagnostics (when increment is not compatible).
2327 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002328 /// \brief A source location for referring to loop init later.
2329 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002330 /// \brief A source location for referring to condition later.
2331 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002332 /// \brief A source location for referring to increment later.
2333 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002334 /// \brief Loop variable.
2335 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002336 /// \brief Reference to loop variable.
2337 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002338 /// \brief Lower bound (initializer for the var).
2339 Expr *LB;
2340 /// \brief Upper bound.
2341 Expr *UB;
2342 /// \brief Loop step (increment).
2343 Expr *Step;
2344 /// \brief This flag is true when condition is one of:
2345 /// Var < UB
2346 /// Var <= UB
2347 /// UB > Var
2348 /// UB >= Var
2349 bool TestIsLessOp;
2350 /// \brief This flag is true when condition is strict ( < or > ).
2351 bool TestIsStrictOp;
2352 /// \brief This flag is true when step is subtracted on each iteration.
2353 bool SubtractStep;
2354
2355public:
2356 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2357 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00002358 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
2359 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002360 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
2361 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002362 /// \brief Check init-expr for canonical loop form and save loop counter
2363 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002364 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002365 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2366 /// for less/greater and for strict/non-strict comparison.
2367 bool CheckCond(Expr *S);
2368 /// \brief Check incr-expr for canonical loop form and return true if it
2369 /// does not conform, otherwise save loop step (#Step).
2370 bool CheckInc(Expr *S);
2371 /// \brief Return the loop counter variable.
2372 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002373 /// \brief Return the reference expression to loop counter variable.
2374 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002375 /// \brief Source range of the loop init.
2376 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2377 /// \brief Source range of the loop condition.
2378 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2379 /// \brief Source range of the loop increment.
2380 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2381 /// \brief True if the step should be subtracted.
2382 bool ShouldSubtractStep() const { return SubtractStep; }
2383 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002384 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002385 /// \brief Build the precondition expression for the loops.
2386 Expr *BuildPreCond(Scope *S, Expr *Cond) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002387 /// \brief Build reference expression to the counter be used for codegen.
2388 Expr *BuildCounterVar() const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002389 /// \brief Build reference expression to the private counter be used for
2390 /// codegen.
2391 Expr *BuildPrivateCounterVar() const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002392 /// \brief Build initization of the counter be used for codegen.
2393 Expr *BuildCounterInit() const;
2394 /// \brief Build step of the counter be used for codegen.
2395 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002396 /// \brief Return true if any expression is dependent.
2397 bool Dependent() const;
2398
2399private:
2400 /// \brief Check the right-hand side of an assignment in the increment
2401 /// expression.
2402 bool CheckIncRHS(Expr *RHS);
2403 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002404 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002405 /// \brief Helper to set upper bound.
2406 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002407 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002408 /// \brief Helper to set loop increment.
2409 bool SetStep(Expr *NewStep, bool Subtract);
2410};
2411
2412bool OpenMPIterationSpaceChecker::Dependent() const {
2413 if (!Var) {
2414 assert(!LB && !UB && !Step);
2415 return false;
2416 }
2417 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2418 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2419}
2420
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002421template <typename T>
2422static T *getExprAsWritten(T *E) {
2423 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2424 E = ExprTemp->getSubExpr();
2425
2426 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2427 E = MTE->GetTemporaryExpr();
2428
2429 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2430 E = Binder->getSubExpr();
2431
2432 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2433 E = ICE->getSubExprAsWritten();
2434 return E->IgnoreParens();
2435}
2436
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002437bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2438 DeclRefExpr *NewVarRefExpr,
2439 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002440 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002441 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2442 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002443 if (!NewVar || !NewLB)
2444 return true;
2445 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002446 VarRef = NewVarRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002447 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2448 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002449 if ((Ctor->isCopyOrMoveConstructor() ||
2450 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2451 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002452 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002453 LB = NewLB;
2454 return false;
2455}
2456
2457bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2458 const SourceRange &SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002459 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002460 // State consistency checking to ensure correct usage.
2461 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2462 !TestIsLessOp && !TestIsStrictOp);
2463 if (!NewUB)
2464 return true;
2465 UB = NewUB;
2466 TestIsLessOp = LessOp;
2467 TestIsStrictOp = StrictOp;
2468 ConditionSrcRange = SR;
2469 ConditionLoc = SL;
2470 return false;
2471}
2472
2473bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2474 // State consistency checking to ensure correct usage.
2475 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2476 if (!NewStep)
2477 return true;
2478 if (!NewStep->isValueDependent()) {
2479 // Check that the step is integer expression.
2480 SourceLocation StepLoc = NewStep->getLocStart();
2481 ExprResult Val =
2482 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2483 if (Val.isInvalid())
2484 return true;
2485 NewStep = Val.get();
2486
2487 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2488 // If test-expr is of form var relational-op b and relational-op is < or
2489 // <= then incr-expr must cause var to increase on each iteration of the
2490 // loop. If test-expr is of form var relational-op b and relational-op is
2491 // > or >= then incr-expr must cause var to decrease on each iteration of
2492 // the loop.
2493 // If test-expr is of form b relational-op var and relational-op is < or
2494 // <= then incr-expr must cause var to decrease on each iteration of the
2495 // loop. If test-expr is of form b relational-op var and relational-op is
2496 // > or >= then incr-expr must cause var to increase on each iteration of
2497 // the loop.
2498 llvm::APSInt Result;
2499 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2500 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2501 bool IsConstNeg =
2502 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002503 bool IsConstPos =
2504 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002505 bool IsConstZero = IsConstant && !Result.getBoolValue();
2506 if (UB && (IsConstZero ||
2507 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002508 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002509 SemaRef.Diag(NewStep->getExprLoc(),
2510 diag::err_omp_loop_incr_not_compatible)
2511 << Var << TestIsLessOp << NewStep->getSourceRange();
2512 SemaRef.Diag(ConditionLoc,
2513 diag::note_omp_loop_cond_requres_compatible_incr)
2514 << TestIsLessOp << ConditionSrcRange;
2515 return true;
2516 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002517 if (TestIsLessOp == Subtract) {
2518 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2519 NewStep).get();
2520 Subtract = !Subtract;
2521 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002522 }
2523
2524 Step = NewStep;
2525 SubtractStep = Subtract;
2526 return false;
2527}
2528
Alexey Bataev9c821032015-04-30 04:23:23 +00002529bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002530 // Check init-expr for canonical loop form and save loop counter
2531 // variable - #Var and its initialization value - #LB.
2532 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2533 // var = lb
2534 // integer-type var = lb
2535 // random-access-iterator-type var = lb
2536 // pointer-type var = lb
2537 //
2538 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002539 if (EmitDiags) {
2540 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2541 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002542 return true;
2543 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002544 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002545 if (Expr *E = dyn_cast<Expr>(S))
2546 S = E->IgnoreParens();
2547 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2548 if (BO->getOpcode() == BO_Assign)
2549 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002550 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002551 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002552 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2553 if (DS->isSingleDecl()) {
2554 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00002555 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002556 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002557 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002558 SemaRef.Diag(S->getLocStart(),
2559 diag::ext_omp_loop_not_canonical_init)
2560 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002561 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002562 }
2563 }
2564 }
2565 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2566 if (CE->getOperator() == OO_Equal)
2567 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002568 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2569 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002570
Alexey Bataev9c821032015-04-30 04:23:23 +00002571 if (EmitDiags) {
2572 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2573 << S->getSourceRange();
2574 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002575 return true;
2576}
2577
Alexey Bataev23b69422014-06-18 07:08:49 +00002578/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002579/// variable (which may be the loop variable) if possible.
2580static const VarDecl *GetInitVarDecl(const Expr *E) {
2581 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002582 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002583 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002584 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2585 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002586 if ((Ctor->isCopyOrMoveConstructor() ||
2587 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2588 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002589 E = CE->getArg(0)->IgnoreParenImpCasts();
2590 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2591 if (!DRE)
2592 return nullptr;
2593 return dyn_cast<VarDecl>(DRE->getDecl());
2594}
2595
2596bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2597 // Check test-expr for canonical form, save upper-bound UB, flags for
2598 // less/greater and for strict/non-strict comparison.
2599 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2600 // var relational-op b
2601 // b relational-op var
2602 //
2603 if (!S) {
2604 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2605 return true;
2606 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002607 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002608 SourceLocation CondLoc = S->getLocStart();
2609 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2610 if (BO->isRelationalOp()) {
2611 if (GetInitVarDecl(BO->getLHS()) == Var)
2612 return SetUB(BO->getRHS(),
2613 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2614 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2615 BO->getSourceRange(), BO->getOperatorLoc());
2616 if (GetInitVarDecl(BO->getRHS()) == Var)
2617 return SetUB(BO->getLHS(),
2618 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2619 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2620 BO->getSourceRange(), BO->getOperatorLoc());
2621 }
2622 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2623 if (CE->getNumArgs() == 2) {
2624 auto Op = CE->getOperator();
2625 switch (Op) {
2626 case OO_Greater:
2627 case OO_GreaterEqual:
2628 case OO_Less:
2629 case OO_LessEqual:
2630 if (GetInitVarDecl(CE->getArg(0)) == Var)
2631 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2632 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2633 CE->getOperatorLoc());
2634 if (GetInitVarDecl(CE->getArg(1)) == Var)
2635 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2636 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2637 CE->getOperatorLoc());
2638 break;
2639 default:
2640 break;
2641 }
2642 }
2643 }
2644 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2645 << S->getSourceRange() << Var;
2646 return true;
2647}
2648
2649bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2650 // RHS of canonical loop form increment can be:
2651 // var + incr
2652 // incr + var
2653 // var - incr
2654 //
2655 RHS = RHS->IgnoreParenImpCasts();
2656 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2657 if (BO->isAdditiveOp()) {
2658 bool IsAdd = BO->getOpcode() == BO_Add;
2659 if (GetInitVarDecl(BO->getLHS()) == Var)
2660 return SetStep(BO->getRHS(), !IsAdd);
2661 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2662 return SetStep(BO->getLHS(), false);
2663 }
2664 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2665 bool IsAdd = CE->getOperator() == OO_Plus;
2666 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2667 if (GetInitVarDecl(CE->getArg(0)) == Var)
2668 return SetStep(CE->getArg(1), !IsAdd);
2669 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2670 return SetStep(CE->getArg(0), false);
2671 }
2672 }
2673 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2674 << RHS->getSourceRange() << Var;
2675 return true;
2676}
2677
2678bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2679 // Check incr-expr for canonical loop form and return true if it
2680 // does not conform.
2681 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2682 // ++var
2683 // var++
2684 // --var
2685 // var--
2686 // var += incr
2687 // var -= incr
2688 // var = var + incr
2689 // var = incr + var
2690 // var = var - incr
2691 //
2692 if (!S) {
2693 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2694 return true;
2695 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002696 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002697 S = S->IgnoreParens();
2698 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2699 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2700 return SetStep(
2701 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2702 (UO->isDecrementOp() ? -1 : 1)).get(),
2703 false);
2704 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2705 switch (BO->getOpcode()) {
2706 case BO_AddAssign:
2707 case BO_SubAssign:
2708 if (GetInitVarDecl(BO->getLHS()) == Var)
2709 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2710 break;
2711 case BO_Assign:
2712 if (GetInitVarDecl(BO->getLHS()) == Var)
2713 return CheckIncRHS(BO->getRHS());
2714 break;
2715 default:
2716 break;
2717 }
2718 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2719 switch (CE->getOperator()) {
2720 case OO_PlusPlus:
2721 case OO_MinusMinus:
2722 if (GetInitVarDecl(CE->getArg(0)) == Var)
2723 return SetStep(
2724 SemaRef.ActOnIntegerConstant(
2725 CE->getLocStart(),
2726 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2727 false);
2728 break;
2729 case OO_PlusEqual:
2730 case OO_MinusEqual:
2731 if (GetInitVarDecl(CE->getArg(0)) == Var)
2732 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2733 break;
2734 case OO_Equal:
2735 if (GetInitVarDecl(CE->getArg(0)) == Var)
2736 return CheckIncRHS(CE->getArg(1));
2737 break;
2738 default:
2739 break;
2740 }
2741 }
2742 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2743 << S->getSourceRange() << Var;
2744 return true;
2745}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002746
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002747namespace {
2748// Transform variables declared in GNU statement expressions to new ones to
2749// avoid crash on codegen.
2750class TransformToNewDefs : public TreeTransform<TransformToNewDefs> {
2751 typedef TreeTransform<TransformToNewDefs> BaseTransform;
2752
2753public:
2754 TransformToNewDefs(Sema &SemaRef) : BaseTransform(SemaRef) {}
2755
2756 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
2757 if (auto *VD = cast<VarDecl>(D))
2758 if (!isa<ParmVarDecl>(D) && !isa<VarTemplateSpecializationDecl>(D) &&
2759 !isa<ImplicitParamDecl>(D)) {
2760 auto *NewVD = VarDecl::Create(
2761 SemaRef.Context, VD->getDeclContext(), VD->getLocStart(),
2762 VD->getLocation(), VD->getIdentifier(), VD->getType(),
2763 VD->getTypeSourceInfo(), VD->getStorageClass());
2764 NewVD->setTSCSpec(VD->getTSCSpec());
2765 NewVD->setInit(VD->getInit());
2766 NewVD->setInitStyle(VD->getInitStyle());
2767 NewVD->setExceptionVariable(VD->isExceptionVariable());
2768 NewVD->setNRVOVariable(VD->isNRVOVariable());
2769 NewVD->setCXXForRangeDecl(VD->isInExternCXXContext());
2770 NewVD->setConstexpr(VD->isConstexpr());
2771 NewVD->setInitCapture(VD->isInitCapture());
2772 NewVD->setPreviousDeclInSameBlockScope(
2773 VD->isPreviousDeclInSameBlockScope());
2774 VD->getDeclContext()->addHiddenDecl(NewVD);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002775 if (VD->hasAttrs())
2776 NewVD->setAttrs(VD->getAttrs());
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002777 transformedLocalDecl(VD, NewVD);
2778 return NewVD;
2779 }
2780 return BaseTransform::TransformDefinition(Loc, D);
2781 }
2782
2783 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
2784 if (auto *NewD = TransformDecl(E->getExprLoc(), E->getDecl()))
2785 if (E->getDecl() != NewD) {
2786 NewD->setReferenced();
2787 NewD->markUsed(SemaRef.Context);
2788 return DeclRefExpr::Create(
2789 SemaRef.Context, E->getQualifierLoc(), E->getTemplateKeywordLoc(),
2790 cast<ValueDecl>(NewD), E->refersToEnclosingVariableOrCapture(),
2791 E->getNameInfo(), E->getType(), E->getValueKind());
2792 }
2793 return BaseTransform::TransformDeclRefExpr(E);
2794 }
2795};
2796}
2797
Alexander Musmana5f070a2014-10-01 06:03:56 +00002798/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002799Expr *
2800OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2801 const bool LimitedType) const {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002802 TransformToNewDefs Transform(SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002803 ExprResult Diff;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002804 auto VarType = Var->getType().getNonReferenceType();
2805 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00002806 SemaRef.getLangOpts().CPlusPlus) {
2807 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002808 auto *UBExpr = TestIsLessOp ? UB : LB;
2809 auto *LBExpr = TestIsLessOp ? LB : UB;
2810 Expr *Upper = Transform.TransformExpr(UBExpr).get();
2811 Expr *Lower = Transform.TransformExpr(LBExpr).get();
2812 if (!Upper || !Lower)
2813 return nullptr;
2814 Upper = SemaRef.PerformImplicitConversion(Upper, UBExpr->getType(),
2815 Sema::AA_Converting,
2816 /*AllowExplicit=*/true)
2817 .get();
2818 Lower = SemaRef.PerformImplicitConversion(Lower, LBExpr->getType(),
2819 Sema::AA_Converting,
2820 /*AllowExplicit=*/true)
2821 .get();
2822 if (!Upper || !Lower)
2823 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002824
2825 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2826
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002827 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002828 // BuildBinOp already emitted error, this one is to point user to upper
2829 // and lower bound, and to tell what is passed to 'operator-'.
2830 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2831 << Upper->getSourceRange() << Lower->getSourceRange();
2832 return nullptr;
2833 }
2834 }
2835
2836 if (!Diff.isUsable())
2837 return nullptr;
2838
2839 // Upper - Lower [- 1]
2840 if (TestIsStrictOp)
2841 Diff = SemaRef.BuildBinOp(
2842 S, DefaultLoc, BO_Sub, Diff.get(),
2843 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2844 if (!Diff.isUsable())
2845 return nullptr;
2846
2847 // Upper - Lower [- 1] + Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002848 auto NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
2849 if (NewStep.isInvalid())
2850 return nullptr;
2851 NewStep = SemaRef.PerformImplicitConversion(
2852 NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
2853 /*AllowExplicit=*/true);
2854 if (NewStep.isInvalid())
2855 return nullptr;
2856 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002857 if (!Diff.isUsable())
2858 return nullptr;
2859
2860 // Parentheses (for dumping/debugging purposes only).
2861 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2862 if (!Diff.isUsable())
2863 return nullptr;
2864
2865 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002866 NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
2867 if (NewStep.isInvalid())
2868 return nullptr;
2869 NewStep = SemaRef.PerformImplicitConversion(
2870 NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
2871 /*AllowExplicit=*/true);
2872 if (NewStep.isInvalid())
2873 return nullptr;
2874 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002875 if (!Diff.isUsable())
2876 return nullptr;
2877
Alexander Musman174b3ca2014-10-06 11:16:29 +00002878 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002879 QualType Type = Diff.get()->getType();
2880 auto &C = SemaRef.Context;
2881 bool UseVarType = VarType->hasIntegerRepresentation() &&
2882 C.getTypeSize(Type) > C.getTypeSize(VarType);
2883 if (!Type->isIntegerType() || UseVarType) {
2884 unsigned NewSize =
2885 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
2886 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
2887 : Type->hasSignedIntegerRepresentation();
2888 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
2889 Diff = SemaRef.PerformImplicitConversion(
2890 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
2891 if (!Diff.isUsable())
2892 return nullptr;
2893 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00002894 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00002895 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2896 if (NewSize != C.getTypeSize(Type)) {
2897 if (NewSize < C.getTypeSize(Type)) {
2898 assert(NewSize == 64 && "incorrect loop var size");
2899 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2900 << InitSrcRange << ConditionSrcRange;
2901 }
2902 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002903 NewSize, Type->hasSignedIntegerRepresentation() ||
2904 C.getTypeSize(Type) < NewSize);
Alexander Musman174b3ca2014-10-06 11:16:29 +00002905 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2906 Sema::AA_Converting, true);
2907 if (!Diff.isUsable())
2908 return nullptr;
2909 }
2910 }
2911
Alexander Musmana5f070a2014-10-01 06:03:56 +00002912 return Diff.get();
2913}
2914
Alexey Bataev62dbb972015-04-22 11:59:37 +00002915Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
2916 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
2917 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
2918 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002919 TransformToNewDefs Transform(SemaRef);
2920
2921 auto NewLB = Transform.TransformExpr(LB);
2922 auto NewUB = Transform.TransformExpr(UB);
2923 if (NewLB.isInvalid() || NewUB.isInvalid())
2924 return Cond;
2925 NewLB = SemaRef.PerformImplicitConversion(NewLB.get(), LB->getType(),
2926 Sema::AA_Converting,
2927 /*AllowExplicit=*/true);
2928 NewUB = SemaRef.PerformImplicitConversion(NewUB.get(), UB->getType(),
2929 Sema::AA_Converting,
2930 /*AllowExplicit=*/true);
2931 if (NewLB.isInvalid() || NewUB.isInvalid())
2932 return Cond;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002933 auto CondExpr = SemaRef.BuildBinOp(
2934 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
2935 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002936 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002937 if (CondExpr.isUsable()) {
2938 CondExpr = SemaRef.PerformImplicitConversion(
2939 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
2940 /*AllowExplicit=*/true);
2941 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00002942 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
2943 // Otherwise use original loop conditon and evaluate it in runtime.
2944 return CondExpr.isUsable() ? CondExpr.get() : Cond;
2945}
2946
Alexander Musmana5f070a2014-10-01 06:03:56 +00002947/// \brief Build reference expression to the counter be used for codegen.
2948Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
Alexey Bataeva8899172015-08-06 12:30:57 +00002949 return buildDeclRefExpr(SemaRef, Var, Var->getType().getNonReferenceType(),
2950 DefaultLoc);
2951}
2952
2953Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
2954 if (Var && !Var->isInvalidDecl()) {
2955 auto Type = Var->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002956 auto *PrivateVar =
2957 buildVarDecl(SemaRef, DefaultLoc, Type, Var->getName(),
2958 Var->hasAttrs() ? &Var->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00002959 if (PrivateVar->isInvalidDecl())
2960 return nullptr;
2961 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
2962 }
2963 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002964}
2965
2966/// \brief Build initization of the counter be used for codegen.
2967Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2968
2969/// \brief Build step of the counter be used for codegen.
2970Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2971
2972/// \brief Iteration space of a single for loop.
2973struct LoopIterationSpace {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002974 /// \brief Condition of the loop.
2975 Expr *PreCond;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002976 /// \brief This expression calculates the number of iterations in the loop.
2977 /// It is always possible to calculate it before starting the loop.
2978 Expr *NumIterations;
2979 /// \brief The loop counter variable.
2980 Expr *CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00002981 /// \brief Private loop counter variable.
2982 Expr *PrivateCounterVar;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002983 /// \brief This is initializer for the initial value of #CounterVar.
2984 Expr *CounterInit;
2985 /// \brief This is step for the #CounterVar used to generate its update:
2986 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2987 Expr *CounterStep;
2988 /// \brief Should step be subtracted?
2989 bool Subtract;
2990 /// \brief Source range of the loop init.
2991 SourceRange InitSrcRange;
2992 /// \brief Source range of the loop condition.
2993 SourceRange CondSrcRange;
2994 /// \brief Source range of the loop increment.
2995 SourceRange IncSrcRange;
2996};
2997
Alexey Bataev23b69422014-06-18 07:08:49 +00002998} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002999
Alexey Bataev9c821032015-04-30 04:23:23 +00003000void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3001 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3002 assert(Init && "Expected loop in canonical form.");
3003 unsigned CollapseIteration = DSAStack->getCollapseNumber();
3004 if (CollapseIteration > 0 &&
3005 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3006 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
3007 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3008 DSAStack->addLoopControlVariable(ISC.GetLoopVar());
3009 }
3010 DSAStack->setCollapseNumber(CollapseIteration - 1);
3011 }
3012}
3013
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003014/// \brief Called on a for stmt to check and extract its iteration space
3015/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003016static bool CheckOpenMPIterationSpace(
3017 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3018 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003019 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003020 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
3021 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003022 // OpenMP [2.6, Canonical Loop Form]
3023 // for (init-expr; test-expr; incr-expr) structured-block
3024 auto For = dyn_cast_or_null<ForStmt>(S);
3025 if (!For) {
3026 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003027 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3028 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3029 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3030 if (NestedLoopCount > 1) {
3031 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3032 SemaRef.Diag(DSA.getConstructLoc(),
3033 diag::note_omp_collapse_ordered_expr)
3034 << 2 << CollapseLoopCountExpr->getSourceRange()
3035 << OrderedLoopCountExpr->getSourceRange();
3036 else if (CollapseLoopCountExpr)
3037 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3038 diag::note_omp_collapse_ordered_expr)
3039 << 0 << CollapseLoopCountExpr->getSourceRange();
3040 else
3041 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3042 diag::note_omp_collapse_ordered_expr)
3043 << 1 << OrderedLoopCountExpr->getSourceRange();
3044 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003045 return true;
3046 }
3047 assert(For->getBody());
3048
3049 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3050
3051 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003052 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003053 if (ISC.CheckInit(Init)) {
3054 return true;
3055 }
3056
3057 bool HasErrors = false;
3058
3059 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003060 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003061
3062 // OpenMP [2.6, Canonical Loop Form]
3063 // Var is one of the following:
3064 // A variable of signed or unsigned integer type.
3065 // For C++, a variable of a random access iterator type.
3066 // For C, a variable of a pointer type.
Alexey Bataeva8899172015-08-06 12:30:57 +00003067 auto VarType = Var->getType().getNonReferenceType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003068 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3069 !VarType->isPointerType() &&
3070 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3071 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3072 << SemaRef.getLangOpts().CPlusPlus;
3073 HasErrors = true;
3074 }
3075
Alexey Bataev4acb8592014-07-07 13:01:15 +00003076 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
3077 // Construct
3078 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3079 // parallel for construct is (are) private.
3080 // The loop iteration variable in the associated for-loop of a simd construct
3081 // with just one associated for-loop is linear with a constant-linear-step
3082 // that is the increment of the associated for-loop.
3083 // Exclude loop var from the list of variables with implicitly defined data
3084 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00003085 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003086
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003087 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
3088 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00003089 // The loop iteration variable in the associated for-loop of a simd construct
3090 // with just one associated for-loop may be listed in a linear clause with a
3091 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00003092 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3093 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003094 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003095 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
3096 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3097 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003098 auto PredeterminedCKind =
3099 isOpenMPSimdDirective(DKind)
3100 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3101 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003102 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00003103 DVar.CKind != OMPC_threadprivate && DVar.CKind != PredeterminedCKind) ||
Alexander Musmanf82886e2014-09-18 05:12:34 +00003104 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
3105 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00003106 DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_threadprivate)) &&
3107 ((DVar.CKind != OMPC_private && DVar.CKind != OMPC_threadprivate) ||
3108 DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003109 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00003110 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3111 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataevf2453a02015-05-06 07:25:08 +00003112 if (DVar.RefExpr == nullptr)
3113 DVar.CKind = PredeterminedCKind;
3114 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003115 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003116 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003117 // Make the loop iteration variable private (for worksharing constructs),
3118 // linear (for simd directives with the only one associated loop) or
Alexey Bataev10e775f2015-07-30 11:36:16 +00003119 // lastprivate (for simd directives with several collapsed or ordered
3120 // loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00003121 if (DVar.CKind == OMPC_unknown)
3122 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
3123 /*FromParent=*/false);
Alexey Bataev9c821032015-04-30 04:23:23 +00003124 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003125 }
3126
Alexey Bataev7ff55242014-06-19 09:13:45 +00003127 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00003128
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003129 // Check test-expr.
3130 HasErrors |= ISC.CheckCond(For->getCond());
3131
3132 // Check incr-expr.
3133 HasErrors |= ISC.CheckInc(For->getInc());
3134
Alexander Musmana5f070a2014-10-01 06:03:56 +00003135 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003136 return HasErrors;
3137
Alexander Musmana5f070a2014-10-01 06:03:56 +00003138 // Build the loop's iteration space representation.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003139 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
Alexander Musman174b3ca2014-10-06 11:16:29 +00003140 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
3141 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
Alexander Musmana5f070a2014-10-01 06:03:56 +00003142 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
Alexey Bataeva8899172015-08-06 12:30:57 +00003143 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003144 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3145 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3146 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3147 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3148 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3149 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3150
Alexey Bataev62dbb972015-04-22 11:59:37 +00003151 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3152 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003153 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003154 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003155 ResultIterSpace.CounterInit == nullptr ||
3156 ResultIterSpace.CounterStep == nullptr);
3157
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003158 return HasErrors;
3159}
3160
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003161/// \brief Build 'VarRef = Start.
3162static ExprResult BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc,
3163 ExprResult VarRef, ExprResult Start) {
3164 TransformToNewDefs Transform(SemaRef);
3165 // Build 'VarRef = Start.
3166 auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
3167 if (NewStart.isInvalid())
3168 return ExprError();
3169 NewStart = SemaRef.PerformImplicitConversion(
3170 NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
3171 Sema::AA_Converting,
3172 /*AllowExplicit=*/true);
3173 if (NewStart.isInvalid())
3174 return ExprError();
3175 NewStart = SemaRef.PerformImplicitConversion(
3176 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3177 /*AllowExplicit=*/true);
3178 if (!NewStart.isUsable())
3179 return ExprError();
3180
3181 auto Init =
3182 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3183 return Init;
3184}
3185
Alexander Musmana5f070a2014-10-01 06:03:56 +00003186/// \brief Build 'VarRef = Start + Iter * Step'.
3187static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
3188 SourceLocation Loc, ExprResult VarRef,
3189 ExprResult Start, ExprResult Iter,
3190 ExprResult Step, bool Subtract) {
3191 // Add parentheses (for debugging purposes only).
3192 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3193 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3194 !Step.isUsable())
3195 return ExprError();
3196
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003197 TransformToNewDefs Transform(SemaRef);
3198 auto NewStep = Transform.TransformExpr(Step.get()->IgnoreImplicit());
3199 if (NewStep.isInvalid())
3200 return ExprError();
3201 NewStep = SemaRef.PerformImplicitConversion(
3202 NewStep.get(), Step.get()->IgnoreImplicit()->getType(),
3203 Sema::AA_Converting,
3204 /*AllowExplicit=*/true);
3205 if (NewStep.isInvalid())
3206 return ExprError();
3207 ExprResult Update =
3208 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003209 if (!Update.isUsable())
3210 return ExprError();
3211
3212 // Build 'VarRef = Start + Iter * Step'.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003213 auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
3214 if (NewStart.isInvalid())
3215 return ExprError();
3216 NewStart = SemaRef.PerformImplicitConversion(
3217 NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
3218 Sema::AA_Converting,
3219 /*AllowExplicit=*/true);
3220 if (NewStart.isInvalid())
3221 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003222 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003223 NewStart.get(), Update.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003224 if (!Update.isUsable())
3225 return ExprError();
3226
3227 Update = SemaRef.PerformImplicitConversion(
3228 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3229 if (!Update.isUsable())
3230 return ExprError();
3231
3232 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3233 return Update;
3234}
3235
3236/// \brief Convert integer expression \a E to make it have at least \a Bits
3237/// bits.
3238static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
3239 Sema &SemaRef) {
3240 if (E == nullptr)
3241 return ExprError();
3242 auto &C = SemaRef.Context;
3243 QualType OldType = E->getType();
3244 unsigned HasBits = C.getTypeSize(OldType);
3245 if (HasBits >= Bits)
3246 return ExprResult(E);
3247 // OK to convert to signed, because new type has more bits than old.
3248 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3249 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3250 true);
3251}
3252
3253/// \brief Check if the given expression \a E is a constant integer that fits
3254/// into \a Bits bits.
3255static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3256 if (E == nullptr)
3257 return false;
3258 llvm::APSInt Result;
3259 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3260 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3261 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003262}
3263
3264/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003265/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3266/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003267static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003268CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3269 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3270 DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003271 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003272 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003273 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003274 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003275 // Found 'collapse' clause - calculate collapse number.
3276 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003277 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
3278 NestedLoopCount += Result.getLimitedValue() - 1;
3279 }
3280 if (OrderedLoopCountExpr) {
3281 // Found 'ordered' clause - calculate collapse number.
3282 llvm::APSInt Result;
3283 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
3284 NestedLoopCount += Result.getLimitedValue() - 1;
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003285 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003286 // This is helper routine for loop directives (e.g., 'for', 'simd',
3287 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00003288 SmallVector<LoopIterationSpace, 4> IterSpaces;
3289 IterSpaces.resize(NestedLoopCount);
3290 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003291 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003292 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003293 NestedLoopCount, CollapseLoopCountExpr,
3294 OrderedLoopCountExpr, VarsWithImplicitDSA,
3295 IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003296 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003297 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003298 // OpenMP [2.8.1, simd construct, Restrictions]
3299 // All loops associated with the construct must be perfectly nested; that
3300 // is, there must be no intervening code nor any OpenMP directive between
3301 // any two loops.
3302 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003303 }
3304
Alexander Musmana5f070a2014-10-01 06:03:56 +00003305 Built.clear(/* size */ NestedLoopCount);
3306
3307 if (SemaRef.CurContext->isDependentContext())
3308 return NestedLoopCount;
3309
3310 // An example of what is generated for the following code:
3311 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003312 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003313 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003314 // for (k = 0; k < NK; ++k)
3315 // for (j = J0; j < NJ; j+=2) {
3316 // <loop body>
3317 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003318 //
3319 // We generate the code below.
3320 // Note: the loop body may be outlined in CodeGen.
3321 // Note: some counters may be C++ classes, operator- is used to find number of
3322 // iterations and operator+= to calculate counter value.
3323 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3324 // or i64 is currently supported).
3325 //
3326 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3327 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3328 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3329 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3330 // // similar updates for vars in clauses (e.g. 'linear')
3331 // <loop body (using local i and j)>
3332 // }
3333 // i = NI; // assign final values of counters
3334 // j = NJ;
3335 //
3336
3337 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3338 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003339 // Precondition tests if there is at least one iteration (all conditions are
3340 // true).
3341 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003342 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003343 ExprResult LastIteration32 = WidenIterationCount(
3344 32 /* Bits */, SemaRef.PerformImplicitConversion(
3345 N0->IgnoreImpCasts(), N0->getType(),
3346 Sema::AA_Converting, /*AllowExplicit=*/true)
3347 .get(),
3348 SemaRef);
3349 ExprResult LastIteration64 = WidenIterationCount(
3350 64 /* Bits */, SemaRef.PerformImplicitConversion(
3351 N0->IgnoreImpCasts(), N0->getType(),
3352 Sema::AA_Converting, /*AllowExplicit=*/true)
3353 .get(),
3354 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003355
3356 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3357 return NestedLoopCount;
3358
3359 auto &C = SemaRef.Context;
3360 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3361
3362 Scope *CurScope = DSA.getCurScope();
3363 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003364 if (PreCond.isUsable()) {
3365 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
3366 PreCond.get(), IterSpaces[Cnt].PreCond);
3367 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003368 auto N = IterSpaces[Cnt].NumIterations;
3369 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3370 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003371 LastIteration32 = SemaRef.BuildBinOp(
3372 CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
3373 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3374 Sema::AA_Converting,
3375 /*AllowExplicit=*/true)
3376 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003377 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003378 LastIteration64 = SemaRef.BuildBinOp(
3379 CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
3380 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3381 Sema::AA_Converting,
3382 /*AllowExplicit=*/true)
3383 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003384 }
3385
3386 // Choose either the 32-bit or 64-bit version.
3387 ExprResult LastIteration = LastIteration64;
3388 if (LastIteration32.isUsable() &&
3389 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3390 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3391 FitsInto(
3392 32 /* Bits */,
3393 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3394 LastIteration64.get(), SemaRef)))
3395 LastIteration = LastIteration32;
3396
3397 if (!LastIteration.isUsable())
3398 return 0;
3399
3400 // Save the number of iterations.
3401 ExprResult NumIterations = LastIteration;
3402 {
3403 LastIteration = SemaRef.BuildBinOp(
3404 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
3405 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3406 if (!LastIteration.isUsable())
3407 return 0;
3408 }
3409
3410 // Calculate the last iteration number beforehand instead of doing this on
3411 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3412 llvm::APSInt Result;
3413 bool IsConstant =
3414 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3415 ExprResult CalcLastIteration;
3416 if (!IsConstant) {
3417 SourceLocation SaveLoc;
3418 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00003419 buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003420 ".omp.last.iteration");
Alexey Bataev39f915b82015-05-08 10:41:21 +00003421 ExprResult SaveRef = buildDeclRefExpr(
3422 SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003423 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
3424 SaveRef.get(), LastIteration.get());
3425 LastIteration = SaveRef;
3426
3427 // Prepare SaveRef + 1.
3428 NumIterations = SemaRef.BuildBinOp(
3429 CurScope, SaveLoc, BO_Add, SaveRef.get(),
3430 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3431 if (!NumIterations.isUsable())
3432 return 0;
3433 }
3434
3435 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3436
Alexander Musmanc6388682014-12-15 07:07:06 +00003437 QualType VType = LastIteration.get()->getType();
3438 // Build variables passed into runtime, nesessary for worksharing directives.
3439 ExprResult LB, UB, IL, ST, EUB;
3440 if (isOpenMPWorksharingDirective(DKind)) {
3441 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003442 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3443 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003444 SemaRef.AddInitializerToDecl(
3445 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3446 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3447
3448 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003449 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3450 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003451 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3452 /*DirectInit*/ false,
3453 /*TypeMayContainAuto*/ false);
3454
3455 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3456 // This will be used to implement clause 'lastprivate'.
3457 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00003458 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3459 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003460 SemaRef.AddInitializerToDecl(
3461 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3462 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3463
3464 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev39f915b82015-05-08 10:41:21 +00003465 VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
3466 ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003467 SemaRef.AddInitializerToDecl(
3468 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3469 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3470
3471 // Build expression: UB = min(UB, LastIteration)
3472 // It is nesessary for CodeGen of directives with static scheduling.
3473 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3474 UB.get(), LastIteration.get());
3475 ExprResult CondOp = SemaRef.ActOnConditionalOp(
3476 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
3477 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
3478 CondOp.get());
3479 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
3480 }
3481
3482 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003483 ExprResult IV;
3484 ExprResult Init;
3485 {
Alexey Bataev39f915b82015-05-08 10:41:21 +00003486 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
3487 IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003488 Expr *RHS = isOpenMPWorksharingDirective(DKind)
3489 ? LB.get()
3490 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
3491 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
3492 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003493 }
3494
Alexander Musmanc6388682014-12-15 07:07:06 +00003495 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003496 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00003497 ExprResult Cond =
3498 isOpenMPWorksharingDirective(DKind)
3499 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
3500 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
3501 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003502
3503 // Loop increment (IV = IV + 1)
3504 SourceLocation IncLoc;
3505 ExprResult Inc =
3506 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
3507 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
3508 if (!Inc.isUsable())
3509 return 0;
3510 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00003511 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
3512 if (!Inc.isUsable())
3513 return 0;
3514
3515 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
3516 // Used for directives with static scheduling.
3517 ExprResult NextLB, NextUB;
3518 if (isOpenMPWorksharingDirective(DKind)) {
3519 // LB + ST
3520 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
3521 if (!NextLB.isUsable())
3522 return 0;
3523 // LB = LB + ST
3524 NextLB =
3525 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
3526 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
3527 if (!NextLB.isUsable())
3528 return 0;
3529 // UB + ST
3530 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
3531 if (!NextUB.isUsable())
3532 return 0;
3533 // UB = UB + ST
3534 NextUB =
3535 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
3536 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
3537 if (!NextUB.isUsable())
3538 return 0;
3539 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003540
3541 // Build updates and final values of the loop counters.
3542 bool HasErrors = false;
3543 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003544 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003545 Built.Updates.resize(NestedLoopCount);
3546 Built.Finals.resize(NestedLoopCount);
3547 {
3548 ExprResult Div;
3549 // Go from inner nested loop to outer.
3550 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
3551 LoopIterationSpace &IS = IterSpaces[Cnt];
3552 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
3553 // Build: Iter = (IV / Div) % IS.NumIters
3554 // where Div is product of previous iterations' IS.NumIters.
3555 ExprResult Iter;
3556 if (Div.isUsable()) {
3557 Iter =
3558 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
3559 } else {
3560 Iter = IV;
3561 assert((Cnt == (int)NestedLoopCount - 1) &&
3562 "unusable div expected on first iteration only");
3563 }
3564
3565 if (Cnt != 0 && Iter.isUsable())
3566 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
3567 IS.NumIterations);
3568 if (!Iter.isUsable()) {
3569 HasErrors = true;
3570 break;
3571 }
3572
Alexey Bataev39f915b82015-05-08 10:41:21 +00003573 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
3574 auto *CounterVar = buildDeclRefExpr(
3575 SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
3576 IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
3577 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003578 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
3579 IS.CounterInit);
3580 if (!Init.isUsable()) {
3581 HasErrors = true;
3582 break;
3583 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003584 ExprResult Update =
Alexey Bataev39f915b82015-05-08 10:41:21 +00003585 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003586 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
3587 if (!Update.isUsable()) {
3588 HasErrors = true;
3589 break;
3590 }
3591
3592 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
3593 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00003594 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003595 IS.NumIterations, IS.CounterStep, IS.Subtract);
3596 if (!Final.isUsable()) {
3597 HasErrors = true;
3598 break;
3599 }
3600
3601 // Build Div for the next iteration: Div <- Div * IS.NumIters
3602 if (Cnt != 0) {
3603 if (Div.isUnset())
3604 Div = IS.NumIterations;
3605 else
3606 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
3607 IS.NumIterations);
3608
3609 // Add parentheses (for debugging purposes only).
3610 if (Div.isUsable())
3611 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
3612 if (!Div.isUsable()) {
3613 HasErrors = true;
3614 break;
3615 }
3616 }
3617 if (!Update.isUsable() || !Final.isUsable()) {
3618 HasErrors = true;
3619 break;
3620 }
3621 // Save results
3622 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00003623 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003624 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003625 Built.Updates[Cnt] = Update.get();
3626 Built.Finals[Cnt] = Final.get();
3627 }
3628 }
3629
3630 if (HasErrors)
3631 return 0;
3632
3633 // Save results
3634 Built.IterationVarRef = IV.get();
3635 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00003636 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003637 Built.CalcLastIteration =
3638 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003639 Built.PreCond = PreCond.get();
3640 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003641 Built.Init = Init.get();
3642 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00003643 Built.LB = LB.get();
3644 Built.UB = UB.get();
3645 Built.IL = IL.get();
3646 Built.ST = ST.get();
3647 Built.EUB = EUB.get();
3648 Built.NLB = NextLB.get();
3649 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003650
Alexey Bataevabfc0692014-06-25 06:52:00 +00003651 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003652}
3653
Alexey Bataev10e775f2015-07-30 11:36:16 +00003654static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003655 auto CollapseClauses =
3656 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
3657 if (CollapseClauses.begin() != CollapseClauses.end())
3658 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003659 return nullptr;
3660}
3661
Alexey Bataev10e775f2015-07-30 11:36:16 +00003662static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003663 auto OrderedClauses =
3664 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
3665 if (OrderedClauses.begin() != OrderedClauses.end())
3666 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003667 return nullptr;
3668}
3669
Alexey Bataev66b15b52015-08-21 11:14:16 +00003670static bool checkSimdlenSafelenValues(Sema &S, const Expr *Simdlen,
3671 const Expr *Safelen) {
3672 llvm::APSInt SimdlenRes, SafelenRes;
3673 if (Simdlen->isValueDependent() || Simdlen->isTypeDependent() ||
3674 Simdlen->isInstantiationDependent() ||
3675 Simdlen->containsUnexpandedParameterPack())
3676 return false;
3677 if (Safelen->isValueDependent() || Safelen->isTypeDependent() ||
3678 Safelen->isInstantiationDependent() ||
3679 Safelen->containsUnexpandedParameterPack())
3680 return false;
3681 Simdlen->EvaluateAsInt(SimdlenRes, S.Context);
3682 Safelen->EvaluateAsInt(SafelenRes, S.Context);
3683 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
3684 // If both simdlen and safelen clauses are specified, the value of the simdlen
3685 // parameter must be less than or equal to the value of the safelen parameter.
3686 if (SimdlenRes > SafelenRes) {
3687 S.Diag(Simdlen->getExprLoc(), diag::err_omp_wrong_simdlen_safelen_values)
3688 << Simdlen->getSourceRange() << Safelen->getSourceRange();
3689 return true;
3690 }
3691 return false;
3692}
3693
Alexey Bataev4acb8592014-07-07 13:01:15 +00003694StmtResult Sema::ActOnOpenMPSimdDirective(
3695 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3696 SourceLocation EndLoc,
3697 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003698 if (!AStmt)
3699 return StmtError();
3700
3701 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00003702 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003703 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
3704 // define the nested loops number.
3705 unsigned NestedLoopCount = CheckOpenMPLoop(
3706 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
3707 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003708 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003709 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003710
Alexander Musmana5f070a2014-10-01 06:03:56 +00003711 assert((CurContext->isDependentContext() || B.builtAll()) &&
3712 "omp simd loop exprs were not built");
3713
Alexander Musman3276a272015-03-21 10:12:56 +00003714 if (!CurContext->isDependentContext()) {
3715 // Finalize the clauses that need pre-built expressions for CodeGen.
3716 for (auto C : Clauses) {
3717 if (auto LC = dyn_cast<OMPLinearClause>(C))
3718 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3719 B.NumIterations, *this, CurScope))
3720 return StmtError();
3721 }
3722 }
3723
Alexey Bataev66b15b52015-08-21 11:14:16 +00003724 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
3725 // If both simdlen and safelen clauses are specified, the value of the simdlen
3726 // parameter must be less than or equal to the value of the safelen parameter.
3727 OMPSafelenClause *Safelen = nullptr;
3728 OMPSimdlenClause *Simdlen = nullptr;
3729 for (auto *Clause : Clauses) {
3730 if (Clause->getClauseKind() == OMPC_safelen)
3731 Safelen = cast<OMPSafelenClause>(Clause);
3732 else if (Clause->getClauseKind() == OMPC_simdlen)
3733 Simdlen = cast<OMPSimdlenClause>(Clause);
3734 if (Safelen && Simdlen)
3735 break;
3736 }
3737 if (Simdlen && Safelen &&
3738 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
3739 Safelen->getSafelen()))
3740 return StmtError();
3741
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003742 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003743 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3744 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003745}
3746
Alexey Bataev4acb8592014-07-07 13:01:15 +00003747StmtResult Sema::ActOnOpenMPForDirective(
3748 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3749 SourceLocation EndLoc,
3750 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003751 if (!AStmt)
3752 return StmtError();
3753
3754 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00003755 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003756 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
3757 // define the nested loops number.
3758 unsigned NestedLoopCount = CheckOpenMPLoop(
3759 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
3760 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003761 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00003762 return StmtError();
3763
Alexander Musmana5f070a2014-10-01 06:03:56 +00003764 assert((CurContext->isDependentContext() || B.builtAll()) &&
3765 "omp for loop exprs were not built");
3766
Alexey Bataev54acd402015-08-04 11:18:19 +00003767 if (!CurContext->isDependentContext()) {
3768 // Finalize the clauses that need pre-built expressions for CodeGen.
3769 for (auto C : Clauses) {
3770 if (auto LC = dyn_cast<OMPLinearClause>(C))
3771 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3772 B.NumIterations, *this, CurScope))
3773 return StmtError();
3774 }
3775 }
3776
Alexey Bataevf29276e2014-06-18 04:14:57 +00003777 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003778 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003779 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00003780}
3781
Alexander Musmanf82886e2014-09-18 05:12:34 +00003782StmtResult Sema::ActOnOpenMPForSimdDirective(
3783 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3784 SourceLocation EndLoc,
3785 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003786 if (!AStmt)
3787 return StmtError();
3788
3789 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00003790 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003791 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
3792 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00003793 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00003794 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
3795 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
3796 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003797 if (NestedLoopCount == 0)
3798 return StmtError();
3799
Alexander Musmanc6388682014-12-15 07:07:06 +00003800 assert((CurContext->isDependentContext() || B.builtAll()) &&
3801 "omp for simd loop exprs were not built");
3802
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00003803 if (!CurContext->isDependentContext()) {
3804 // Finalize the clauses that need pre-built expressions for CodeGen.
3805 for (auto C : Clauses) {
3806 if (auto LC = dyn_cast<OMPLinearClause>(C))
3807 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3808 B.NumIterations, *this, CurScope))
3809 return StmtError();
3810 }
3811 }
3812
Alexey Bataev66b15b52015-08-21 11:14:16 +00003813 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
3814 // If both simdlen and safelen clauses are specified, the value of the simdlen
3815 // parameter must be less than or equal to the value of the safelen parameter.
3816 OMPSafelenClause *Safelen = nullptr;
3817 OMPSimdlenClause *Simdlen = nullptr;
3818 for (auto *Clause : Clauses) {
3819 if (Clause->getClauseKind() == OMPC_safelen)
3820 Safelen = cast<OMPSafelenClause>(Clause);
3821 else if (Clause->getClauseKind() == OMPC_simdlen)
3822 Simdlen = cast<OMPSimdlenClause>(Clause);
3823 if (Safelen && Simdlen)
3824 break;
3825 }
3826 if (Simdlen && Safelen &&
3827 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
3828 Safelen->getSafelen()))
3829 return StmtError();
3830
Alexander Musmanf82886e2014-09-18 05:12:34 +00003831 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003832 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3833 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003834}
3835
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003836StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3837 Stmt *AStmt,
3838 SourceLocation StartLoc,
3839 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003840 if (!AStmt)
3841 return StmtError();
3842
3843 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003844 auto BaseStmt = AStmt;
3845 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3846 BaseStmt = CS->getCapturedStmt();
3847 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3848 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00003849 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003850 return StmtError();
3851 // All associated statements must be '#pragma omp section' except for
3852 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00003853 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003854 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3855 if (SectionStmt)
3856 Diag(SectionStmt->getLocStart(),
3857 diag::err_omp_sections_substmt_not_section);
3858 return StmtError();
3859 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00003860 cast<OMPSectionDirective>(SectionStmt)
3861 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003862 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003863 } else {
3864 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3865 return StmtError();
3866 }
3867
3868 getCurFunction()->setHasBranchProtectedScope();
3869
Alexey Bataev25e5b442015-09-15 12:52:43 +00003870 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3871 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003872}
3873
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003874StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3875 SourceLocation StartLoc,
3876 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003877 if (!AStmt)
3878 return StmtError();
3879
3880 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003881
3882 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00003883 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003884
Alexey Bataev25e5b442015-09-15 12:52:43 +00003885 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
3886 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003887}
3888
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003889StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3890 Stmt *AStmt,
3891 SourceLocation StartLoc,
3892 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003893 if (!AStmt)
3894 return StmtError();
3895
3896 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00003897
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003898 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00003899
Alexey Bataev3255bf32015-01-19 05:20:46 +00003900 // OpenMP [2.7.3, single Construct, Restrictions]
3901 // The copyprivate clause must not be used with the nowait clause.
3902 OMPClause *Nowait = nullptr;
3903 OMPClause *Copyprivate = nullptr;
3904 for (auto *Clause : Clauses) {
3905 if (Clause->getClauseKind() == OMPC_nowait)
3906 Nowait = Clause;
3907 else if (Clause->getClauseKind() == OMPC_copyprivate)
3908 Copyprivate = Clause;
3909 if (Copyprivate && Nowait) {
3910 Diag(Copyprivate->getLocStart(),
3911 diag::err_omp_single_copyprivate_with_nowait);
3912 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3913 return StmtError();
3914 }
3915 }
3916
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003917 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3918}
3919
Alexander Musman80c22892014-07-17 08:54:58 +00003920StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3921 SourceLocation StartLoc,
3922 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003923 if (!AStmt)
3924 return StmtError();
3925
3926 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00003927
3928 getCurFunction()->setHasBranchProtectedScope();
3929
3930 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3931}
3932
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003933StmtResult
3934Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3935 Stmt *AStmt, SourceLocation StartLoc,
3936 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003937 if (!AStmt)
3938 return StmtError();
3939
3940 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003941
3942 getCurFunction()->setHasBranchProtectedScope();
3943
3944 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3945 AStmt);
3946}
3947
Alexey Bataev4acb8592014-07-07 13:01:15 +00003948StmtResult Sema::ActOnOpenMPParallelForDirective(
3949 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3950 SourceLocation EndLoc,
3951 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003952 if (!AStmt)
3953 return StmtError();
3954
Alexey Bataev4acb8592014-07-07 13:01:15 +00003955 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3956 // 1.2.2 OpenMP Language Terminology
3957 // Structured block - An executable statement with a single entry at the
3958 // top and a single exit at the bottom.
3959 // The point of exit cannot be a branch out of the structured block.
3960 // longjmp() and throw() must not violate the entry/exit criteria.
3961 CS->getCapturedDecl()->setNothrow();
3962
Alexander Musmanc6388682014-12-15 07:07:06 +00003963 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003964 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
3965 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003966 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00003967 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
3968 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
3969 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003970 if (NestedLoopCount == 0)
3971 return StmtError();
3972
Alexander Musmana5f070a2014-10-01 06:03:56 +00003973 assert((CurContext->isDependentContext() || B.builtAll()) &&
3974 "omp parallel for loop exprs were not built");
3975
Alexey Bataev54acd402015-08-04 11:18:19 +00003976 if (!CurContext->isDependentContext()) {
3977 // Finalize the clauses that need pre-built expressions for CodeGen.
3978 for (auto C : Clauses) {
3979 if (auto LC = dyn_cast<OMPLinearClause>(C))
3980 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3981 B.NumIterations, *this, CurScope))
3982 return StmtError();
3983 }
3984 }
3985
Alexey Bataev4acb8592014-07-07 13:01:15 +00003986 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003987 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003988 NestedLoopCount, Clauses, AStmt, B,
3989 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00003990}
3991
Alexander Musmane4e893b2014-09-23 09:33:00 +00003992StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3993 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3994 SourceLocation EndLoc,
3995 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003996 if (!AStmt)
3997 return StmtError();
3998
Alexander Musmane4e893b2014-09-23 09:33:00 +00003999 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4000 // 1.2.2 OpenMP Language Terminology
4001 // Structured block - An executable statement with a single entry at the
4002 // top and a single exit at the bottom.
4003 // The point of exit cannot be a branch out of the structured block.
4004 // longjmp() and throw() must not violate the entry/exit criteria.
4005 CS->getCapturedDecl()->setNothrow();
4006
Alexander Musmanc6388682014-12-15 07:07:06 +00004007 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004008 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4009 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004010 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004011 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4012 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4013 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004014 if (NestedLoopCount == 0)
4015 return StmtError();
4016
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004017 if (!CurContext->isDependentContext()) {
4018 // Finalize the clauses that need pre-built expressions for CodeGen.
4019 for (auto C : Clauses) {
4020 if (auto LC = dyn_cast<OMPLinearClause>(C))
4021 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4022 B.NumIterations, *this, CurScope))
4023 return StmtError();
4024 }
4025 }
4026
Alexey Bataev66b15b52015-08-21 11:14:16 +00004027 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4028 // If both simdlen and safelen clauses are specified, the value of the simdlen
4029 // parameter must be less than or equal to the value of the safelen parameter.
4030 OMPSafelenClause *Safelen = nullptr;
4031 OMPSimdlenClause *Simdlen = nullptr;
4032 for (auto *Clause : Clauses) {
4033 if (Clause->getClauseKind() == OMPC_safelen)
4034 Safelen = cast<OMPSafelenClause>(Clause);
4035 else if (Clause->getClauseKind() == OMPC_simdlen)
4036 Simdlen = cast<OMPSimdlenClause>(Clause);
4037 if (Safelen && Simdlen)
4038 break;
4039 }
4040 if (Simdlen && Safelen &&
4041 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
4042 Safelen->getSafelen()))
4043 return StmtError();
4044
Alexander Musmane4e893b2014-09-23 09:33:00 +00004045 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004046 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004047 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004048}
4049
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004050StmtResult
4051Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4052 Stmt *AStmt, SourceLocation StartLoc,
4053 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004054 if (!AStmt)
4055 return StmtError();
4056
4057 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004058 auto BaseStmt = AStmt;
4059 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4060 BaseStmt = CS->getCapturedStmt();
4061 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4062 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004063 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004064 return StmtError();
4065 // All associated statements must be '#pragma omp section' except for
4066 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004067 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004068 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4069 if (SectionStmt)
4070 Diag(SectionStmt->getLocStart(),
4071 diag::err_omp_parallel_sections_substmt_not_section);
4072 return StmtError();
4073 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004074 cast<OMPSectionDirective>(SectionStmt)
4075 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004076 }
4077 } else {
4078 Diag(AStmt->getLocStart(),
4079 diag::err_omp_parallel_sections_not_compound_stmt);
4080 return StmtError();
4081 }
4082
4083 getCurFunction()->setHasBranchProtectedScope();
4084
Alexey Bataev25e5b442015-09-15 12:52:43 +00004085 return OMPParallelSectionsDirective::Create(
4086 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004087}
4088
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004089StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4090 Stmt *AStmt, SourceLocation StartLoc,
4091 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004092 if (!AStmt)
4093 return StmtError();
4094
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004095 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4096 // 1.2.2 OpenMP Language Terminology
4097 // Structured block - An executable statement with a single entry at the
4098 // top and a single exit at the bottom.
4099 // The point of exit cannot be a branch out of the structured block.
4100 // longjmp() and throw() must not violate the entry/exit criteria.
4101 CS->getCapturedDecl()->setNothrow();
4102
4103 getCurFunction()->setHasBranchProtectedScope();
4104
Alexey Bataev25e5b442015-09-15 12:52:43 +00004105 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4106 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004107}
4108
Alexey Bataev68446b72014-07-18 07:47:19 +00004109StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4110 SourceLocation EndLoc) {
4111 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4112}
4113
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004114StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4115 SourceLocation EndLoc) {
4116 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4117}
4118
Alexey Bataev2df347a2014-07-18 10:17:07 +00004119StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4120 SourceLocation EndLoc) {
4121 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4122}
4123
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004124StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4125 SourceLocation StartLoc,
4126 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004127 if (!AStmt)
4128 return StmtError();
4129
4130 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004131
4132 getCurFunction()->setHasBranchProtectedScope();
4133
4134 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4135}
4136
Alexey Bataev6125da92014-07-21 11:26:11 +00004137StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4138 SourceLocation StartLoc,
4139 SourceLocation EndLoc) {
4140 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4141 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4142}
4143
Alexey Bataev346265e2015-09-25 10:37:12 +00004144StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4145 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004146 SourceLocation StartLoc,
4147 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004148 if (!AStmt)
4149 return StmtError();
4150
4151 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004152
4153 getCurFunction()->setHasBranchProtectedScope();
4154
Alexey Bataev346265e2015-09-25 10:37:12 +00004155 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004156 OMPSIMDClause *SC = nullptr;
Alexey Bataev346265e2015-09-25 10:37:12 +00004157 for (auto *C: Clauses) {
4158 if (C->getClauseKind() == OMPC_threads)
4159 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004160 else if (C->getClauseKind() == OMPC_simd)
4161 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004162 }
4163
4164 // TODO: this must happen only if 'threads' clause specified or if no clauses
4165 // is specified.
4166 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4167 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4168 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) << (TC != nullptr);
4169 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4170 return StmtError();
4171 }
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004172 if (!SC && isOpenMPSimdDirective(DSAStack->getParentDirective())) {
4173 // OpenMP [2.8.1,simd Construct, Restrictions]
4174 // An ordered construct with the simd clause is the only OpenMP construct
4175 // that can appear in the simd region.
4176 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
4177 return StmtError();
4178 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004179
4180 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004181}
4182
Alexey Bataev1d160b12015-03-13 12:27:31 +00004183namespace {
4184/// \brief Helper class for checking expression in 'omp atomic [update]'
4185/// construct.
4186class OpenMPAtomicUpdateChecker {
4187 /// \brief Error results for atomic update expressions.
4188 enum ExprAnalysisErrorCode {
4189 /// \brief A statement is not an expression statement.
4190 NotAnExpression,
4191 /// \brief Expression is not builtin binary or unary operation.
4192 NotABinaryOrUnaryExpression,
4193 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4194 NotAnUnaryIncDecExpression,
4195 /// \brief An expression is not of scalar type.
4196 NotAScalarType,
4197 /// \brief A binary operation is not an assignment operation.
4198 NotAnAssignmentOp,
4199 /// \brief RHS part of the binary operation is not a binary expression.
4200 NotABinaryExpression,
4201 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4202 /// expression.
4203 NotABinaryOperator,
4204 /// \brief RHS binary operation does not have reference to the updated LHS
4205 /// part.
4206 NotAnUpdateExpression,
4207 /// \brief No errors is found.
4208 NoError
4209 };
4210 /// \brief Reference to Sema.
4211 Sema &SemaRef;
4212 /// \brief A location for note diagnostics (when error is found).
4213 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004214 /// \brief 'x' lvalue part of the source atomic expression.
4215 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004216 /// \brief 'expr' rvalue part of the source atomic expression.
4217 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004218 /// \brief Helper expression of the form
4219 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4220 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4221 Expr *UpdateExpr;
4222 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4223 /// important for non-associative operations.
4224 bool IsXLHSInRHSPart;
4225 BinaryOperatorKind Op;
4226 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004227 /// \brief true if the source expression is a postfix unary operation, false
4228 /// if it is a prefix unary operation.
4229 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004230
4231public:
4232 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00004233 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00004234 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00004235 /// \brief Check specified statement that it is suitable for 'atomic update'
4236 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00004237 /// expression. If DiagId and NoteId == 0, then only check is performed
4238 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00004239 /// \param DiagId Diagnostic which should be emitted if error is found.
4240 /// \param NoteId Diagnostic note for the main error message.
4241 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00004242 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004243 /// \brief Return the 'x' lvalue part of the source atomic expression.
4244 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00004245 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4246 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00004247 /// \brief Return the update expression used in calculation of the updated
4248 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4249 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4250 Expr *getUpdateExpr() const { return UpdateExpr; }
4251 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4252 /// false otherwise.
4253 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4254
Alexey Bataevb78ca832015-04-01 03:33:17 +00004255 /// \brief true if the source expression is a postfix unary operation, false
4256 /// if it is a prefix unary operation.
4257 bool isPostfixUpdate() const { return IsPostfixUpdate; }
4258
Alexey Bataev1d160b12015-03-13 12:27:31 +00004259private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00004260 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4261 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004262};
4263} // namespace
4264
4265bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4266 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4267 ExprAnalysisErrorCode ErrorFound = NoError;
4268 SourceLocation ErrorLoc, NoteLoc;
4269 SourceRange ErrorRange, NoteRange;
4270 // Allowed constructs are:
4271 // x = x binop expr;
4272 // x = expr binop x;
4273 if (AtomicBinOp->getOpcode() == BO_Assign) {
4274 X = AtomicBinOp->getLHS();
4275 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4276 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4277 if (AtomicInnerBinOp->isMultiplicativeOp() ||
4278 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4279 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00004280 Op = AtomicInnerBinOp->getOpcode();
4281 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004282 auto *LHS = AtomicInnerBinOp->getLHS();
4283 auto *RHS = AtomicInnerBinOp->getRHS();
4284 llvm::FoldingSetNodeID XId, LHSId, RHSId;
4285 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4286 /*Canonical=*/true);
4287 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4288 /*Canonical=*/true);
4289 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4290 /*Canonical=*/true);
4291 if (XId == LHSId) {
4292 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004293 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004294 } else if (XId == RHSId) {
4295 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004296 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004297 } else {
4298 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4299 ErrorRange = AtomicInnerBinOp->getSourceRange();
4300 NoteLoc = X->getExprLoc();
4301 NoteRange = X->getSourceRange();
4302 ErrorFound = NotAnUpdateExpression;
4303 }
4304 } else {
4305 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4306 ErrorRange = AtomicInnerBinOp->getSourceRange();
4307 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4308 NoteRange = SourceRange(NoteLoc, NoteLoc);
4309 ErrorFound = NotABinaryOperator;
4310 }
4311 } else {
4312 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4313 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4314 ErrorFound = NotABinaryExpression;
4315 }
4316 } else {
4317 ErrorLoc = AtomicBinOp->getExprLoc();
4318 ErrorRange = AtomicBinOp->getSourceRange();
4319 NoteLoc = AtomicBinOp->getOperatorLoc();
4320 NoteRange = SourceRange(NoteLoc, NoteLoc);
4321 ErrorFound = NotAnAssignmentOp;
4322 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004323 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004324 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4325 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4326 return true;
4327 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00004328 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004329 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004330}
4331
4332bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
4333 unsigned NoteId) {
4334 ExprAnalysisErrorCode ErrorFound = NoError;
4335 SourceLocation ErrorLoc, NoteLoc;
4336 SourceRange ErrorRange, NoteRange;
4337 // Allowed constructs are:
4338 // x++;
4339 // x--;
4340 // ++x;
4341 // --x;
4342 // x binop= expr;
4343 // x = x binop expr;
4344 // x = expr binop x;
4345 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
4346 AtomicBody = AtomicBody->IgnoreParenImpCasts();
4347 if (AtomicBody->getType()->isScalarType() ||
4348 AtomicBody->isInstantiationDependent()) {
4349 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
4350 AtomicBody->IgnoreParenImpCasts())) {
4351 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00004352 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00004353 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00004354 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004355 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004356 X = AtomicCompAssignOp->getLHS();
4357 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004358 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
4359 AtomicBody->IgnoreParenImpCasts())) {
4360 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00004361 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
4362 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004363 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00004364 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
4365 // Check for Unary Operation
4366 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004367 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004368 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
4369 OpLoc = AtomicUnaryOp->getOperatorLoc();
4370 X = AtomicUnaryOp->getSubExpr();
4371 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
4372 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004373 } else {
4374 ErrorFound = NotAnUnaryIncDecExpression;
4375 ErrorLoc = AtomicUnaryOp->getExprLoc();
4376 ErrorRange = AtomicUnaryOp->getSourceRange();
4377 NoteLoc = AtomicUnaryOp->getOperatorLoc();
4378 NoteRange = SourceRange(NoteLoc, NoteLoc);
4379 }
Alexey Bataev5a195472015-09-04 12:55:50 +00004380 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004381 ErrorFound = NotABinaryOrUnaryExpression;
4382 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
4383 NoteRange = ErrorRange = AtomicBody->getSourceRange();
4384 }
4385 } else {
4386 ErrorFound = NotAScalarType;
4387 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
4388 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4389 }
4390 } else {
4391 ErrorFound = NotAnExpression;
4392 NoteLoc = ErrorLoc = S->getLocStart();
4393 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4394 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004395 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004396 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4397 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4398 return true;
4399 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00004400 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004401 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00004402 // Build an update expression of form 'OpaqueValueExpr(x) binop
4403 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
4404 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
4405 auto *OVEX = new (SemaRef.getASTContext())
4406 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
4407 auto *OVEExpr = new (SemaRef.getASTContext())
4408 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
4409 auto Update =
4410 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
4411 IsXLHSInRHSPart ? OVEExpr : OVEX);
4412 if (Update.isInvalid())
4413 return true;
4414 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
4415 Sema::AA_Casting);
4416 if (Update.isInvalid())
4417 return true;
4418 UpdateExpr = Update.get();
4419 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00004420 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004421}
4422
Alexey Bataev0162e452014-07-22 10:10:35 +00004423StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
4424 Stmt *AStmt,
4425 SourceLocation StartLoc,
4426 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004427 if (!AStmt)
4428 return StmtError();
4429
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004430 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00004431 // 1.2.2 OpenMP Language Terminology
4432 // Structured block - An executable statement with a single entry at the
4433 // top and a single exit at the bottom.
4434 // The point of exit cannot be a branch out of the structured block.
4435 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00004436 OpenMPClauseKind AtomicKind = OMPC_unknown;
4437 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004438 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00004439 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00004440 C->getClauseKind() == OMPC_update ||
4441 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00004442 if (AtomicKind != OMPC_unknown) {
4443 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
4444 << SourceRange(C->getLocStart(), C->getLocEnd());
4445 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
4446 << getOpenMPClauseName(AtomicKind);
4447 } else {
4448 AtomicKind = C->getClauseKind();
4449 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004450 }
4451 }
4452 }
Alexey Bataev62cec442014-11-18 10:14:22 +00004453
Alexey Bataev459dec02014-07-24 06:46:57 +00004454 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00004455 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
4456 Body = EWC->getSubExpr();
4457
Alexey Bataev62cec442014-11-18 10:14:22 +00004458 Expr *X = nullptr;
4459 Expr *V = nullptr;
4460 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004461 Expr *UE = nullptr;
4462 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004463 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00004464 // OpenMP [2.12.6, atomic Construct]
4465 // In the next expressions:
4466 // * x and v (as applicable) are both l-value expressions with scalar type.
4467 // * During the execution of an atomic region, multiple syntactic
4468 // occurrences of x must designate the same storage location.
4469 // * Neither of v and expr (as applicable) may access the storage location
4470 // designated by x.
4471 // * Neither of x and expr (as applicable) may access the storage location
4472 // designated by v.
4473 // * expr is an expression with scalar type.
4474 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
4475 // * binop, binop=, ++, and -- are not overloaded operators.
4476 // * The expression x binop expr must be numerically equivalent to x binop
4477 // (expr). This requirement is satisfied if the operators in expr have
4478 // precedence greater than binop, or by using parentheses around expr or
4479 // subexpressions of expr.
4480 // * The expression expr binop x must be numerically equivalent to (expr)
4481 // binop x. This requirement is satisfied if the operators in expr have
4482 // precedence equal to or greater than binop, or by using parentheses around
4483 // expr or subexpressions of expr.
4484 // * For forms that allow multiple occurrences of x, the number of times
4485 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00004486 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004487 enum {
4488 NotAnExpression,
4489 NotAnAssignmentOp,
4490 NotAScalarType,
4491 NotAnLValue,
4492 NoError
4493 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00004494 SourceLocation ErrorLoc, NoteLoc;
4495 SourceRange ErrorRange, NoteRange;
4496 // If clause is read:
4497 // v = x;
4498 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
4499 auto AtomicBinOp =
4500 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4501 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
4502 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
4503 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
4504 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
4505 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
4506 if (!X->isLValue() || !V->isLValue()) {
4507 auto NotLValueExpr = X->isLValue() ? V : X;
4508 ErrorFound = NotAnLValue;
4509 ErrorLoc = AtomicBinOp->getExprLoc();
4510 ErrorRange = AtomicBinOp->getSourceRange();
4511 NoteLoc = NotLValueExpr->getExprLoc();
4512 NoteRange = NotLValueExpr->getSourceRange();
4513 }
4514 } else if (!X->isInstantiationDependent() ||
4515 !V->isInstantiationDependent()) {
4516 auto NotScalarExpr =
4517 (X->isInstantiationDependent() || X->getType()->isScalarType())
4518 ? V
4519 : X;
4520 ErrorFound = NotAScalarType;
4521 ErrorLoc = AtomicBinOp->getExprLoc();
4522 ErrorRange = AtomicBinOp->getSourceRange();
4523 NoteLoc = NotScalarExpr->getExprLoc();
4524 NoteRange = NotScalarExpr->getSourceRange();
4525 }
Alexey Bataev5a195472015-09-04 12:55:50 +00004526 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00004527 ErrorFound = NotAnAssignmentOp;
4528 ErrorLoc = AtomicBody->getExprLoc();
4529 ErrorRange = AtomicBody->getSourceRange();
4530 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4531 : AtomicBody->getExprLoc();
4532 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4533 : AtomicBody->getSourceRange();
4534 }
4535 } else {
4536 ErrorFound = NotAnExpression;
4537 NoteLoc = ErrorLoc = Body->getLocStart();
4538 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00004539 }
Alexey Bataev62cec442014-11-18 10:14:22 +00004540 if (ErrorFound != NoError) {
4541 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
4542 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00004543 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
4544 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00004545 return StmtError();
4546 } else if (CurContext->isDependentContext())
4547 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00004548 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004549 enum {
4550 NotAnExpression,
4551 NotAnAssignmentOp,
4552 NotAScalarType,
4553 NotAnLValue,
4554 NoError
4555 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00004556 SourceLocation ErrorLoc, NoteLoc;
4557 SourceRange ErrorRange, NoteRange;
4558 // If clause is write:
4559 // x = expr;
4560 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
4561 auto AtomicBinOp =
4562 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4563 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00004564 X = AtomicBinOp->getLHS();
4565 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00004566 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
4567 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
4568 if (!X->isLValue()) {
4569 ErrorFound = NotAnLValue;
4570 ErrorLoc = AtomicBinOp->getExprLoc();
4571 ErrorRange = AtomicBinOp->getSourceRange();
4572 NoteLoc = X->getExprLoc();
4573 NoteRange = X->getSourceRange();
4574 }
4575 } else if (!X->isInstantiationDependent() ||
4576 !E->isInstantiationDependent()) {
4577 auto NotScalarExpr =
4578 (X->isInstantiationDependent() || X->getType()->isScalarType())
4579 ? E
4580 : X;
4581 ErrorFound = NotAScalarType;
4582 ErrorLoc = AtomicBinOp->getExprLoc();
4583 ErrorRange = AtomicBinOp->getSourceRange();
4584 NoteLoc = NotScalarExpr->getExprLoc();
4585 NoteRange = NotScalarExpr->getSourceRange();
4586 }
Alexey Bataev5a195472015-09-04 12:55:50 +00004587 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00004588 ErrorFound = NotAnAssignmentOp;
4589 ErrorLoc = AtomicBody->getExprLoc();
4590 ErrorRange = AtomicBody->getSourceRange();
4591 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4592 : AtomicBody->getExprLoc();
4593 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4594 : AtomicBody->getSourceRange();
4595 }
4596 } else {
4597 ErrorFound = NotAnExpression;
4598 NoteLoc = ErrorLoc = Body->getLocStart();
4599 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00004600 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00004601 if (ErrorFound != NoError) {
4602 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
4603 << ErrorRange;
4604 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
4605 << NoteRange;
4606 return StmtError();
4607 } else if (CurContext->isDependentContext())
4608 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004609 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004610 // If clause is update:
4611 // x++;
4612 // x--;
4613 // ++x;
4614 // --x;
4615 // x binop= expr;
4616 // x = x binop expr;
4617 // x = expr binop x;
4618 OpenMPAtomicUpdateChecker Checker(*this);
4619 if (Checker.checkStatement(
4620 Body, (AtomicKind == OMPC_update)
4621 ? diag::err_omp_atomic_update_not_expression_statement
4622 : diag::err_omp_atomic_not_expression_statement,
4623 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00004624 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004625 if (!CurContext->isDependentContext()) {
4626 E = Checker.getExpr();
4627 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004628 UE = Checker.getUpdateExpr();
4629 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00004630 }
Alexey Bataev459dec02014-07-24 06:46:57 +00004631 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004632 enum {
4633 NotAnAssignmentOp,
4634 NotACompoundStatement,
4635 NotTwoSubstatements,
4636 NotASpecificExpression,
4637 NoError
4638 } ErrorFound = NoError;
4639 SourceLocation ErrorLoc, NoteLoc;
4640 SourceRange ErrorRange, NoteRange;
4641 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
4642 // If clause is a capture:
4643 // v = x++;
4644 // v = x--;
4645 // v = ++x;
4646 // v = --x;
4647 // v = x binop= expr;
4648 // v = x = x binop expr;
4649 // v = x = expr binop x;
4650 auto *AtomicBinOp =
4651 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4652 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
4653 V = AtomicBinOp->getLHS();
4654 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
4655 OpenMPAtomicUpdateChecker Checker(*this);
4656 if (Checker.checkStatement(
4657 Body, diag::err_omp_atomic_capture_not_expression_statement,
4658 diag::note_omp_atomic_update))
4659 return StmtError();
4660 E = Checker.getExpr();
4661 X = Checker.getX();
4662 UE = Checker.getUpdateExpr();
4663 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4664 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00004665 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004666 ErrorLoc = AtomicBody->getExprLoc();
4667 ErrorRange = AtomicBody->getSourceRange();
4668 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4669 : AtomicBody->getExprLoc();
4670 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4671 : AtomicBody->getSourceRange();
4672 ErrorFound = NotAnAssignmentOp;
4673 }
4674 if (ErrorFound != NoError) {
4675 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
4676 << ErrorRange;
4677 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4678 return StmtError();
4679 } else if (CurContext->isDependentContext()) {
4680 UE = V = E = X = nullptr;
4681 }
4682 } else {
4683 // If clause is a capture:
4684 // { v = x; x = expr; }
4685 // { v = x; x++; }
4686 // { v = x; x--; }
4687 // { v = x; ++x; }
4688 // { v = x; --x; }
4689 // { v = x; x binop= expr; }
4690 // { v = x; x = x binop expr; }
4691 // { v = x; x = expr binop x; }
4692 // { x++; v = x; }
4693 // { x--; v = x; }
4694 // { ++x; v = x; }
4695 // { --x; v = x; }
4696 // { x binop= expr; v = x; }
4697 // { x = x binop expr; v = x; }
4698 // { x = expr binop x; v = x; }
4699 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
4700 // Check that this is { expr1; expr2; }
4701 if (CS->size() == 2) {
4702 auto *First = CS->body_front();
4703 auto *Second = CS->body_back();
4704 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
4705 First = EWC->getSubExpr()->IgnoreParenImpCasts();
4706 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
4707 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
4708 // Need to find what subexpression is 'v' and what is 'x'.
4709 OpenMPAtomicUpdateChecker Checker(*this);
4710 bool IsUpdateExprFound = !Checker.checkStatement(Second);
4711 BinaryOperator *BinOp = nullptr;
4712 if (IsUpdateExprFound) {
4713 BinOp = dyn_cast<BinaryOperator>(First);
4714 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4715 }
4716 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4717 // { v = x; x++; }
4718 // { v = x; x--; }
4719 // { v = x; ++x; }
4720 // { v = x; --x; }
4721 // { v = x; x binop= expr; }
4722 // { v = x; x = x binop expr; }
4723 // { v = x; x = expr binop x; }
4724 // Check that the first expression has form v = x.
4725 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4726 llvm::FoldingSetNodeID XId, PossibleXId;
4727 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4728 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4729 IsUpdateExprFound = XId == PossibleXId;
4730 if (IsUpdateExprFound) {
4731 V = BinOp->getLHS();
4732 X = Checker.getX();
4733 E = Checker.getExpr();
4734 UE = Checker.getUpdateExpr();
4735 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00004736 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004737 }
4738 }
4739 if (!IsUpdateExprFound) {
4740 IsUpdateExprFound = !Checker.checkStatement(First);
4741 BinOp = nullptr;
4742 if (IsUpdateExprFound) {
4743 BinOp = dyn_cast<BinaryOperator>(Second);
4744 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4745 }
4746 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4747 // { x++; v = x; }
4748 // { x--; v = x; }
4749 // { ++x; v = x; }
4750 // { --x; v = x; }
4751 // { x binop= expr; v = x; }
4752 // { x = x binop expr; v = x; }
4753 // { x = expr binop x; v = x; }
4754 // Check that the second expression has form v = x.
4755 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4756 llvm::FoldingSetNodeID XId, PossibleXId;
4757 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4758 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4759 IsUpdateExprFound = XId == PossibleXId;
4760 if (IsUpdateExprFound) {
4761 V = BinOp->getLHS();
4762 X = Checker.getX();
4763 E = Checker.getExpr();
4764 UE = Checker.getUpdateExpr();
4765 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00004766 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004767 }
4768 }
4769 }
4770 if (!IsUpdateExprFound) {
4771 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00004772 auto *FirstExpr = dyn_cast<Expr>(First);
4773 auto *SecondExpr = dyn_cast<Expr>(Second);
4774 if (!FirstExpr || !SecondExpr ||
4775 !(FirstExpr->isInstantiationDependent() ||
4776 SecondExpr->isInstantiationDependent())) {
4777 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
4778 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004779 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00004780 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
4781 : First->getLocStart();
4782 NoteRange = ErrorRange = FirstBinOp
4783 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00004784 : SourceRange(ErrorLoc, ErrorLoc);
4785 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00004786 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
4787 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
4788 ErrorFound = NotAnAssignmentOp;
4789 NoteLoc = ErrorLoc = SecondBinOp
4790 ? SecondBinOp->getOperatorLoc()
4791 : Second->getLocStart();
4792 NoteRange = ErrorRange =
4793 SecondBinOp ? SecondBinOp->getSourceRange()
4794 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00004795 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00004796 auto *PossibleXRHSInFirst =
4797 FirstBinOp->getRHS()->IgnoreParenImpCasts();
4798 auto *PossibleXLHSInSecond =
4799 SecondBinOp->getLHS()->IgnoreParenImpCasts();
4800 llvm::FoldingSetNodeID X1Id, X2Id;
4801 PossibleXRHSInFirst->Profile(X1Id, Context,
4802 /*Canonical=*/true);
4803 PossibleXLHSInSecond->Profile(X2Id, Context,
4804 /*Canonical=*/true);
4805 IsUpdateExprFound = X1Id == X2Id;
4806 if (IsUpdateExprFound) {
4807 V = FirstBinOp->getLHS();
4808 X = SecondBinOp->getLHS();
4809 E = SecondBinOp->getRHS();
4810 UE = nullptr;
4811 IsXLHSInRHSPart = false;
4812 IsPostfixUpdate = true;
4813 } else {
4814 ErrorFound = NotASpecificExpression;
4815 ErrorLoc = FirstBinOp->getExprLoc();
4816 ErrorRange = FirstBinOp->getSourceRange();
4817 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
4818 NoteRange = SecondBinOp->getRHS()->getSourceRange();
4819 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004820 }
4821 }
4822 }
4823 }
4824 } else {
4825 NoteLoc = ErrorLoc = Body->getLocStart();
4826 NoteRange = ErrorRange =
4827 SourceRange(Body->getLocStart(), Body->getLocStart());
4828 ErrorFound = NotTwoSubstatements;
4829 }
4830 } else {
4831 NoteLoc = ErrorLoc = Body->getLocStart();
4832 NoteRange = ErrorRange =
4833 SourceRange(Body->getLocStart(), Body->getLocStart());
4834 ErrorFound = NotACompoundStatement;
4835 }
4836 if (ErrorFound != NoError) {
4837 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
4838 << ErrorRange;
4839 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4840 return StmtError();
4841 } else if (CurContext->isDependentContext()) {
4842 UE = V = E = X = nullptr;
4843 }
Alexey Bataev459dec02014-07-24 06:46:57 +00004844 }
Alexey Bataevdea47612014-07-23 07:46:59 +00004845 }
Alexey Bataev0162e452014-07-22 10:10:35 +00004846
4847 getCurFunction()->setHasBranchProtectedScope();
4848
Alexey Bataev62cec442014-11-18 10:14:22 +00004849 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00004850 X, V, E, UE, IsXLHSInRHSPart,
4851 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00004852}
4853
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004854StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
4855 Stmt *AStmt,
4856 SourceLocation StartLoc,
4857 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004858 if (!AStmt)
4859 return StmtError();
4860
4861 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004862
Alexey Bataev13314bf2014-10-09 04:18:56 +00004863 // OpenMP [2.16, Nesting of Regions]
4864 // If specified, a teams construct must be contained within a target
4865 // construct. That target construct must contain no statements or directives
4866 // outside of the teams construct.
4867 if (DSAStack->hasInnerTeamsRegion()) {
4868 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
4869 bool OMPTeamsFound = true;
4870 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
4871 auto I = CS->body_begin();
4872 while (I != CS->body_end()) {
4873 auto OED = dyn_cast<OMPExecutableDirective>(*I);
4874 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
4875 OMPTeamsFound = false;
4876 break;
4877 }
4878 ++I;
4879 }
4880 assert(I != CS->body_end() && "Not found statement");
4881 S = *I;
4882 }
4883 if (!OMPTeamsFound) {
4884 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
4885 Diag(DSAStack->getInnerTeamsRegionLoc(),
4886 diag::note_omp_nested_teams_construct_here);
4887 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
4888 << isa<OMPExecutableDirective>(S);
4889 return StmtError();
4890 }
4891 }
4892
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004893 getCurFunction()->setHasBranchProtectedScope();
4894
4895 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4896}
4897
Michael Wong65f367f2015-07-21 13:44:28 +00004898StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
4899 Stmt *AStmt,
4900 SourceLocation StartLoc,
4901 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004902 if (!AStmt)
4903 return StmtError();
4904
4905 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4906
Michael Wong65f367f2015-07-21 13:44:28 +00004907 getCurFunction()->setHasBranchProtectedScope();
4908
4909 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
4910 AStmt);
4911}
4912
Alexey Bataev13314bf2014-10-09 04:18:56 +00004913StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
4914 Stmt *AStmt, SourceLocation StartLoc,
4915 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004916 if (!AStmt)
4917 return StmtError();
4918
Alexey Bataev13314bf2014-10-09 04:18:56 +00004919 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4920 // 1.2.2 OpenMP Language Terminology
4921 // Structured block - An executable statement with a single entry at the
4922 // top and a single exit at the bottom.
4923 // The point of exit cannot be a branch out of the structured block.
4924 // longjmp() and throw() must not violate the entry/exit criteria.
4925 CS->getCapturedDecl()->setNothrow();
4926
4927 getCurFunction()->setHasBranchProtectedScope();
4928
4929 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4930}
4931
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004932StmtResult
4933Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
4934 SourceLocation EndLoc,
4935 OpenMPDirectiveKind CancelRegion) {
4936 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
4937 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
4938 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4939 << getOpenMPDirectiveName(CancelRegion);
4940 return StmtError();
4941 }
4942 if (DSAStack->isParentNowaitRegion()) {
4943 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
4944 return StmtError();
4945 }
4946 if (DSAStack->isParentOrderedRegion()) {
4947 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
4948 return StmtError();
4949 }
4950 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
4951 CancelRegion);
4952}
4953
Alexey Bataev87933c72015-09-18 08:07:34 +00004954StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
4955 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00004956 SourceLocation EndLoc,
4957 OpenMPDirectiveKind CancelRegion) {
4958 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
4959 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
4960 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4961 << getOpenMPDirectiveName(CancelRegion);
4962 return StmtError();
4963 }
4964 if (DSAStack->isParentNowaitRegion()) {
4965 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
4966 return StmtError();
4967 }
4968 if (DSAStack->isParentOrderedRegion()) {
4969 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
4970 return StmtError();
4971 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004972 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00004973 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
4974 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00004975}
4976
Alexey Bataeved09d242014-05-28 05:53:51 +00004977OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004978 SourceLocation StartLoc,
4979 SourceLocation LParenLoc,
4980 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004981 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004982 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00004983 case OMPC_final:
4984 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
4985 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00004986 case OMPC_num_threads:
4987 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
4988 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004989 case OMPC_safelen:
4990 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
4991 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00004992 case OMPC_simdlen:
4993 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
4994 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00004995 case OMPC_collapse:
4996 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
4997 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004998 case OMPC_ordered:
4999 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
5000 break;
Michael Wonge710d542015-08-07 16:16:36 +00005001 case OMPC_device:
5002 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
5003 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005004 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005005 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005006 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005007 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005008 case OMPC_private:
5009 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00005010 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005011 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005012 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00005013 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005014 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005015 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005016 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00005017 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005018 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005019 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005020 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005021 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005022 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005023 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005024 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005025 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005026 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005027 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00005028 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005029 case OMPC_simd:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005030 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005031 llvm_unreachable("Clause is not allowed.");
5032 }
5033 return Res;
5034}
5035
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005036OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
5037 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005038 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005039 SourceLocation NameModifierLoc,
5040 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005041 SourceLocation EndLoc) {
5042 Expr *ValExpr = Condition;
5043 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
5044 !Condition->isInstantiationDependent() &&
5045 !Condition->containsUnexpandedParameterPack()) {
5046 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00005047 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005048 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005049 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005050
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005051 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005052 }
5053
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005054 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
5055 NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005056}
5057
Alexey Bataev3778b602014-07-17 07:32:53 +00005058OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
5059 SourceLocation StartLoc,
5060 SourceLocation LParenLoc,
5061 SourceLocation EndLoc) {
5062 Expr *ValExpr = Condition;
5063 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
5064 !Condition->isInstantiationDependent() &&
5065 !Condition->containsUnexpandedParameterPack()) {
5066 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
5067 Condition->getExprLoc(), Condition);
5068 if (Val.isInvalid())
5069 return nullptr;
5070
5071 ValExpr = Val.get();
5072 }
5073
5074 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
5075}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005076ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
5077 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00005078 if (!Op)
5079 return ExprError();
5080
5081 class IntConvertDiagnoser : public ICEConvertDiagnoser {
5082 public:
5083 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00005084 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00005085 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
5086 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005087 return S.Diag(Loc, diag::err_omp_not_integral) << T;
5088 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005089 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
5090 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005091 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
5092 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005093 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
5094 QualType T,
5095 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005096 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
5097 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005098 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
5099 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005100 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00005101 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00005102 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005103 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
5104 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005105 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
5106 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005107 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
5108 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005109 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00005110 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00005111 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005112 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
5113 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005114 llvm_unreachable("conversion functions are permitted");
5115 }
5116 } ConvertDiagnoser;
5117 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
5118}
5119
5120OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
5121 SourceLocation StartLoc,
5122 SourceLocation LParenLoc,
5123 SourceLocation EndLoc) {
5124 Expr *ValExpr = NumThreads;
5125 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
Alexey Bataev568a8332014-03-06 06:15:19 +00005126 !NumThreads->containsUnexpandedParameterPack()) {
5127 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
5128 ExprResult Val =
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005129 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
Alexey Bataev568a8332014-03-06 06:15:19 +00005130 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005131 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00005132
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005133 ValExpr = Val.get();
Alexey Bataev568a8332014-03-06 06:15:19 +00005134
5135 // OpenMP [2.5, Restrictions]
5136 // The num_threads expression must evaluate to a positive integer value.
5137 llvm::APSInt Result;
Alexey Bataeved09d242014-05-28 05:53:51 +00005138 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
5139 !Result.isStrictlyPositive()) {
Alexey Bataev568a8332014-03-06 06:15:19 +00005140 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
5141 << "num_threads" << NumThreads->getSourceRange();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005142 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00005143 }
5144 }
5145
Alexey Bataeved09d242014-05-28 05:53:51 +00005146 return new (Context)
5147 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00005148}
5149
Alexey Bataev62c87d22014-03-21 04:51:18 +00005150ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
5151 OpenMPClauseKind CKind) {
5152 if (!E)
5153 return ExprError();
5154 if (E->isValueDependent() || E->isTypeDependent() ||
5155 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005156 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00005157 llvm::APSInt Result;
5158 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
5159 if (ICE.isInvalid())
5160 return ExprError();
5161 if (!Result.isStrictlyPositive()) {
5162 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
5163 << getOpenMPClauseName(CKind) << E->getSourceRange();
5164 return ExprError();
5165 }
Alexander Musman09184fe2014-09-30 05:29:28 +00005166 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
5167 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
5168 << E->getSourceRange();
5169 return ExprError();
5170 }
Alexey Bataev9c821032015-04-30 04:23:23 +00005171 if (CKind == OMPC_collapse) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00005172 DSAStack->setCollapseNumber(DSAStack->getCollapseNumber() - 1 +
5173 Result.getExtValue());
5174 } else if (CKind == OMPC_ordered) {
5175 DSAStack->setCollapseNumber(DSAStack->getCollapseNumber() - 1 +
5176 Result.getExtValue());
Alexey Bataev9c821032015-04-30 04:23:23 +00005177 }
Alexey Bataev62c87d22014-03-21 04:51:18 +00005178 return ICE;
5179}
5180
5181OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
5182 SourceLocation LParenLoc,
5183 SourceLocation EndLoc) {
5184 // OpenMP [2.8.1, simd construct, Description]
5185 // The parameter of the safelen clause must be a constant
5186 // positive integer expression.
5187 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
5188 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005189 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00005190 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005191 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00005192}
5193
Alexey Bataev66b15b52015-08-21 11:14:16 +00005194OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
5195 SourceLocation LParenLoc,
5196 SourceLocation EndLoc) {
5197 // OpenMP [2.8.1, simd construct, Description]
5198 // The parameter of the simdlen clause must be a constant
5199 // positive integer expression.
5200 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
5201 if (Simdlen.isInvalid())
5202 return nullptr;
5203 return new (Context)
5204 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
5205}
5206
Alexander Musman64d33f12014-06-04 07:53:32 +00005207OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
5208 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00005209 SourceLocation LParenLoc,
5210 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00005211 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00005212 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00005213 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00005214 // The parameter of the collapse clause must be a constant
5215 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00005216 ExprResult NumForLoopsResult =
5217 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
5218 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00005219 return nullptr;
5220 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00005221 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00005222}
5223
Alexey Bataev10e775f2015-07-30 11:36:16 +00005224OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
5225 SourceLocation EndLoc,
5226 SourceLocation LParenLoc,
5227 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00005228 // OpenMP [2.7.1, loop construct, Description]
5229 // OpenMP [2.8.1, simd construct, Description]
5230 // OpenMP [2.9.6, distribute construct, Description]
5231 // The parameter of the ordered clause must be a constant
5232 // positive integer expression if any.
5233 if (NumForLoops && LParenLoc.isValid()) {
5234 ExprResult NumForLoopsResult =
5235 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
5236 if (NumForLoopsResult.isInvalid())
5237 return nullptr;
5238 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00005239 } else
5240 NumForLoops = nullptr;
5241 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00005242 return new (Context)
5243 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
5244}
5245
Alexey Bataeved09d242014-05-28 05:53:51 +00005246OMPClause *Sema::ActOnOpenMPSimpleClause(
5247 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
5248 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005249 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005250 switch (Kind) {
5251 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00005252 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00005253 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
5254 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005255 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005256 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00005257 Res = ActOnOpenMPProcBindClause(
5258 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
5259 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005260 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005261 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00005262 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00005263 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00005264 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005265 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00005266 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005267 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005268 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005269 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00005270 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00005271 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005272 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00005273 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005274 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005275 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005276 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005277 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00005278 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005279 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005280 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005281 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005282 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005283 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005284 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005285 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005286 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005287 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005288 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00005289 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00005290 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005291 case OMPC_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005292 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005293 llvm_unreachable("Clause is not allowed.");
5294 }
5295 return Res;
5296}
5297
5298OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
5299 SourceLocation KindKwLoc,
5300 SourceLocation StartLoc,
5301 SourceLocation LParenLoc,
5302 SourceLocation EndLoc) {
5303 if (Kind == OMPC_DEFAULT_unknown) {
5304 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005305 static_assert(OMPC_DEFAULT_unknown > 0,
5306 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00005307 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005308 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005309 Values += "'";
5310 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
5311 Values += "'";
5312 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005313 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005314 Values += " or ";
5315 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005316 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005317 break;
5318 default:
5319 Values += Sep;
5320 break;
5321 }
5322 }
5323 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00005324 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005325 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005326 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00005327 switch (Kind) {
5328 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005329 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005330 break;
5331 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005332 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005333 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005334 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005335 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00005336 break;
5337 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005338 return new (Context)
5339 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005340}
5341
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005342OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
5343 SourceLocation KindKwLoc,
5344 SourceLocation StartLoc,
5345 SourceLocation LParenLoc,
5346 SourceLocation EndLoc) {
5347 if (Kind == OMPC_PROC_BIND_unknown) {
5348 std::string Values;
5349 std::string Sep(", ");
5350 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
5351 Values += "'";
5352 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
5353 Values += "'";
5354 switch (i) {
5355 case OMPC_PROC_BIND_unknown - 2:
5356 Values += " or ";
5357 break;
5358 case OMPC_PROC_BIND_unknown - 1:
5359 break;
5360 default:
5361 Values += Sep;
5362 break;
5363 }
5364 }
5365 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00005366 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005367 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005368 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005369 return new (Context)
5370 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005371}
5372
Alexey Bataev56dafe82014-06-20 07:16:17 +00005373OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
5374 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
5375 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005376 SourceLocation ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00005377 SourceLocation EndLoc) {
5378 OMPClause *Res = nullptr;
5379 switch (Kind) {
5380 case OMPC_schedule:
5381 Res = ActOnOpenMPScheduleClause(
5382 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005383 LParenLoc, ArgumentLoc, DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00005384 break;
5385 case OMPC_if:
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005386 Res =
5387 ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument), Expr,
5388 StartLoc, LParenLoc, ArgumentLoc, DelimLoc, EndLoc);
5389 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00005390 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005391 case OMPC_num_threads:
5392 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005393 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005394 case OMPC_collapse:
5395 case OMPC_default:
5396 case OMPC_proc_bind:
5397 case OMPC_private:
5398 case OMPC_firstprivate:
5399 case OMPC_lastprivate:
5400 case OMPC_shared:
5401 case OMPC_reduction:
5402 case OMPC_linear:
5403 case OMPC_aligned:
5404 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005405 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005406 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00005407 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005408 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005409 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005410 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005411 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005412 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005413 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005414 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005415 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005416 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005417 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00005418 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00005419 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005420 case OMPC_simd:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005421 case OMPC_unknown:
5422 llvm_unreachable("Clause is not allowed.");
5423 }
5424 return Res;
5425}
5426
5427OMPClause *Sema::ActOnOpenMPScheduleClause(
5428 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
5429 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
5430 SourceLocation EndLoc) {
5431 if (Kind == OMPC_SCHEDULE_unknown) {
5432 std::string Values;
5433 std::string Sep(", ");
5434 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
5435 Values += "'";
5436 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
5437 Values += "'";
5438 switch (i) {
5439 case OMPC_SCHEDULE_unknown - 2:
5440 Values += " or ";
5441 break;
5442 case OMPC_SCHEDULE_unknown - 1:
5443 break;
5444 default:
5445 Values += Sep;
5446 break;
5447 }
5448 }
5449 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
5450 << Values << getOpenMPClauseName(OMPC_schedule);
5451 return nullptr;
5452 }
5453 Expr *ValExpr = ChunkSize;
Alexey Bataev040d5402015-05-12 08:35:28 +00005454 Expr *HelperValExpr = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00005455 if (ChunkSize) {
5456 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
5457 !ChunkSize->isInstantiationDependent() &&
5458 !ChunkSize->containsUnexpandedParameterPack()) {
5459 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
5460 ExprResult Val =
5461 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
5462 if (Val.isInvalid())
5463 return nullptr;
5464
5465 ValExpr = Val.get();
5466
5467 // OpenMP [2.7.1, Restrictions]
5468 // chunk_size must be a loop invariant integer expression with a positive
5469 // value.
5470 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00005471 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
5472 if (Result.isSigned() && !Result.isStrictlyPositive()) {
5473 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
5474 << "schedule" << ChunkSize->getSourceRange();
5475 return nullptr;
5476 }
5477 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
5478 auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
5479 ChunkSize->getType(), ".chunk.");
5480 auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
5481 ChunkSize->getExprLoc(),
5482 /*RefersToCapture=*/true);
5483 HelperValExpr = ImpVarRef;
Alexey Bataev56dafe82014-06-20 07:16:17 +00005484 }
5485 }
5486 }
5487
5488 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
Alexey Bataev040d5402015-05-12 08:35:28 +00005489 EndLoc, Kind, ValExpr, HelperValExpr);
Alexey Bataev56dafe82014-06-20 07:16:17 +00005490}
5491
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005492OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
5493 SourceLocation StartLoc,
5494 SourceLocation EndLoc) {
5495 OMPClause *Res = nullptr;
5496 switch (Kind) {
5497 case OMPC_ordered:
5498 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
5499 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00005500 case OMPC_nowait:
5501 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
5502 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005503 case OMPC_untied:
5504 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
5505 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005506 case OMPC_mergeable:
5507 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
5508 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005509 case OMPC_read:
5510 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
5511 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00005512 case OMPC_write:
5513 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
5514 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005515 case OMPC_update:
5516 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
5517 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00005518 case OMPC_capture:
5519 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
5520 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005521 case OMPC_seq_cst:
5522 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
5523 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00005524 case OMPC_threads:
5525 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
5526 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005527 case OMPC_simd:
5528 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
5529 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005530 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00005531 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005532 case OMPC_num_threads:
5533 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005534 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005535 case OMPC_collapse:
5536 case OMPC_schedule:
5537 case OMPC_private:
5538 case OMPC_firstprivate:
5539 case OMPC_lastprivate:
5540 case OMPC_shared:
5541 case OMPC_reduction:
5542 case OMPC_linear:
5543 case OMPC_aligned:
5544 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005545 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005546 case OMPC_default:
5547 case OMPC_proc_bind:
5548 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005549 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005550 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00005551 case OMPC_device:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005552 case OMPC_unknown:
5553 llvm_unreachable("Clause is not allowed.");
5554 }
5555 return Res;
5556}
5557
Alexey Bataev236070f2014-06-20 11:19:47 +00005558OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
5559 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005560 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00005561 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
5562}
5563
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005564OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
5565 SourceLocation EndLoc) {
5566 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
5567}
5568
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005569OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
5570 SourceLocation EndLoc) {
5571 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
5572}
5573
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005574OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
5575 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005576 return new (Context) OMPReadClause(StartLoc, EndLoc);
5577}
5578
Alexey Bataevdea47612014-07-23 07:46:59 +00005579OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
5580 SourceLocation EndLoc) {
5581 return new (Context) OMPWriteClause(StartLoc, EndLoc);
5582}
5583
Alexey Bataev67a4f222014-07-23 10:25:33 +00005584OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
5585 SourceLocation EndLoc) {
5586 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
5587}
5588
Alexey Bataev459dec02014-07-24 06:46:57 +00005589OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
5590 SourceLocation EndLoc) {
5591 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
5592}
5593
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005594OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
5595 SourceLocation EndLoc) {
5596 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
5597}
5598
Alexey Bataev346265e2015-09-25 10:37:12 +00005599OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
5600 SourceLocation EndLoc) {
5601 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
5602}
5603
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005604OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
5605 SourceLocation EndLoc) {
5606 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
5607}
5608
Alexey Bataevc5e02582014-06-16 07:08:35 +00005609OMPClause *Sema::ActOnOpenMPVarListClause(
5610 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
5611 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
5612 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005613 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Alexey Bataev182227b2015-08-20 10:54:39 +00005614 OpenMPLinearClauseKind LinKind, SourceLocation DepLinLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005615 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005616 switch (Kind) {
5617 case OMPC_private:
5618 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5619 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005620 case OMPC_firstprivate:
5621 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5622 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005623 case OMPC_lastprivate:
5624 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5625 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00005626 case OMPC_shared:
5627 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
5628 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005629 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00005630 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
5631 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005632 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00005633 case OMPC_linear:
5634 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Alexey Bataev182227b2015-08-20 10:54:39 +00005635 LinKind, DepLinLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00005636 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005637 case OMPC_aligned:
5638 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
5639 ColonLoc, EndLoc);
5640 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005641 case OMPC_copyin:
5642 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
5643 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00005644 case OMPC_copyprivate:
5645 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5646 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00005647 case OMPC_flush:
5648 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
5649 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005650 case OMPC_depend:
Alexey Bataev182227b2015-08-20 10:54:39 +00005651 Res = ActOnOpenMPDependClause(DepKind, DepLinLoc, ColonLoc, VarList, StartLoc,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005652 LParenLoc, EndLoc);
5653 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005654 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00005655 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00005656 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00005657 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005658 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00005659 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005660 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005661 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005662 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005663 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00005664 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005665 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005666 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005667 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005668 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005669 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005670 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005671 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005672 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00005673 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00005674 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005675 case OMPC_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005676 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005677 llvm_unreachable("Clause is not allowed.");
5678 }
5679 return Res;
5680}
5681
5682OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
5683 SourceLocation StartLoc,
5684 SourceLocation LParenLoc,
5685 SourceLocation EndLoc) {
5686 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00005687 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00005688 for (auto &RefExpr : VarList) {
5689 assert(RefExpr && "NULL expr in OpenMP private clause.");
5690 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005691 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005692 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005693 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005694 continue;
5695 }
5696
Alexey Bataeved09d242014-05-28 05:53:51 +00005697 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005698 // OpenMP [2.1, C/C++]
5699 // A list item is a variable name.
5700 // OpenMP [2.9.3.3, Restrictions, p.1]
5701 // A variable that is part of another variable (as an array or
5702 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005703 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005704 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005705 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005706 continue;
5707 }
5708 Decl *D = DE->getDecl();
5709 VarDecl *VD = cast<VarDecl>(D);
5710
5711 QualType Type = VD->getType();
5712 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5713 // It will be analyzed later.
5714 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005715 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005716 continue;
5717 }
5718
5719 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5720 // A variable that appears in a private clause must not have an incomplete
5721 // type or a reference type.
5722 if (RequireCompleteType(ELoc, Type,
5723 diag::err_omp_private_incomplete_type)) {
5724 continue;
5725 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00005726 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005727
Alexey Bataev758e55e2013-09-06 18:03:48 +00005728 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5729 // in a Construct]
5730 // Variables with the predetermined data-sharing attributes may not be
5731 // listed in data-sharing attributes clauses, except for the cases
5732 // listed below. For these exceptions only, listing a predetermined
5733 // variable in a data-sharing attribute clause is allowed and overrides
5734 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005735 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005736 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005737 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5738 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005739 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005740 continue;
5741 }
5742
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005743 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00005744 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005745 DSAStack->getCurrentDirective() == OMPD_task) {
5746 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5747 << getOpenMPClauseName(OMPC_private) << Type
5748 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5749 bool IsDecl =
5750 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5751 Diag(VD->getLocation(),
5752 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5753 << VD;
5754 continue;
5755 }
5756
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005757 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
5758 // A variable of class type (or array thereof) that appears in a private
5759 // clause requires an accessible, unambiguous default constructor for the
5760 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00005761 // Generate helper private variable and initialize it with the default
5762 // value. The address of the original variable is replaced by the address of
5763 // the new private variable in CodeGen. This new variable is not added to
5764 // IdResolver, so the code in the OpenMP region uses original variable for
5765 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005766 Type = Type.getUnqualifiedType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00005767 auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName(),
5768 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005769 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005770 if (VDPrivate->isInvalidDecl())
5771 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005772 auto VDPrivateRefExpr = buildDeclRefExpr(
5773 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev03b340a2014-10-21 03:16:40 +00005774
Alexey Bataev758e55e2013-09-06 18:03:48 +00005775 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005776 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005777 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005778 }
5779
Alexey Bataeved09d242014-05-28 05:53:51 +00005780 if (Vars.empty())
5781 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005782
Alexey Bataev03b340a2014-10-21 03:16:40 +00005783 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
5784 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005785}
5786
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005787namespace {
5788class DiagsUninitializedSeveretyRAII {
5789private:
5790 DiagnosticsEngine &Diags;
5791 SourceLocation SavedLoc;
5792 bool IsIgnored;
5793
5794public:
5795 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
5796 bool IsIgnored)
5797 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
5798 if (!IsIgnored) {
5799 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
5800 /*Map*/ diag::Severity::Ignored, Loc);
5801 }
5802 }
5803 ~DiagsUninitializedSeveretyRAII() {
5804 if (!IsIgnored)
5805 Diags.popMappings(SavedLoc);
5806 }
5807};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005808}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005809
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005810OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
5811 SourceLocation StartLoc,
5812 SourceLocation LParenLoc,
5813 SourceLocation EndLoc) {
5814 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005815 SmallVector<Expr *, 8> PrivateCopies;
5816 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005817 bool IsImplicitClause =
5818 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
5819 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
5820
Alexey Bataeved09d242014-05-28 05:53:51 +00005821 for (auto &RefExpr : VarList) {
5822 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
5823 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005824 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005825 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005826 PrivateCopies.push_back(nullptr);
5827 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005828 continue;
5829 }
5830
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005831 SourceLocation ELoc =
5832 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005833 // OpenMP [2.1, C/C++]
5834 // A list item is a variable name.
5835 // OpenMP [2.9.3.3, Restrictions, p.1]
5836 // A variable that is part of another variable (as an array or
5837 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005838 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005839 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005840 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005841 continue;
5842 }
5843 Decl *D = DE->getDecl();
5844 VarDecl *VD = cast<VarDecl>(D);
5845
5846 QualType Type = VD->getType();
5847 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5848 // It will be analyzed later.
5849 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005850 PrivateCopies.push_back(nullptr);
5851 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005852 continue;
5853 }
5854
5855 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5856 // A variable that appears in a private clause must not have an incomplete
5857 // type or a reference type.
5858 if (RequireCompleteType(ELoc, Type,
5859 diag::err_omp_firstprivate_incomplete_type)) {
5860 continue;
5861 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00005862 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005863
5864 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
5865 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00005866 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005867 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005868 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005869
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005870 // If an implicit firstprivate variable found it was checked already.
5871 if (!IsImplicitClause) {
5872 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005873 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005874 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
5875 // A list item that specifies a given variable may not appear in more
5876 // than one clause on the same directive, except that a variable may be
5877 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005878 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00005879 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005880 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00005881 << getOpenMPClauseName(DVar.CKind)
5882 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005883 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005884 continue;
5885 }
5886
5887 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5888 // in a Construct]
5889 // Variables with the predetermined data-sharing attributes may not be
5890 // listed in data-sharing attributes clauses, except for the cases
5891 // listed below. For these exceptions only, listing a predetermined
5892 // variable in a data-sharing attribute clause is allowed and overrides
5893 // the variable's predetermined data-sharing attributes.
5894 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5895 // in a Construct, C/C++, p.2]
5896 // Variables with const-qualified type having no mutable member may be
5897 // listed in a firstprivate clause, even if they are static data members.
5898 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
5899 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
5900 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00005901 << getOpenMPClauseName(DVar.CKind)
5902 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005903 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005904 continue;
5905 }
5906
Alexey Bataevf29276e2014-06-18 04:14:57 +00005907 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005908 // OpenMP [2.9.3.4, Restrictions, p.2]
5909 // A list item that is private within a parallel region must not appear
5910 // in a firstprivate clause on a worksharing construct if any of the
5911 // worksharing regions arising from the worksharing construct ever bind
5912 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00005913 if (isOpenMPWorksharingDirective(CurrDir) &&
5914 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005915 DVar = DSAStack->getImplicitDSA(VD, true);
5916 if (DVar.CKind != OMPC_shared &&
5917 (isOpenMPParallelDirective(DVar.DKind) ||
5918 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00005919 Diag(ELoc, diag::err_omp_required_access)
5920 << getOpenMPClauseName(OMPC_firstprivate)
5921 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005922 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005923 continue;
5924 }
5925 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005926 // OpenMP [2.9.3.4, Restrictions, p.3]
5927 // A list item that appears in a reduction clause of a parallel construct
5928 // must not appear in a firstprivate clause on a worksharing or task
5929 // construct if any of the worksharing or task regions arising from the
5930 // worksharing or task construct ever bind to any of the parallel regions
5931 // arising from the parallel construct.
5932 // OpenMP [2.9.3.4, Restrictions, p.4]
5933 // A list item that appears in a reduction clause in worksharing
5934 // construct must not appear in a firstprivate clause in a task construct
5935 // encountered during execution of any of the worksharing regions arising
5936 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005937 if (CurrDir == OMPD_task) {
5938 DVar =
5939 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
5940 [](OpenMPDirectiveKind K) -> bool {
5941 return isOpenMPParallelDirective(K) ||
5942 isOpenMPWorksharingDirective(K);
5943 },
5944 false);
5945 if (DVar.CKind == OMPC_reduction &&
5946 (isOpenMPParallelDirective(DVar.DKind) ||
5947 isOpenMPWorksharingDirective(DVar.DKind))) {
5948 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
5949 << getOpenMPDirectiveName(DVar.DKind);
5950 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5951 continue;
5952 }
5953 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005954 }
5955
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005956 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00005957 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005958 DSAStack->getCurrentDirective() == OMPD_task) {
5959 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5960 << getOpenMPClauseName(OMPC_firstprivate) << Type
5961 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5962 bool IsDecl =
5963 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5964 Diag(VD->getLocation(),
5965 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5966 << VD;
5967 continue;
5968 }
5969
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005970 Type = Type.getUnqualifiedType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00005971 auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName(),
5972 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005973 // Generate helper private variable and initialize it with the value of the
5974 // original variable. The address of the original variable is replaced by
5975 // the address of the new private variable in the CodeGen. This new variable
5976 // is not added to IdResolver, so the code in the OpenMP region uses
5977 // original variable for proper diagnostics and variable capturing.
5978 Expr *VDInitRefExpr = nullptr;
5979 // For arrays generate initializer for single element and replace it by the
5980 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005981 if (Type->isArrayType()) {
5982 auto VDInit =
5983 buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
5984 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005985 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005986 ElemType = ElemType.getUnqualifiedType();
5987 auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
5988 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00005989 InitializedEntity Entity =
5990 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005991 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
5992
5993 InitializationSequence InitSeq(*this, Entity, Kind, Init);
5994 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
5995 if (Result.isInvalid())
5996 VDPrivate->setInvalidDecl();
5997 else
5998 VDPrivate->setInit(Result.getAs<Expr>());
5999 } else {
Alexey Bataev69c62a92015-04-15 04:52:20 +00006000 auto *VDInit =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006001 buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006002 VDInitRefExpr =
6003 buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00006004 AddInitializerToDecl(VDPrivate,
6005 DefaultLvalueConversion(VDInitRefExpr).get(),
6006 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006007 }
6008 if (VDPrivate->isInvalidDecl()) {
6009 if (IsImplicitClause) {
6010 Diag(DE->getExprLoc(),
6011 diag::note_omp_task_predetermined_firstprivate_here);
6012 }
6013 continue;
6014 }
6015 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00006016 auto VDPrivateRefExpr = buildDeclRefExpr(
6017 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006018 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
6019 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006020 PrivateCopies.push_back(VDPrivateRefExpr);
6021 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006022 }
6023
Alexey Bataeved09d242014-05-28 05:53:51 +00006024 if (Vars.empty())
6025 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006026
6027 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006028 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006029}
6030
Alexander Musman1bb328c2014-06-04 13:06:39 +00006031OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
6032 SourceLocation StartLoc,
6033 SourceLocation LParenLoc,
6034 SourceLocation EndLoc) {
6035 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00006036 SmallVector<Expr *, 8> SrcExprs;
6037 SmallVector<Expr *, 8> DstExprs;
6038 SmallVector<Expr *, 8> AssignmentOps;
Alexander Musman1bb328c2014-06-04 13:06:39 +00006039 for (auto &RefExpr : VarList) {
6040 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
6041 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6042 // It will be analyzed later.
6043 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00006044 SrcExprs.push_back(nullptr);
6045 DstExprs.push_back(nullptr);
6046 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006047 continue;
6048 }
6049
6050 SourceLocation ELoc = RefExpr->getExprLoc();
6051 // OpenMP [2.1, C/C++]
6052 // A list item is a variable name.
6053 // OpenMP [2.14.3.5, Restrictions, p.1]
6054 // A variable that is part of another variable (as an array or structure
6055 // element) cannot appear in a lastprivate clause.
6056 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
6057 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6058 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6059 continue;
6060 }
6061 Decl *D = DE->getDecl();
6062 VarDecl *VD = cast<VarDecl>(D);
6063
6064 QualType Type = VD->getType();
6065 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6066 // It will be analyzed later.
6067 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00006068 SrcExprs.push_back(nullptr);
6069 DstExprs.push_back(nullptr);
6070 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006071 continue;
6072 }
6073
6074 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
6075 // A variable that appears in a lastprivate clause must not have an
6076 // incomplete type or a reference type.
6077 if (RequireCompleteType(ELoc, Type,
6078 diag::err_omp_lastprivate_incomplete_type)) {
6079 continue;
6080 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006081 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00006082
6083 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
6084 // in a Construct]
6085 // Variables with the predetermined data-sharing attributes may not be
6086 // listed in data-sharing attributes clauses, except for the cases
6087 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006088 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006089 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
6090 DVar.CKind != OMPC_firstprivate &&
6091 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
6092 Diag(ELoc, diag::err_omp_wrong_dsa)
6093 << getOpenMPClauseName(DVar.CKind)
6094 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006095 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006096 continue;
6097 }
6098
Alexey Bataevf29276e2014-06-18 04:14:57 +00006099 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
6100 // OpenMP [2.14.3.5, Restrictions, p.2]
6101 // A list item that is private within a parallel region, or that appears in
6102 // the reduction clause of a parallel construct, must not appear in a
6103 // lastprivate clause on a worksharing construct if any of the corresponding
6104 // worksharing regions ever binds to any of the corresponding parallel
6105 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00006106 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00006107 if (isOpenMPWorksharingDirective(CurrDir) &&
6108 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006109 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006110 if (DVar.CKind != OMPC_shared) {
6111 Diag(ELoc, diag::err_omp_required_access)
6112 << getOpenMPClauseName(OMPC_lastprivate)
6113 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006114 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006115 continue;
6116 }
6117 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00006118 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00006119 // A variable of class type (or array thereof) that appears in a
6120 // lastprivate clause requires an accessible, unambiguous default
6121 // constructor for the class type, unless the list item is also specified
6122 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00006123 // A variable of class type (or array thereof) that appears in a
6124 // lastprivate clause requires an accessible, unambiguous copy assignment
6125 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00006126 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00006127 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00006128 Type.getUnqualifiedType(), ".lastprivate.src",
6129 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00006130 auto *PseudoSrcExpr = buildDeclRefExpr(
6131 *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00006132 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00006133 buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst",
6134 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00006135 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006136 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00006137 // For arrays generate assignment operation for single element and replace
6138 // it by the original array element in CodeGen.
6139 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6140 PseudoDstExpr, PseudoSrcExpr);
6141 if (AssignmentOp.isInvalid())
6142 continue;
6143 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6144 /*DiscardedValue=*/true);
6145 if (AssignmentOp.isInvalid())
6146 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00006147
Alexey Bataev39f915b82015-05-08 10:41:21 +00006148 if (TopDVar.CKind != OMPC_firstprivate)
Alexey Bataevf29276e2014-06-18 04:14:57 +00006149 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006150 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00006151 SrcExprs.push_back(PseudoSrcExpr);
6152 DstExprs.push_back(PseudoDstExpr);
6153 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00006154 }
6155
6156 if (Vars.empty())
6157 return nullptr;
6158
6159 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00006160 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006161}
6162
Alexey Bataev758e55e2013-09-06 18:03:48 +00006163OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
6164 SourceLocation StartLoc,
6165 SourceLocation LParenLoc,
6166 SourceLocation EndLoc) {
6167 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00006168 for (auto &RefExpr : VarList) {
6169 assert(RefExpr && "NULL expr in OpenMP shared clause.");
6170 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00006171 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006172 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006173 continue;
6174 }
6175
Alexey Bataeved09d242014-05-28 05:53:51 +00006176 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00006177 // OpenMP [2.1, C/C++]
6178 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00006179 // OpenMP [2.14.3.2, Restrictions, p.1]
6180 // A variable that is part of another variable (as an array or structure
6181 // element) cannot appear in a shared unless it is a static data member
6182 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00006183 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006184 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00006185 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00006186 continue;
6187 }
6188 Decl *D = DE->getDecl();
6189 VarDecl *VD = cast<VarDecl>(D);
6190
6191 QualType Type = VD->getType();
6192 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6193 // It will be analyzed later.
6194 Vars.push_back(DE);
6195 continue;
6196 }
6197
6198 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
6199 // in a Construct]
6200 // Variables with the predetermined data-sharing attributes may not be
6201 // listed in data-sharing attributes clauses, except for the cases
6202 // listed below. For these exceptions only, listing a predetermined
6203 // variable in a data-sharing attribute clause is allowed and overrides
6204 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006205 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00006206 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
6207 DVar.RefExpr) {
6208 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
6209 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006210 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006211 continue;
6212 }
6213
6214 DSAStack->addDSA(VD, DE, OMPC_shared);
6215 Vars.push_back(DE);
6216 }
6217
Alexey Bataeved09d242014-05-28 05:53:51 +00006218 if (Vars.empty())
6219 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00006220
6221 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
6222}
6223
Alexey Bataevc5e02582014-06-16 07:08:35 +00006224namespace {
6225class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
6226 DSAStackTy *Stack;
6227
6228public:
6229 bool VisitDeclRefExpr(DeclRefExpr *E) {
6230 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006231 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006232 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
6233 return false;
6234 if (DVar.CKind != OMPC_unknown)
6235 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00006236 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006237 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006238 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00006239 return true;
6240 return false;
6241 }
6242 return false;
6243 }
6244 bool VisitStmt(Stmt *S) {
6245 for (auto Child : S->children()) {
6246 if (Child && Visit(Child))
6247 return true;
6248 }
6249 return false;
6250 }
Alexey Bataev23b69422014-06-18 07:08:49 +00006251 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00006252};
Alexey Bataev23b69422014-06-18 07:08:49 +00006253} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00006254
6255OMPClause *Sema::ActOnOpenMPReductionClause(
6256 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
6257 SourceLocation ColonLoc, SourceLocation EndLoc,
6258 CXXScopeSpec &ReductionIdScopeSpec,
6259 const DeclarationNameInfo &ReductionId) {
6260 // TODO: Allow scope specification search when 'declare reduction' is
6261 // supported.
6262 assert(ReductionIdScopeSpec.isEmpty() &&
6263 "No support for scoped reduction identifiers yet.");
6264
6265 auto DN = ReductionId.getName();
6266 auto OOK = DN.getCXXOverloadedOperator();
6267 BinaryOperatorKind BOK = BO_Comma;
6268
6269 // OpenMP [2.14.3.6, reduction clause]
6270 // C
6271 // reduction-identifier is either an identifier or one of the following
6272 // operators: +, -, *, &, |, ^, && and ||
6273 // C++
6274 // reduction-identifier is either an id-expression or one of the following
6275 // operators: +, -, *, &, |, ^, && and ||
6276 // FIXME: Only 'min' and 'max' identifiers are supported for now.
6277 switch (OOK) {
6278 case OO_Plus:
6279 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006280 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006281 break;
6282 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006283 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006284 break;
6285 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006286 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006287 break;
6288 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006289 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006290 break;
6291 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006292 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006293 break;
6294 case OO_AmpAmp:
6295 BOK = BO_LAnd;
6296 break;
6297 case OO_PipePipe:
6298 BOK = BO_LOr;
6299 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006300 case OO_New:
6301 case OO_Delete:
6302 case OO_Array_New:
6303 case OO_Array_Delete:
6304 case OO_Slash:
6305 case OO_Percent:
6306 case OO_Tilde:
6307 case OO_Exclaim:
6308 case OO_Equal:
6309 case OO_Less:
6310 case OO_Greater:
6311 case OO_LessEqual:
6312 case OO_GreaterEqual:
6313 case OO_PlusEqual:
6314 case OO_MinusEqual:
6315 case OO_StarEqual:
6316 case OO_SlashEqual:
6317 case OO_PercentEqual:
6318 case OO_CaretEqual:
6319 case OO_AmpEqual:
6320 case OO_PipeEqual:
6321 case OO_LessLess:
6322 case OO_GreaterGreater:
6323 case OO_LessLessEqual:
6324 case OO_GreaterGreaterEqual:
6325 case OO_EqualEqual:
6326 case OO_ExclaimEqual:
6327 case OO_PlusPlus:
6328 case OO_MinusMinus:
6329 case OO_Comma:
6330 case OO_ArrowStar:
6331 case OO_Arrow:
6332 case OO_Call:
6333 case OO_Subscript:
6334 case OO_Conditional:
6335 case NUM_OVERLOADED_OPERATORS:
6336 llvm_unreachable("Unexpected reduction identifier");
6337 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006338 if (auto II = DN.getAsIdentifierInfo()) {
6339 if (II->isStr("max"))
6340 BOK = BO_GT;
6341 else if (II->isStr("min"))
6342 BOK = BO_LT;
6343 }
6344 break;
6345 }
6346 SourceRange ReductionIdRange;
6347 if (ReductionIdScopeSpec.isValid()) {
6348 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
6349 }
6350 ReductionIdRange.setEnd(ReductionId.getEndLoc());
6351 if (BOK == BO_Comma) {
6352 // Not allowed reduction identifier is found.
6353 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
6354 << ReductionIdRange;
6355 return nullptr;
6356 }
6357
6358 SmallVector<Expr *, 8> Vars;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006359 SmallVector<Expr *, 8> LHSs;
6360 SmallVector<Expr *, 8> RHSs;
6361 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006362 for (auto RefExpr : VarList) {
6363 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
6364 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6365 // It will be analyzed later.
6366 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006367 LHSs.push_back(nullptr);
6368 RHSs.push_back(nullptr);
6369 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006370 continue;
6371 }
6372
6373 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
6374 RefExpr->isInstantiationDependent() ||
6375 RefExpr->containsUnexpandedParameterPack()) {
6376 // It will be analyzed later.
6377 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006378 LHSs.push_back(nullptr);
6379 RHSs.push_back(nullptr);
6380 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006381 continue;
6382 }
6383
6384 auto ELoc = RefExpr->getExprLoc();
6385 auto ERange = RefExpr->getSourceRange();
6386 // OpenMP [2.1, C/C++]
6387 // A list item is a variable or array section, subject to the restrictions
6388 // specified in Section 2.4 on page 42 and in each of the sections
6389 // describing clauses and directives for which a list appears.
6390 // OpenMP [2.14.3.3, Restrictions, p.1]
6391 // A variable that is part of another variable (as an array or
6392 // structure element) cannot appear in a private clause.
Alexey Bataeva1764212015-09-30 09:22:36 +00006393 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
6394 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr);
6395 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr);
6396 if (!ASE && !OASE && (!DE || !isa<VarDecl>(DE->getDecl()))) {
6397 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item) << ERange;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006398 continue;
6399 }
Alexey Bataeva1764212015-09-30 09:22:36 +00006400 QualType Type;
6401 VarDecl *VD = nullptr;
6402 if (DE) {
6403 auto D = DE->getDecl();
6404 VD = cast<VarDecl>(D);
6405 Type = VD->getType();
6406 } else if (ASE)
6407 Type = ASE->getType();
6408 else if (OASE) {
6409 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
6410 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
6411 Type = ATy->getElementType();
6412 else
6413 Type = BaseType->getPointeeType();
6414 }
6415 // OpenMP [2.15.3.6, reduction Clause]
6416 // If a list item is an array section, its lower-bound must be zero.
6417 llvm::APSInt Result;
6418 if (OASE && OASE->getLowerBound() &&
6419 OASE->getLowerBound()->EvaluateAsInt(Result, Context) && Result != 0) {
6420 Diag(OASE->getLowerBound()->getExprLoc(),
6421 diag::err_omp_expected_array_sect_reduction_lb_not_zero)
6422 << OASE->getLowerBound()->getSourceRange();
6423 continue;
6424 }
6425
Alexey Bataevc5e02582014-06-16 07:08:35 +00006426 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
6427 // A variable that appears in a private clause must not have an incomplete
6428 // type or a reference type.
6429 if (RequireCompleteType(ELoc, Type,
6430 diag::err_omp_reduction_incomplete_type))
6431 continue;
6432 // OpenMP [2.14.3.6, reduction clause, Restrictions]
6433 // Arrays may not appear in a reduction clause.
6434 if (Type.getNonReferenceType()->isArrayType()) {
6435 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
Alexey Bataeva1764212015-09-30 09:22:36 +00006436 if (VD) {
6437 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6438 VarDecl::DeclarationOnly;
6439 Diag(VD->getLocation(),
6440 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6441 << VD;
6442 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006443 continue;
6444 }
6445 // OpenMP [2.14.3.6, reduction clause, Restrictions]
6446 // A list item that appears in a reduction clause must not be
6447 // const-qualified.
6448 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006449 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00006450 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataeva1764212015-09-30 09:22:36 +00006451 if (VD) {
6452 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6453 VarDecl::DeclarationOnly;
6454 Diag(VD->getLocation(),
6455 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6456 << VD;
6457 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006458 continue;
6459 }
6460 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
6461 // If a list-item is a reference type then it must bind to the same object
6462 // for all threads of the team.
Alexey Bataeva1764212015-09-30 09:22:36 +00006463 if (VD) {
6464 VarDecl *VDDef = VD->getDefinition();
6465 if (Type->isReferenceType() && VDDef) {
6466 DSARefChecker Check(DSAStack);
6467 if (Check.Visit(VDDef->getInit())) {
6468 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
6469 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
6470 continue;
6471 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006472 }
6473 }
6474 // OpenMP [2.14.3.6, reduction clause, Restrictions]
6475 // The type of a list item that appears in a reduction clause must be valid
6476 // for the reduction-identifier. For a max or min reduction in C, the type
6477 // of the list item must be an allowed arithmetic data type: char, int,
6478 // float, double, or _Bool, possibly modified with long, short, signed, or
6479 // unsigned. For a max or min reduction in C++, the type of the list item
6480 // must be an allowed arithmetic data type: char, wchar_t, int, float,
6481 // double, or bool, possibly modified with long, short, signed, or unsigned.
6482 if ((BOK == BO_GT || BOK == BO_LT) &&
6483 !(Type->isScalarType() ||
6484 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
6485 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
6486 << getLangOpts().CPlusPlus;
Alexey Bataeva1764212015-09-30 09:22:36 +00006487 if (VD) {
6488 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6489 VarDecl::DeclarationOnly;
6490 Diag(VD->getLocation(),
6491 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6492 << VD;
6493 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006494 continue;
6495 }
6496 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
6497 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
6498 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
Alexey Bataeva1764212015-09-30 09:22:36 +00006499 if (VD) {
6500 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6501 VarDecl::DeclarationOnly;
6502 Diag(VD->getLocation(),
6503 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6504 << VD;
6505 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006506 continue;
6507 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006508 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
6509 // in a Construct]
6510 // Variables with the predetermined data-sharing attributes may not be
6511 // listed in data-sharing attributes clauses, except for the cases
6512 // listed below. For these exceptions only, listing a predetermined
6513 // variable in a data-sharing attribute clause is allowed and overrides
6514 // the variable's predetermined data-sharing attributes.
6515 // OpenMP [2.14.3.6, Restrictions, p.3]
6516 // Any number of reduction clauses can be specified on the directive,
6517 // but a list item can appear only once in the reduction clauses for that
6518 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00006519 DSAStackTy::DSAVarData DVar;
6520 if (VD) {
6521 DVar = DSAStack->getTopDSA(VD, false);
6522 if (DVar.CKind == OMPC_reduction) {
6523 Diag(ELoc, diag::err_omp_once_referenced)
6524 << getOpenMPClauseName(OMPC_reduction);
6525 if (DVar.RefExpr) {
6526 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
6527 }
6528 } else if (DVar.CKind != OMPC_unknown) {
6529 Diag(ELoc, diag::err_omp_wrong_dsa)
6530 << getOpenMPClauseName(DVar.CKind)
6531 << getOpenMPClauseName(OMPC_reduction);
6532 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6533 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006534 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006535 }
6536
6537 // OpenMP [2.14.3.6, Restrictions, p.1]
6538 // A list item that appears in a reduction clause of a worksharing
6539 // construct must be shared in the parallel regions to which any of the
6540 // worksharing regions arising from the worksharing construct bind.
Alexey Bataeva1764212015-09-30 09:22:36 +00006541 if (VD) {
6542 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
6543 if (isOpenMPWorksharingDirective(CurrDir) &&
6544 !isOpenMPParallelDirective(CurrDir)) {
6545 DVar = DSAStack->getImplicitDSA(VD, true);
6546 if (DVar.CKind != OMPC_shared) {
6547 Diag(ELoc, diag::err_omp_required_access)
6548 << getOpenMPClauseName(OMPC_reduction)
6549 << getOpenMPClauseName(OMPC_shared);
6550 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6551 continue;
6552 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00006553 }
6554 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006555 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeva1764212015-09-30 09:22:36 +00006556 auto *LHSVD =
6557 buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
6558 VD && VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6559 auto *RHSVD =
6560 buildVarDecl(*this, ELoc, Type, VD ? VD->getName() : ".item.",
6561 VD && VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006562 // Add initializer for private variable.
6563 Expr *Init = nullptr;
6564 switch (BOK) {
6565 case BO_Add:
6566 case BO_Xor:
6567 case BO_Or:
6568 case BO_LOr:
6569 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
6570 if (Type->isScalarType() || Type->isAnyComplexType()) {
6571 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00006572 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006573 break;
6574 case BO_Mul:
6575 case BO_LAnd:
6576 if (Type->isScalarType() || Type->isAnyComplexType()) {
6577 // '*' and '&&' reduction ops - initializer is '1'.
6578 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
6579 }
6580 break;
6581 case BO_And: {
6582 // '&' reduction op - initializer is '~0'.
6583 QualType OrigType = Type;
6584 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
6585 Type = ComplexTy->getElementType();
6586 }
6587 if (Type->isRealFloatingType()) {
6588 llvm::APFloat InitValue =
6589 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
6590 /*isIEEE=*/true);
6591 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
6592 Type, ELoc);
6593 } else if (Type->isScalarType()) {
6594 auto Size = Context.getTypeSize(Type);
6595 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
6596 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
6597 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
6598 }
6599 if (Init && OrigType->isAnyComplexType()) {
6600 // Init = 0xFFFF + 0xFFFFi;
6601 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
6602 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
6603 }
6604 Type = OrigType;
6605 break;
6606 }
6607 case BO_LT:
6608 case BO_GT: {
6609 // 'min' reduction op - initializer is 'Largest representable number in
6610 // the reduction list item type'.
6611 // 'max' reduction op - initializer is 'Least representable number in
6612 // the reduction list item type'.
6613 if (Type->isIntegerType() || Type->isPointerType()) {
6614 bool IsSigned = Type->hasSignedIntegerRepresentation();
6615 auto Size = Context.getTypeSize(Type);
6616 QualType IntTy =
6617 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
6618 llvm::APInt InitValue =
6619 (BOK != BO_LT)
6620 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
6621 : llvm::APInt::getMinValue(Size)
6622 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
6623 : llvm::APInt::getMaxValue(Size);
6624 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
6625 if (Type->isPointerType()) {
6626 // Cast to pointer type.
6627 auto CastExpr = BuildCStyleCastExpr(
6628 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
6629 SourceLocation(), Init);
6630 if (CastExpr.isInvalid())
6631 continue;
6632 Init = CastExpr.get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00006633 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006634 } else if (Type->isRealFloatingType()) {
6635 llvm::APFloat InitValue = llvm::APFloat::getLargest(
6636 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
6637 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
6638 Type, ELoc);
6639 }
6640 break;
6641 }
6642 case BO_PtrMemD:
6643 case BO_PtrMemI:
6644 case BO_MulAssign:
6645 case BO_Div:
6646 case BO_Rem:
6647 case BO_Sub:
6648 case BO_Shl:
6649 case BO_Shr:
6650 case BO_LE:
6651 case BO_GE:
6652 case BO_EQ:
6653 case BO_NE:
6654 case BO_AndAssign:
6655 case BO_XorAssign:
6656 case BO_OrAssign:
6657 case BO_Assign:
6658 case BO_AddAssign:
6659 case BO_SubAssign:
6660 case BO_DivAssign:
6661 case BO_RemAssign:
6662 case BO_ShlAssign:
6663 case BO_ShrAssign:
6664 case BO_Comma:
6665 llvm_unreachable("Unexpected reduction operation");
6666 }
6667 if (Init) {
6668 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
6669 /*TypeMayContainAuto=*/false);
6670 } else {
6671 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
6672 }
6673 if (!RHSVD->hasInit()) {
6674 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
6675 << ReductionIdRange;
Alexey Bataeva1764212015-09-30 09:22:36 +00006676 if (VD) {
6677 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6678 VarDecl::DeclarationOnly;
6679 Diag(VD->getLocation(),
6680 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6681 << VD;
6682 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006683 continue;
6684 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00006685 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
6686 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006687 ExprResult ReductionOp =
6688 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
6689 LHSDRE, RHSDRE);
6690 if (ReductionOp.isUsable()) {
Alexey Bataev69a47792015-05-07 03:54:03 +00006691 if (BOK != BO_LT && BOK != BO_GT) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006692 ReductionOp =
6693 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
6694 BO_Assign, LHSDRE, ReductionOp.get());
6695 } else {
6696 auto *ConditionalOp = new (Context) ConditionalOperator(
6697 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
6698 RHSDRE, Type, VK_LValue, OK_Ordinary);
6699 ReductionOp =
6700 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
6701 BO_Assign, LHSDRE, ConditionalOp);
6702 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006703 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00006704 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006705 if (ReductionOp.isInvalid())
6706 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006707
Alexey Bataeva1764212015-09-30 09:22:36 +00006708 if (VD)
6709 DSAStack->addDSA(VD, DE, OMPC_reduction);
6710 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006711 LHSs.push_back(LHSDRE);
6712 RHSs.push_back(RHSDRE);
6713 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00006714 }
6715
6716 if (Vars.empty())
6717 return nullptr;
6718
6719 return OMPReductionClause::Create(
6720 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006721 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
6722 RHSs, ReductionOps);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006723}
6724
Alexey Bataev182227b2015-08-20 10:54:39 +00006725OMPClause *Sema::ActOnOpenMPLinearClause(
6726 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
6727 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
6728 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00006729 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006730 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00006731 SmallVector<Expr *, 8> Inits;
Alexey Bataev182227b2015-08-20 10:54:39 +00006732 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
6733 LinKind == OMPC_LINEAR_unknown) {
6734 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
6735 LinKind = OMPC_LINEAR_val;
6736 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006737 for (auto &RefExpr : VarList) {
6738 assert(RefExpr && "NULL expr in OpenMP linear clause.");
6739 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00006740 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006741 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006742 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00006743 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00006744 continue;
6745 }
6746
6747 // OpenMP [2.14.3.7, linear clause]
6748 // A list item that appears in a linear clause is subject to the private
6749 // clause semantics described in Section 2.14.3.3 on page 159 except as
6750 // noted. In addition, the value of the new list item on each iteration
6751 // of the associated loop(s) corresponds to the value of the original
6752 // list item before entering the construct plus the logical number of
6753 // the iteration times linear-step.
6754
Alexey Bataeved09d242014-05-28 05:53:51 +00006755 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00006756 // OpenMP [2.1, C/C++]
6757 // A list item is a variable name.
6758 // OpenMP [2.14.3.3, Restrictions, p.1]
6759 // A variable that is part of another variable (as an array or
6760 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00006761 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00006762 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00006763 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00006764 continue;
6765 }
6766
6767 VarDecl *VD = cast<VarDecl>(DE->getDecl());
6768
6769 // OpenMP [2.14.3.7, linear clause]
6770 // A list-item cannot appear in more than one linear clause.
6771 // A list-item that appears in a linear clause cannot appear in any
6772 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006773 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00006774 if (DVar.RefExpr) {
6775 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
6776 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006777 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00006778 continue;
6779 }
6780
6781 QualType QType = VD->getType();
6782 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
6783 // It will be analyzed later.
6784 Vars.push_back(DE);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006785 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00006786 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00006787 continue;
6788 }
6789
6790 // A variable must not have an incomplete type or a reference type.
6791 if (RequireCompleteType(ELoc, QType,
6792 diag::err_omp_linear_incomplete_type)) {
6793 continue;
6794 }
Alexey Bataev1185e192015-08-20 12:15:57 +00006795 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
6796 !QType->isReferenceType()) {
6797 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
6798 << QType << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
6799 continue;
6800 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006801 QType = QType.getNonReferenceType();
Alexander Musman8dba6642014-04-22 13:09:42 +00006802
6803 // A list item must not be const-qualified.
6804 if (QType.isConstant(Context)) {
6805 Diag(ELoc, diag::err_omp_const_variable)
6806 << getOpenMPClauseName(OMPC_linear);
6807 bool IsDecl =
6808 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6809 Diag(VD->getLocation(),
6810 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6811 << VD;
6812 continue;
6813 }
6814
6815 // A list item must be of integral or pointer type.
6816 QType = QType.getUnqualifiedType().getCanonicalType();
6817 const Type *Ty = QType.getTypePtrOrNull();
6818 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
6819 !Ty->isPointerType())) {
6820 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
6821 bool IsDecl =
6822 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6823 Diag(VD->getLocation(),
6824 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6825 << VD;
6826 continue;
6827 }
6828
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006829 // Build private copy of original var.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00006830 auto *Private = buildVarDecl(*this, ELoc, QType, VD->getName(),
6831 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006832 auto *PrivateRef = buildDeclRefExpr(
6833 *this, Private, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexander Musman3276a272015-03-21 10:12:56 +00006834 // Build var to save initial value.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006835 VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00006836 Expr *InitExpr;
6837 if (LinKind == OMPC_LINEAR_uval)
6838 InitExpr = VD->getInit();
6839 else
6840 InitExpr = DE;
6841 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Alexander Musman3276a272015-03-21 10:12:56 +00006842 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006843 auto InitRef = buildDeclRefExpr(
6844 *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexander Musman8dba6642014-04-22 13:09:42 +00006845 DSAStack->addDSA(VD, DE, OMPC_linear);
6846 Vars.push_back(DE);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006847 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00006848 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00006849 }
6850
6851 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006852 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00006853
6854 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00006855 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00006856 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
6857 !Step->isInstantiationDependent() &&
6858 !Step->containsUnexpandedParameterPack()) {
6859 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006860 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00006861 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006862 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006863 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00006864
Alexander Musman3276a272015-03-21 10:12:56 +00006865 // Build var to save the step value.
6866 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006867 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00006868 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006869 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00006870 ExprResult CalcStep =
6871 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006872 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00006873
Alexander Musman8dba6642014-04-22 13:09:42 +00006874 // Warn about zero linear step (it would be probably better specified as
6875 // making corresponding variables 'const').
6876 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00006877 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
6878 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00006879 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
6880 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00006881 if (!IsConstant && CalcStep.isUsable()) {
6882 // Calculate the step beforehand instead of doing this on each iteration.
6883 // (This is not used if the number of iterations may be kfold-ed).
6884 CalcStepExpr = CalcStep.get();
6885 }
Alexander Musman8dba6642014-04-22 13:09:42 +00006886 }
6887
Alexey Bataev182227b2015-08-20 10:54:39 +00006888 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
6889 ColonLoc, EndLoc, Vars, Privates, Inits,
6890 StepExpr, CalcStepExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00006891}
6892
6893static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
6894 Expr *NumIterations, Sema &SemaRef,
6895 Scope *S) {
6896 // Walk the vars and build update/final expressions for the CodeGen.
6897 SmallVector<Expr *, 8> Updates;
6898 SmallVector<Expr *, 8> Finals;
6899 Expr *Step = Clause.getStep();
6900 Expr *CalcStep = Clause.getCalcStep();
6901 // OpenMP [2.14.3.7, linear clause]
6902 // If linear-step is not specified it is assumed to be 1.
6903 if (Step == nullptr)
6904 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
6905 else if (CalcStep)
6906 Step = cast<BinaryOperator>(CalcStep)->getLHS();
6907 bool HasErrors = false;
6908 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006909 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00006910 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00006911 for (auto &RefExpr : Clause.varlists()) {
6912 Expr *InitExpr = *CurInit;
6913
6914 // Build privatized reference to the current linear var.
6915 auto DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00006916 Expr *CapturedRef;
6917 if (LinKind == OMPC_LINEAR_uval)
6918 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
6919 else
6920 CapturedRef =
6921 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
6922 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
6923 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00006924
6925 // Build update: Var = InitExpr + IV * Step
6926 ExprResult Update =
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006927 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexander Musman3276a272015-03-21 10:12:56 +00006928 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006929 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
6930 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00006931
6932 // Build final: Var = InitExpr + NumIterations * Step
6933 ExprResult Final =
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006934 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataev39f915b82015-05-08 10:41:21 +00006935 InitExpr, NumIterations, Step, /* Subtract */ false);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006936 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
6937 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00006938 if (!Update.isUsable() || !Final.isUsable()) {
6939 Updates.push_back(nullptr);
6940 Finals.push_back(nullptr);
6941 HasErrors = true;
6942 } else {
6943 Updates.push_back(Update.get());
6944 Finals.push_back(Final.get());
6945 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006946 ++CurInit, ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00006947 }
6948 Clause.setUpdates(Updates);
6949 Clause.setFinals(Finals);
6950 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00006951}
6952
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006953OMPClause *Sema::ActOnOpenMPAlignedClause(
6954 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
6955 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
6956
6957 SmallVector<Expr *, 8> Vars;
6958 for (auto &RefExpr : VarList) {
6959 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
6960 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6961 // It will be analyzed later.
6962 Vars.push_back(RefExpr);
6963 continue;
6964 }
6965
6966 SourceLocation ELoc = RefExpr->getExprLoc();
6967 // OpenMP [2.1, C/C++]
6968 // A list item is a variable name.
6969 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6970 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6971 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6972 continue;
6973 }
6974
6975 VarDecl *VD = cast<VarDecl>(DE->getDecl());
6976
6977 // OpenMP [2.8.1, simd construct, Restrictions]
6978 // The type of list items appearing in the aligned clause must be
6979 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006980 QualType QType = VD->getType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006981 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006982 const Type *Ty = QType.getTypePtrOrNull();
6983 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
6984 !Ty->isPointerType())) {
6985 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
6986 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
6987 bool IsDecl =
6988 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6989 Diag(VD->getLocation(),
6990 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6991 << VD;
6992 continue;
6993 }
6994
6995 // OpenMP [2.8.1, simd construct, Restrictions]
6996 // A list-item cannot appear in more than one aligned clause.
6997 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
6998 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
6999 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
7000 << getOpenMPClauseName(OMPC_aligned);
7001 continue;
7002 }
7003
7004 Vars.push_back(DE);
7005 }
7006
7007 // OpenMP [2.8.1, simd construct, Description]
7008 // The parameter of the aligned clause, alignment, must be a constant
7009 // positive integer expression.
7010 // If no optional parameter is specified, implementation-defined default
7011 // alignments for SIMD instructions on the target platforms are assumed.
7012 if (Alignment != nullptr) {
7013 ExprResult AlignResult =
7014 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
7015 if (AlignResult.isInvalid())
7016 return nullptr;
7017 Alignment = AlignResult.get();
7018 }
7019 if (Vars.empty())
7020 return nullptr;
7021
7022 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
7023 EndLoc, Vars, Alignment);
7024}
7025
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007026OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
7027 SourceLocation StartLoc,
7028 SourceLocation LParenLoc,
7029 SourceLocation EndLoc) {
7030 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007031 SmallVector<Expr *, 8> SrcExprs;
7032 SmallVector<Expr *, 8> DstExprs;
7033 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00007034 for (auto &RefExpr : VarList) {
7035 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
7036 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007037 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007038 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007039 SrcExprs.push_back(nullptr);
7040 DstExprs.push_back(nullptr);
7041 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007042 continue;
7043 }
7044
Alexey Bataeved09d242014-05-28 05:53:51 +00007045 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007046 // OpenMP [2.1, C/C++]
7047 // A list item is a variable name.
7048 // OpenMP [2.14.4.1, Restrictions, p.1]
7049 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00007050 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007051 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007052 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007053 continue;
7054 }
7055
7056 Decl *D = DE->getDecl();
7057 VarDecl *VD = cast<VarDecl>(D);
7058
7059 QualType Type = VD->getType();
7060 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
7061 // It will be analyzed later.
7062 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007063 SrcExprs.push_back(nullptr);
7064 DstExprs.push_back(nullptr);
7065 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007066 continue;
7067 }
7068
7069 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
7070 // A list item that appears in a copyin clause must be threadprivate.
7071 if (!DSAStack->isThreadPrivate(VD)) {
7072 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00007073 << getOpenMPClauseName(OMPC_copyin)
7074 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007075 continue;
7076 }
7077
7078 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
7079 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00007080 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007081 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007082 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007083 auto *SrcVD =
7084 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
7085 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007086 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007087 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
7088 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007089 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
7090 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007091 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007092 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007093 // For arrays generate assignment operation for single element and replace
7094 // it by the original array element in CodeGen.
7095 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
7096 PseudoDstExpr, PseudoSrcExpr);
7097 if (AssignmentOp.isInvalid())
7098 continue;
7099 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
7100 /*DiscardedValue=*/true);
7101 if (AssignmentOp.isInvalid())
7102 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007103
7104 DSAStack->addDSA(VD, DE, OMPC_copyin);
7105 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007106 SrcExprs.push_back(PseudoSrcExpr);
7107 DstExprs.push_back(PseudoDstExpr);
7108 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007109 }
7110
Alexey Bataeved09d242014-05-28 05:53:51 +00007111 if (Vars.empty())
7112 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007113
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007114 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7115 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007116}
7117
Alexey Bataevbae9a792014-06-27 10:37:06 +00007118OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
7119 SourceLocation StartLoc,
7120 SourceLocation LParenLoc,
7121 SourceLocation EndLoc) {
7122 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00007123 SmallVector<Expr *, 8> SrcExprs;
7124 SmallVector<Expr *, 8> DstExprs;
7125 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007126 for (auto &RefExpr : VarList) {
7127 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
7128 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7129 // It will be analyzed later.
7130 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007131 SrcExprs.push_back(nullptr);
7132 DstExprs.push_back(nullptr);
7133 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007134 continue;
7135 }
7136
7137 SourceLocation ELoc = RefExpr->getExprLoc();
7138 // OpenMP [2.1, C/C++]
7139 // A list item is a variable name.
7140 // OpenMP [2.14.4.1, Restrictions, p.1]
7141 // A list item that appears in a copyin clause must be threadprivate.
7142 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7143 if (!DE || !isa<VarDecl>(DE->getDecl())) {
7144 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7145 continue;
7146 }
7147
7148 Decl *D = DE->getDecl();
7149 VarDecl *VD = cast<VarDecl>(D);
7150
7151 QualType Type = VD->getType();
7152 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
7153 // It will be analyzed later.
7154 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007155 SrcExprs.push_back(nullptr);
7156 DstExprs.push_back(nullptr);
7157 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007158 continue;
7159 }
7160
7161 // OpenMP [2.14.4.2, Restrictions, p.2]
7162 // A list item that appears in a copyprivate clause may not appear in a
7163 // private or firstprivate clause on the single construct.
7164 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007165 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007166 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
7167 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00007168 Diag(ELoc, diag::err_omp_wrong_dsa)
7169 << getOpenMPClauseName(DVar.CKind)
7170 << getOpenMPClauseName(OMPC_copyprivate);
7171 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7172 continue;
7173 }
7174
7175 // OpenMP [2.11.4.2, Restrictions, p.1]
7176 // All list items that appear in a copyprivate clause must be either
7177 // threadprivate or private in the enclosing context.
7178 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007179 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007180 if (DVar.CKind == OMPC_shared) {
7181 Diag(ELoc, diag::err_omp_required_access)
7182 << getOpenMPClauseName(OMPC_copyprivate)
7183 << "threadprivate or private in the enclosing context";
7184 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7185 continue;
7186 }
7187 }
7188 }
7189
Alexey Bataev7a3e5852015-05-19 08:19:24 +00007190 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007191 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00007192 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007193 << getOpenMPClauseName(OMPC_copyprivate) << Type
7194 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00007195 bool IsDecl =
7196 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7197 Diag(VD->getLocation(),
7198 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7199 << VD;
7200 continue;
7201 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007202
Alexey Bataevbae9a792014-06-27 10:37:06 +00007203 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
7204 // A variable of class type (or array thereof) that appears in a
7205 // copyin clause requires an accessible, unambiguous copy assignment
7206 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007207 Type = Context.getBaseElementType(Type.getNonReferenceType())
7208 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00007209 auto *SrcVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007210 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src",
7211 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev420d45b2015-04-14 05:11:24 +00007212 auto *PseudoSrcExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00007213 buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
Alexey Bataev420d45b2015-04-14 05:11:24 +00007214 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007215 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst",
7216 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev420d45b2015-04-14 05:11:24 +00007217 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00007218 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataeva63048e2015-03-23 06:18:07 +00007219 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
7220 PseudoDstExpr, PseudoSrcExpr);
7221 if (AssignmentOp.isInvalid())
7222 continue;
7223 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
7224 /*DiscardedValue=*/true);
7225 if (AssignmentOp.isInvalid())
7226 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007227
7228 // No need to mark vars as copyprivate, they are already threadprivate or
7229 // implicitly private.
7230 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007231 SrcExprs.push_back(PseudoSrcExpr);
7232 DstExprs.push_back(PseudoDstExpr);
7233 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00007234 }
7235
7236 if (Vars.empty())
7237 return nullptr;
7238
Alexey Bataeva63048e2015-03-23 06:18:07 +00007239 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
7240 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007241}
7242
Alexey Bataev6125da92014-07-21 11:26:11 +00007243OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
7244 SourceLocation StartLoc,
7245 SourceLocation LParenLoc,
7246 SourceLocation EndLoc) {
7247 if (VarList.empty())
7248 return nullptr;
7249
7250 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
7251}
Alexey Bataevdea47612014-07-23 07:46:59 +00007252
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007253OMPClause *
7254Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
7255 SourceLocation DepLoc, SourceLocation ColonLoc,
7256 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
7257 SourceLocation LParenLoc, SourceLocation EndLoc) {
7258 if (DepKind == OMPC_DEPEND_unknown) {
7259 std::string Values;
7260 std::string Sep(", ");
7261 for (unsigned i = 0; i < OMPC_DEPEND_unknown; ++i) {
7262 Values += "'";
7263 Values += getOpenMPSimpleClauseTypeName(OMPC_depend, i);
7264 Values += "'";
7265 switch (i) {
7266 case OMPC_DEPEND_unknown - 2:
7267 Values += " or ";
7268 break;
7269 case OMPC_DEPEND_unknown - 1:
7270 break;
7271 default:
7272 Values += Sep;
7273 break;
7274 }
7275 }
7276 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
7277 << Values << getOpenMPClauseName(OMPC_depend);
7278 return nullptr;
7279 }
7280 SmallVector<Expr *, 8> Vars;
7281 for (auto &RefExpr : VarList) {
7282 assert(RefExpr && "NULL expr in OpenMP shared clause.");
7283 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7284 // It will be analyzed later.
7285 Vars.push_back(RefExpr);
7286 continue;
7287 }
7288
7289 SourceLocation ELoc = RefExpr->getExprLoc();
7290 // OpenMP [2.11.1.1, Restrictions, p.3]
7291 // A variable that is part of another variable (such as a field of a
7292 // structure) but is not an array element or an array section cannot appear
7293 // in a depend clause.
7294 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007295 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
7296 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
7297 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
7298 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
7299 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007300 (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
7301 !ASE->getBase()->getType()->isArrayType())) {
7302 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
7303 << RefExpr->getSourceRange();
7304 continue;
7305 }
7306
7307 Vars.push_back(RefExpr->IgnoreParenImpCasts());
7308 }
7309
7310 if (Vars.empty())
7311 return nullptr;
7312
7313 return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind,
7314 DepLoc, ColonLoc, Vars);
7315}
Michael Wonge710d542015-08-07 16:16:36 +00007316
7317OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
7318 SourceLocation LParenLoc,
7319 SourceLocation EndLoc) {
7320 Expr *ValExpr = Device;
7321 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7322 !ValExpr->isInstantiationDependent()) {
7323 SourceLocation Loc = ValExpr->getExprLoc();
7324 ExprResult Value = PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7325 if (Value.isInvalid())
7326 return nullptr;
7327
7328 // OpenMP [2.9.1, Restrictions]
7329 // The device expression must evaluate to a non-negative integer value.
7330 llvm::APSInt Result;
7331 if (Value.get()->isIntegerConstantExpr(Result, Context) &&
7332 Result.isSigned() && !Result.isStrictlyPositive()) {
7333 Diag(Loc, diag::err_omp_negative_expression_in_clause)
7334 << "device" << ValExpr->getSourceRange();
7335 return nullptr;
7336 }
7337 }
Michael Wonge710d542015-08-07 16:16:36 +00007338 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7339}