blob: 86ae474323131b5881f1fc89ed05c90dac2e92e4 [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 Bataeva839ddd2016-03-17 10:19:46 +000018#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000022#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000026#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000027#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000028#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000030#include "clang/Sema/SemaInternal.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000031#include "llvm/ADT/PointerEmbeddedInt.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
Alexey Bataevf47c4b42017-09-26 13:47:31 +000038static Expr *CheckMapClauseExpressionBase(
39 Sema &SemaRef, Expr *E,
40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
41 OpenMPClauseKind CKind);
42
Alexey Bataev758e55e2013-09-06 18:03:48 +000043namespace {
44/// \brief Default data sharing attributes, which can be applied to directive.
45enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000046 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
47 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000048 DSA_shared = 1 << 1, /// \brief Default data sharing attribute 'shared'.
49};
50
51/// Attributes of the defaultmap clause.
52enum DefaultMapAttributes {
53 DMA_unspecified, /// Default mapping is not specified.
54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000055};
Alexey Bataev7ff55242014-06-19 09:13:45 +000056
Alexey Bataev758e55e2013-09-06 18:03:48 +000057/// \brief Stack for tracking declarations used in OpenMP directives and
58/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000059class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000060public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000061 struct DSAVarData final {
62 OpenMPDirectiveKind DKind = OMPD_unknown;
63 OpenMPClauseKind CKind = OMPC_unknown;
64 Expr *RefExpr = nullptr;
65 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000066 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000067 DSAVarData() = default;
Alexey Bataevf189cb72017-07-24 14:52:13 +000068 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr,
69 DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc)
70 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
71 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000072 };
Alexey Bataev8b427062016-05-25 12:36:08 +000073 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
74 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000075
Alexey Bataev758e55e2013-09-06 18:03:48 +000076private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000077 struct DSAInfo final {
78 OpenMPClauseKind Attributes = OMPC_unknown;
79 /// Pointer to a reference expression and a flag which shows that the
80 /// variable is marked as lastprivate(true) or not (false).
81 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
82 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000083 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000084 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
85 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000086 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
87 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000088 /// Struct that associates a component with the clause kind where they are
89 /// found.
90 struct MappedExprComponentTy {
91 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
92 OpenMPClauseKind Kind = OMPC_unknown;
93 };
94 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000095 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000096 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
97 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000098 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
99 DoacrossDependMapTy;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000100 struct ReductionData {
Alexey Bataevf87fa882017-07-21 19:26:22 +0000101 typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000102 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000103 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000104 ReductionData() = default;
105 void set(BinaryOperatorKind BO, SourceRange RR) {
106 ReductionRange = RR;
107 ReductionOp = BO;
108 }
109 void set(const Expr *RefExpr, SourceRange RR) {
110 ReductionRange = RR;
111 ReductionOp = RefExpr;
112 }
113 };
114 typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000115
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000116 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000117 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000118 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000119 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000120 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000121 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000122 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000123 SourceLocation DefaultAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000124 DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
125 SourceLocation DefaultMapAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000126 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000127 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000128 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000129 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000130 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
131 /// get the data (loop counters etc.) about enclosing loop-based construct.
132 /// This data is required during codegen.
133 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000134 /// \brief first argument (Expr *) contains optional argument of the
135 /// 'ordered' clause, the second one is true if the regions has 'ordered'
136 /// clause, false otherwise.
137 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000138 bool NowaitRegion = false;
139 bool CancelRegion = false;
140 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000141 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000142 /// Reference to the taskgroup task_reduction reference expression.
143 Expr *TaskgroupReductionRef = nullptr;
Alexey Bataeved09d242014-05-28 05:53:51 +0000144 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000145 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000146 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
147 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000148 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149 };
150
Axel Naumann323862e2016-02-03 10:45:22 +0000151 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000152
153 /// \brief Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000154 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000155 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
156 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000157 /// \brief true, if check for DSA must be from parent directive, false, if
158 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000159 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000160 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000161 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000162 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000163
164 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
165
David Majnemer9d168222016-08-05 17:44:54 +0000166 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000167
168 /// \brief Checks if the variable is a local for OpenMP region.
169 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000170
Alexey Bataev4b465392017-04-26 15:06:24 +0000171 bool isStackEmpty() const {
172 return Stack.empty() ||
173 Stack.back().second != CurrentNonCapturingFunctionScope ||
174 Stack.back().first.empty();
175 }
176
Alexey Bataev758e55e2013-09-06 18:03:48 +0000177public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000178 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000179
Alexey Bataevaac108a2015-06-23 04:51:00 +0000180 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
181 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000182
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000183 bool isForceVarCapturing() const { return ForceCapturing; }
184 void setForceVarCapturing(bool V) { ForceCapturing = V; }
185
Alexey Bataev758e55e2013-09-06 18:03:48 +0000186 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000187 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000188 if (Stack.empty() ||
189 Stack.back().second != CurrentNonCapturingFunctionScope)
190 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
191 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
192 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000193 }
194
195 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000196 assert(!Stack.back().first.empty() &&
197 "Data-sharing attributes stack is empty!");
198 Stack.back().first.pop_back();
199 }
200
201 /// Start new OpenMP region stack in new non-capturing function.
202 void pushFunction() {
203 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
204 assert(!isa<CapturingScopeInfo>(CurFnScope));
205 CurrentNonCapturingFunctionScope = CurFnScope;
206 }
207 /// Pop region stack for non-capturing function.
208 void popFunction(const FunctionScopeInfo *OldFSI) {
209 if (!Stack.empty() && Stack.back().second == OldFSI) {
210 assert(Stack.back().first.empty());
211 Stack.pop_back();
212 }
213 CurrentNonCapturingFunctionScope = nullptr;
214 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
215 if (!isa<CapturingScopeInfo>(FSI)) {
216 CurrentNonCapturingFunctionScope = FSI;
217 break;
218 }
219 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000220 }
221
Alexey Bataev28c75412015-12-15 08:19:24 +0000222 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
223 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
224 }
225 const std::pair<OMPCriticalDirective *, llvm::APSInt>
226 getCriticalWithHint(const DeclarationNameInfo &Name) const {
227 auto I = Criticals.find(Name.getAsString());
228 if (I != Criticals.end())
229 return I->second;
230 return std::make_pair(nullptr, llvm::APSInt());
231 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000232 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000233 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000234 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000235 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000236
Alexey Bataev9c821032015-04-30 04:23:23 +0000237 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000238 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000239 /// \brief Check if the specified variable is a loop control variable for
240 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000241 /// \return The index of the loop control variable in the list of associated
242 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000243 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000244 /// \brief Check if the specified variable is a loop control variable for
245 /// parent region.
246 /// \return The index of the loop control variable in the list of associated
247 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000248 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000249 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
250 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000251 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000252
Alexey Bataev758e55e2013-09-06 18:03:48 +0000253 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000254 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
255 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000256
Alexey Bataevfa312f32017-07-21 18:48:21 +0000257 /// Adds additional information for the reduction items with the reduction id
258 /// represented as an operator.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000259 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
260 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000261 /// Adds additional information for the reduction items with the reduction id
262 /// represented as reduction identifier.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000263 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
264 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000265 /// Returns the location and reduction operation from the innermost parent
266 /// region for the given \p D.
Alexey Bataevf189cb72017-07-24 14:52:13 +0000267 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000268 BinaryOperatorKind &BOK,
269 Expr *&TaskgroupDescriptor);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000270 /// Returns the location and reduction operation from the innermost parent
271 /// region for the given \p D.
Alexey Bataevf189cb72017-07-24 14:52:13 +0000272 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000273 const Expr *&ReductionRef,
274 Expr *&TaskgroupDescriptor);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000275 /// Return reduction reference expression for the current taskgroup.
276 Expr *getTaskgroupReductionRef() const {
277 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
278 "taskgroup reference expression requested for non taskgroup "
279 "directive.");
280 return Stack.back().first.back().TaskgroupReductionRef;
281 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000282 /// Checks if the given \p VD declaration is actually a taskgroup reduction
283 /// descriptor variable at the \p Level of OpenMP regions.
284 bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const {
285 return Stack.back().first[Level].TaskgroupReductionRef &&
286 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
287 ->getDecl() == VD;
288 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000289
Alexey Bataev758e55e2013-09-06 18:03:48 +0000290 /// \brief Returns data sharing attributes from top of the stack for the
291 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000292 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000293 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000294 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000295 /// \brief Checks if the specified variables has data-sharing attributes which
296 /// match specified \a CPred predicate in any directive which matches \a DPred
297 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000298 DSAVarData hasDSA(ValueDecl *D,
299 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
300 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
301 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000302 /// \brief Checks if the specified variables has data-sharing attributes which
303 /// match specified \a CPred predicate in any innermost directive which
304 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000305 DSAVarData
306 hasInnermostDSA(ValueDecl *D,
307 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
308 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
309 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000310 /// \brief Checks if the specified variables has explicit data-sharing
311 /// attributes which match specified \a CPred predicate at the specified
312 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000313 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000314 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000315 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000316
317 /// \brief Returns true if the directive at level \Level matches in the
318 /// specified \a DPred predicate.
319 bool hasExplicitDirective(
320 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
321 unsigned Level);
322
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000323 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000324 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
325 const DeclarationNameInfo &,
326 SourceLocation)> &DPred,
327 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000328
Alexey Bataev758e55e2013-09-06 18:03:48 +0000329 /// \brief Returns currently analyzed directive.
330 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000331 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000332 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000333 /// \brief Returns parent directive.
334 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000335 if (isStackEmpty() || Stack.back().first.size() == 1)
336 return OMPD_unknown;
337 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000338 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000339
340 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000341 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000342 assert(!isStackEmpty());
343 Stack.back().first.back().DefaultAttr = DSA_none;
344 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000345 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000346 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000347 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000348 assert(!isStackEmpty());
349 Stack.back().first.back().DefaultAttr = DSA_shared;
350 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000351 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000352 /// Set default data mapping attribute to 'tofrom:scalar'.
353 void setDefaultDMAToFromScalar(SourceLocation Loc) {
354 assert(!isStackEmpty());
355 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
356 Stack.back().first.back().DefaultMapAttrLoc = Loc;
357 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000358
359 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000360 return isStackEmpty() ? DSA_unspecified
361 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000362 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000363 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000364 return isStackEmpty() ? SourceLocation()
365 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000366 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000367 DefaultMapAttributes getDefaultDMA() const {
368 return isStackEmpty() ? DMA_unspecified
369 : Stack.back().first.back().DefaultMapAttr;
370 }
371 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
372 return Stack.back().first[Level].DefaultMapAttr;
373 }
374 SourceLocation getDefaultDMALocation() const {
375 return isStackEmpty() ? SourceLocation()
376 : Stack.back().first.back().DefaultMapAttrLoc;
377 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000378
Alexey Bataevf29276e2014-06-18 04:14:57 +0000379 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000380 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000381 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000382 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000383 }
384
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000385 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000386 void setOrderedRegion(bool IsOrdered, Expr *Param) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000387 assert(!isStackEmpty());
388 Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
389 Stack.back().first.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000390 }
391 /// \brief Returns true, if parent region is ordered (has associated
392 /// 'ordered' clause), false - otherwise.
393 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000394 if (isStackEmpty() || Stack.back().first.size() == 1)
395 return false;
396 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000397 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000398 /// \brief Returns optional parameter for the ordered region.
399 Expr *getParentOrderedRegionParam() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000400 if (isStackEmpty() || Stack.back().first.size() == 1)
401 return nullptr;
402 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
Alexey Bataev346265e2015-09-25 10:37:12 +0000403 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000404 /// \brief Marks current region as nowait (it has a 'nowait' clause).
405 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000406 assert(!isStackEmpty());
407 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000408 }
409 /// \brief Returns true, if parent region is nowait (has associated
410 /// 'nowait' clause), false - otherwise.
411 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000412 if (isStackEmpty() || Stack.back().first.size() == 1)
413 return false;
414 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000415 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000416 /// \brief Marks parent region as cancel region.
417 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000418 if (!isStackEmpty() && Stack.back().first.size() > 1) {
419 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
420 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
421 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000422 }
423 /// \brief Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000424 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000425 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000426 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000427
Alexey Bataev9c821032015-04-30 04:23:23 +0000428 /// \brief Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000429 void setAssociatedLoops(unsigned Val) {
430 assert(!isStackEmpty());
431 Stack.back().first.back().AssociatedLoops = Val;
432 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000433 /// \brief Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000434 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000435 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000436 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000437
Alexey Bataev13314bf2014-10-09 04:18:56 +0000438 /// \brief Marks current target region as one with closely nested teams
439 /// region.
440 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000441 if (!isStackEmpty() && Stack.back().first.size() > 1) {
442 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
443 TeamsRegionLoc;
444 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000445 }
446 /// \brief Returns true, if current region has closely nested teams region.
447 bool hasInnerTeamsRegion() const {
448 return getInnerTeamsRegionLoc().isValid();
449 }
450 /// \brief Returns location of the nested teams region (if any).
451 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000452 return isStackEmpty() ? SourceLocation()
453 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000454 }
455
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000456 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000457 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000458 }
459 Scope *getCurScope() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000460 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000461 }
462 SourceLocation getConstructLoc() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000463 return isStackEmpty() ? SourceLocation()
464 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000465 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000466
Samuel Antao4c8035b2016-12-12 18:00:20 +0000467 /// Do the check specified in \a Check to all component lists and return true
468 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000469 bool checkMappableExprComponentListsForDecl(
470 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000471 const llvm::function_ref<
472 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
473 OpenMPClauseKind)> &Check) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000474 if (isStackEmpty())
475 return false;
476 auto SI = Stack.back().first.rbegin();
477 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000478
479 if (SI == SE)
480 return false;
481
482 if (CurrentRegionOnly) {
483 SE = std::next(SI);
484 } else {
485 ++SI;
486 }
487
488 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000489 auto MI = SI->MappedExprComponents.find(VD);
490 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000491 for (auto &L : MI->second.Components)
492 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000493 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000494 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000495 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000496 }
497
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000498 /// Do the check specified in \a Check to all component lists at a given level
499 /// and return true if any issue is found.
500 bool checkMappableExprComponentListsForDeclAtLevel(
501 ValueDecl *VD, unsigned Level,
502 const llvm::function_ref<
503 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
504 OpenMPClauseKind)> &Check) {
505 if (isStackEmpty())
506 return false;
507
508 auto StartI = Stack.back().first.begin();
509 auto EndI = Stack.back().first.end();
510 if (std::distance(StartI, EndI) <= (int)Level)
511 return false;
512 std::advance(StartI, Level);
513
514 auto MI = StartI->MappedExprComponents.find(VD);
515 if (MI != StartI->MappedExprComponents.end())
516 for (auto &L : MI->second.Components)
517 if (Check(L, MI->second.Kind))
518 return true;
519 return false;
520 }
521
Samuel Antao4c8035b2016-12-12 18:00:20 +0000522 /// Create a new mappable expression component list associated with a given
523 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000524 void addMappableExpressionComponents(
525 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000526 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
527 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000528 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000529 "Not expecting to retrieve components from a empty stack!");
Alexey Bataev4b465392017-04-26 15:06:24 +0000530 auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000531 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000532 MEC.Components.resize(MEC.Components.size() + 1);
533 MEC.Components.back().append(Components.begin(), Components.end());
534 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000535 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000536
537 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000538 assert(!isStackEmpty());
539 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000540 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000541 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000542 assert(!isStackEmpty() && Stack.back().first.size() > 1);
543 auto &StackElem = *std::next(Stack.back().first.rbegin());
544 assert(isOpenMPWorksharingDirective(StackElem.Directive));
545 StackElem.DoacrossDepends.insert({C, OpsOffs});
Alexey Bataev8b427062016-05-25 12:36:08 +0000546 }
547 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
548 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000549 assert(!isStackEmpty());
550 auto &StackElem = Stack.back().first.back();
551 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
552 auto &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000553 return llvm::make_range(Ref.begin(), Ref.end());
554 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000555 return llvm::make_range(StackElem.DoacrossDepends.end(),
556 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000557 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000558};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000559bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000560 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
561 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000562}
Alexey Bataeved09d242014-05-28 05:53:51 +0000563} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000564
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000565static Expr *getExprAsWritten(Expr *E) {
566 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
567 E = ExprTemp->getSubExpr();
568
569 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
570 E = MTE->GetTemporaryExpr();
571
572 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
573 E = Binder->getSubExpr();
574
575 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
576 E = ICE->getSubExprAsWritten();
577 return E->IgnoreParens();
578}
579
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000580static ValueDecl *getCanonicalDecl(ValueDecl *D) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000581 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
582 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
583 D = ME->getMemberDecl();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000584 auto *VD = dyn_cast<VarDecl>(D);
585 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000586 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000587 VD = VD->getCanonicalDecl();
588 D = VD;
589 } else {
590 assert(FD);
591 FD = FD->getCanonicalDecl();
592 D = FD;
593 }
594 return D;
595}
596
David Majnemer9d168222016-08-05 17:44:54 +0000597DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000598 ValueDecl *D) {
599 D = getCanonicalDecl(D);
600 auto *VD = dyn_cast<VarDecl>(D);
601 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000602 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000603 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000604 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
605 // in a region but not in construct]
606 // File-scope or namespace-scope variables referenced in called routines
607 // in the region are shared unless they appear in a threadprivate
608 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000609 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000610 DVar.CKind = OMPC_shared;
611
612 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
613 // in a region but not in construct]
614 // Variables with static storage duration that are declared in called
615 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000616 if (VD && VD->hasGlobalStorage())
617 DVar.CKind = OMPC_shared;
618
619 // Non-static data members are shared by default.
620 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000621 DVar.CKind = OMPC_shared;
622
Alexey Bataev758e55e2013-09-06 18:03:48 +0000623 return DVar;
624 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000625
Alexey Bataevec3da872014-01-31 05:15:34 +0000626 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
627 // in a Construct, C/C++, predetermined, p.1]
628 // Variables with automatic storage duration that are declared in a scope
629 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000630 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
631 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000632 DVar.CKind = OMPC_private;
633 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000634 }
635
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000636 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000637 // Explicitly specified attributes and local variables with predetermined
638 // attributes.
639 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000640 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000641 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000642 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000643 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000644 return DVar;
645 }
646
647 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
648 // in a Construct, C/C++, implicitly determined, p.1]
649 // In a parallel or task construct, the data-sharing attributes of these
650 // variables are determined by the default clause, if present.
651 switch (Iter->DefaultAttr) {
652 case DSA_shared:
653 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000654 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000655 return DVar;
656 case DSA_none:
657 return DVar;
658 case DSA_unspecified:
659 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
660 // in a Construct, implicitly determined, p.2]
661 // In a parallel construct, if no default clause is present, these
662 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000663 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000664 if (isOpenMPParallelDirective(DVar.DKind) ||
665 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000666 DVar.CKind = OMPC_shared;
667 return DVar;
668 }
669
670 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
671 // in a Construct, implicitly determined, p.4]
672 // In a task construct, if no default clause is present, a variable that in
673 // the enclosing context is determined to be shared by all implicit tasks
674 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000675 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000676 DSAVarData DVarTemp;
Alexey Bataev4b465392017-04-26 15:06:24 +0000677 auto I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000678 do {
679 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000680 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000681 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000682 // In a task construct, if no default clause is present, a variable
683 // whose data-sharing attribute is not determined by the rules above is
684 // firstprivate.
685 DVarTemp = getDSA(I, D);
686 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000687 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000688 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000689 return DVar;
690 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000691 } while (I != E && !isParallelOrTaskRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000692 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000693 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000694 return DVar;
695 }
696 }
697 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
698 // in a Construct, implicitly determined, p.3]
699 // For constructs other than task, if no default clause is present, these
700 // variables inherit their data-sharing attributes from the enclosing
701 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000702 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000703}
704
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000705Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000706 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000707 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000708 auto &StackElem = Stack.back().first.back();
709 auto It = StackElem.AlignedMap.find(D);
710 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000711 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000712 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000713 return nullptr;
714 } else {
715 assert(It->second && "Unexpected nullptr expr in the aligned map");
716 return It->second;
717 }
718 return nullptr;
719}
720
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000721void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000722 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000723 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000724 auto &StackElem = Stack.back().first.back();
725 StackElem.LCVMap.insert(
726 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
Alexey Bataev9c821032015-04-30 04:23:23 +0000727}
728
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000729DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000730 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000731 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000732 auto &StackElem = Stack.back().first.back();
733 auto It = StackElem.LCVMap.find(D);
734 if (It != StackElem.LCVMap.end())
735 return It->second;
736 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000737}
738
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000739DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000740 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
741 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000742 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000743 auto &StackElem = *std::next(Stack.back().first.rbegin());
744 auto It = StackElem.LCVMap.find(D);
745 if (It != StackElem.LCVMap.end())
746 return It->second;
747 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000748}
749
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000750ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000751 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
752 "Data-sharing attributes stack is empty");
753 auto &StackElem = *std::next(Stack.back().first.rbegin());
754 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000755 return nullptr;
Alexey Bataev4b465392017-04-26 15:06:24 +0000756 for (auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000757 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000758 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000759 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000760}
761
Alexey Bataev90c228f2016-02-08 09:29:13 +0000762void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
763 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000764 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000765 if (A == OMPC_threadprivate) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000766 auto &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000767 Data.Attributes = A;
768 Data.RefExpr.setPointer(E);
769 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000770 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000771 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
772 auto &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000773 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
774 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
775 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
776 (isLoopControlVariable(D).first && A == OMPC_private));
777 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
778 Data.RefExpr.setInt(/*IntVal=*/true);
779 return;
780 }
781 const bool IsLastprivate =
782 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
783 Data.Attributes = A;
784 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
785 Data.PrivateCopy = PrivateCopy;
786 if (PrivateCopy) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000787 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000788 Data.Attributes = A;
789 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
790 Data.PrivateCopy = nullptr;
791 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000792 }
793}
794
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000795/// \brief Build a variable declaration for OpenMP loop iteration variable.
796static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
797 StringRef Name, const AttrVec *Attrs = nullptr) {
798 DeclContext *DC = SemaRef.CurContext;
799 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
800 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
801 VarDecl *Decl =
802 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
803 if (Attrs) {
804 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
805 I != E; ++I)
806 Decl->addAttr(*I);
807 }
808 Decl->setImplicit();
809 return Decl;
810}
811
812static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
813 SourceLocation Loc,
814 bool RefersToCapture = false) {
815 D->setReferenced();
816 D->markUsed(S.Context);
817 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
818 SourceLocation(), D, RefersToCapture, Loc, Ty,
819 VK_LValue);
820}
821
822void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
823 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000824 D = getCanonicalDecl(D);
825 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000826 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000827 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000828 "Additional reduction info may be specified only for reduction items.");
829 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
830 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000831 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000832 "Additional reduction info may be specified only once for reduction "
833 "items.");
834 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000835 Expr *&TaskgroupReductionRef =
836 Stack.back().first.back().TaskgroupReductionRef;
837 if (!TaskgroupReductionRef) {
Alexey Bataevd070a582017-10-25 15:54:04 +0000838 auto *VD = buildVarDecl(SemaRef, SR.getBegin(),
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000839 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +0000840 TaskgroupReductionRef =
841 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000842 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000843}
844
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000845void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
846 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000847 D = getCanonicalDecl(D);
848 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000849 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000850 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000851 "Additional reduction info may be specified only for reduction items.");
852 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
853 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000854 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000855 "Additional reduction info may be specified only once for reduction "
856 "items.");
857 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000858 Expr *&TaskgroupReductionRef =
859 Stack.back().first.back().TaskgroupReductionRef;
860 if (!TaskgroupReductionRef) {
Alexey Bataevd070a582017-10-25 15:54:04 +0000861 auto *VD = buildVarDecl(SemaRef, SR.getBegin(), SemaRef.Context.VoidPtrTy,
862 ".task_red.");
863 TaskgroupReductionRef =
864 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000865 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000866}
867
Alexey Bataevf189cb72017-07-24 14:52:13 +0000868DSAStackTy::DSAVarData
869DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000870 BinaryOperatorKind &BOK,
871 Expr *&TaskgroupDescriptor) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000872 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000873 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
874 if (Stack.back().first.empty())
875 return DSAVarData();
876 for (auto I = std::next(Stack.back().first.rbegin(), 1),
Alexey Bataevfa312f32017-07-21 18:48:21 +0000877 E = Stack.back().first.rend();
878 I != E; std::advance(I, 1)) {
879 auto &Data = I->SharingMap[D];
Alexey Bataevf189cb72017-07-24 14:52:13 +0000880 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000881 continue;
882 auto &ReductionData = I->ReductionMap[D];
883 if (!ReductionData.ReductionOp ||
884 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000885 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000886 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000887 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000888 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
889 "expression for the descriptor is not "
890 "set.");
891 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000892 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
893 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000894 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000895 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000896}
897
Alexey Bataevf189cb72017-07-24 14:52:13 +0000898DSAStackTy::DSAVarData
899DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000900 const Expr *&ReductionRef,
901 Expr *&TaskgroupDescriptor) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000902 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000903 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
904 if (Stack.back().first.empty())
905 return DSAVarData();
906 for (auto I = std::next(Stack.back().first.rbegin(), 1),
Alexey Bataevfa312f32017-07-21 18:48:21 +0000907 E = Stack.back().first.rend();
908 I != E; std::advance(I, 1)) {
909 auto &Data = I->SharingMap[D];
Alexey Bataevf189cb72017-07-24 14:52:13 +0000910 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000911 continue;
912 auto &ReductionData = I->ReductionMap[D];
913 if (!ReductionData.ReductionOp ||
914 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000915 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000916 SR = ReductionData.ReductionRange;
917 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000918 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
919 "expression for the descriptor is not "
920 "set.");
921 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000922 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
923 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000924 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000925 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000926}
927
Alexey Bataeved09d242014-05-28 05:53:51 +0000928bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000929 D = D->getCanonicalDecl();
Alexey Bataev4b465392017-04-26 15:06:24 +0000930 if (!isStackEmpty() && Stack.back().first.size() > 1) {
931 reverse_iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000932 Scope *TopScope = nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000933 while (I != E && !isParallelOrTaskRegion(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +0000934 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000935 if (I == E)
936 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000937 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000938 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000939 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +0000940 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000941 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000942 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000943 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000944}
945
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000946DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
947 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000948 DSAVarData DVar;
949
950 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
951 // in a Construct, C/C++, predetermined, p.1]
952 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000953 auto *VD = dyn_cast<VarDecl>(D);
954 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
955 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000956 SemaRef.getLangOpts().OpenMPUseTLS &&
957 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000958 (VD && VD->getStorageClass() == SC_Register &&
959 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
960 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000961 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000962 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000963 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000964 auto TI = Threadprivates.find(D);
965 if (TI != Threadprivates.end()) {
966 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000967 DVar.CKind = OMPC_threadprivate;
968 return DVar;
Alexey Bataev817d7f32017-11-14 21:01:01 +0000969 } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
970 DVar.RefExpr = buildDeclRefExpr(
971 SemaRef, VD, D->getType().getNonReferenceType(),
972 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
973 DVar.CKind = OMPC_threadprivate;
974 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000975 }
976
Alexey Bataev4b465392017-04-26 15:06:24 +0000977 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000978 // Not in OpenMP execution region and top scope was already checked.
979 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000980
Alexey Bataev758e55e2013-09-06 18:03:48 +0000981 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000982 // in a Construct, C/C++, predetermined, p.4]
983 // Static data members are shared.
984 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
985 // in a Construct, C/C++, predetermined, p.7]
986 // Variables with static storage duration that are declared in a scope
987 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000988 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000989 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000990 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000991 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000992 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000993
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000994 DVar.CKind = OMPC_shared;
995 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000996 }
997
998 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000999 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
1000 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001001 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1002 // in a Construct, C/C++, predetermined, p.6]
1003 // Variables with const qualified type having no mutable member are
1004 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001005 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +00001006 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +00001007 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1008 if (auto *CTD = CTSD->getSpecializedTemplate())
1009 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001010 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +00001011 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1012 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001013 // Variables with const-qualified type having no mutable member may be
1014 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001015 DSAVarData DVarTemp = hasDSA(
1016 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
1017 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001018 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
1019 return DVar;
1020
Alexey Bataev758e55e2013-09-06 18:03:48 +00001021 DVar.CKind = OMPC_shared;
1022 return DVar;
1023 }
1024
Alexey Bataev758e55e2013-09-06 18:03:48 +00001025 // Explicitly specified attributes and local variables with predetermined
1026 // attributes.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001027 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001028 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001029 if (FromParent && I != EndI)
1030 std::advance(I, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001031 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001032 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +00001033 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001034 DVar.CKind = I->SharingMap[D].Attributes;
1035 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001036 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001037 }
1038
1039 return DVar;
1040}
1041
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001042DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1043 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001044 if (isStackEmpty()) {
1045 StackTy::reverse_iterator I;
1046 return getDSA(I, D);
1047 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001048 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001049 auto StartI = Stack.back().first.rbegin();
1050 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001051 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001052 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001053 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001054}
1055
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001056DSAStackTy::DSAVarData
1057DSAStackTy::hasDSA(ValueDecl *D,
1058 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1059 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1060 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001061 if (isStackEmpty())
1062 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001063 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001064 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001065 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001066 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001067 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001068 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001069 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001070 continue;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001071 auto NewI = I;
1072 DSAVarData DVar = getDSA(NewI, D);
1073 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001074 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001075 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001076 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001077}
1078
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001079DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1080 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1081 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1082 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001083 if (isStackEmpty())
1084 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001085 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001086 auto StartI = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001087 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001088 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001089 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001090 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001091 return {};
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001092 auto NewI = StartI;
1093 DSAVarData DVar = getDSA(NewI, D);
1094 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001095}
1096
Alexey Bataevaac108a2015-06-23 04:51:00 +00001097bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001098 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001099 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001100 if (CPred(ClauseKindMode))
1101 return true;
Alexey Bataev4b465392017-04-26 15:06:24 +00001102 if (isStackEmpty())
1103 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001104 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001105 auto StartI = Stack.back().first.begin();
1106 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001107 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001108 return false;
1109 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001110 return (StartI->SharingMap.count(D) > 0) &&
1111 StartI->SharingMap[D].RefExpr.getPointer() &&
1112 CPred(StartI->SharingMap[D].Attributes) &&
1113 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +00001114}
1115
Samuel Antao4be30e92015-10-02 17:14:03 +00001116bool DSAStackTy::hasExplicitDirective(
1117 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1118 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001119 if (isStackEmpty())
1120 return false;
1121 auto StartI = Stack.back().first.begin();
1122 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001123 if (std::distance(StartI, EndI) <= (int)Level)
1124 return false;
1125 std::advance(StartI, Level);
1126 return DPred(StartI->Directive);
1127}
1128
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001129bool DSAStackTy::hasDirective(
1130 const llvm::function_ref<bool(OpenMPDirectiveKind,
1131 const DeclarationNameInfo &, SourceLocation)>
1132 &DPred,
1133 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +00001134 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001135 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001136 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001137 auto StartI = std::next(Stack.back().first.rbegin());
1138 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001139 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001140 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001141 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1142 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1143 return true;
1144 }
1145 return false;
1146}
1147
Alexey Bataev758e55e2013-09-06 18:03:48 +00001148void Sema::InitDataSharingAttributesStack() {
1149 VarDataSharingAttributesStack = new DSAStackTy(*this);
1150}
1151
1152#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1153
Alexey Bataev4b465392017-04-26 15:06:24 +00001154void Sema::pushOpenMPFunctionRegion() {
1155 DSAStack->pushFunction();
1156}
1157
1158void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1159 DSAStack->popFunction(OldFSI);
1160}
1161
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001162bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001163 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1164
1165 auto &Ctx = getASTContext();
1166 bool IsByRef = true;
1167
1168 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001169 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001170 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001171
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001172 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001173 // This table summarizes how a given variable should be passed to the device
1174 // given its type and the clauses where it appears. This table is based on
1175 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1176 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1177 //
1178 // =========================================================================
1179 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1180 // | |(tofrom:scalar)| | pvt | | | |
1181 // =========================================================================
1182 // | scl | | | | - | | bycopy|
1183 // | scl | | - | x | - | - | bycopy|
1184 // | scl | | x | - | - | - | null |
1185 // | scl | x | | | - | | byref |
1186 // | scl | x | - | x | - | - | bycopy|
1187 // | scl | x | x | - | - | - | null |
1188 // | scl | | - | - | - | x | byref |
1189 // | scl | x | - | - | - | x | byref |
1190 //
1191 // | agg | n.a. | | | - | | byref |
1192 // | agg | n.a. | - | x | - | - | byref |
1193 // | agg | n.a. | x | - | - | - | null |
1194 // | agg | n.a. | - | - | - | x | byref |
1195 // | agg | n.a. | - | - | - | x[] | byref |
1196 //
1197 // | ptr | n.a. | | | - | | bycopy|
1198 // | ptr | n.a. | - | x | - | - | bycopy|
1199 // | ptr | n.a. | x | - | - | - | null |
1200 // | ptr | n.a. | - | - | - | x | byref |
1201 // | ptr | n.a. | - | - | - | x[] | bycopy|
1202 // | ptr | n.a. | - | - | x | | bycopy|
1203 // | ptr | n.a. | - | - | x | x | bycopy|
1204 // | ptr | n.a. | - | - | x | x[] | bycopy|
1205 // =========================================================================
1206 // Legend:
1207 // scl - scalar
1208 // ptr - pointer
1209 // agg - aggregate
1210 // x - applies
1211 // - - invalid in this combination
1212 // [] - mapped with an array section
1213 // byref - should be mapped by reference
1214 // byval - should be mapped by value
1215 // null - initialize a local variable to null on the device
1216 //
1217 // Observations:
1218 // - All scalar declarations that show up in a map clause have to be passed
1219 // by reference, because they may have been mapped in the enclosing data
1220 // environment.
1221 // - If the scalar value does not fit the size of uintptr, it has to be
1222 // passed by reference, regardless the result in the table above.
1223 // - For pointers mapped by value that have either an implicit map or an
1224 // array section, the runtime library may pass the NULL value to the
1225 // device instead of the value passed to it by the compiler.
1226
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001227 if (Ty->isReferenceType())
1228 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001229
1230 // Locate map clauses and see if the variable being captured is referred to
1231 // in any of those clauses. Here we only care about variables, not fields,
1232 // because fields are part of aggregates.
1233 bool IsVariableUsedInMapClause = false;
1234 bool IsVariableAssociatedWithSection = false;
1235
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001236 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1237 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001238 MapExprComponents,
1239 OpenMPClauseKind WhereFoundClauseKind) {
1240 // Only the map clause information influences how a variable is
1241 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001242 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001243 if (WhereFoundClauseKind != OMPC_map)
1244 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001245
1246 auto EI = MapExprComponents.rbegin();
1247 auto EE = MapExprComponents.rend();
1248
1249 assert(EI != EE && "Invalid map expression!");
1250
1251 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1252 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1253
1254 ++EI;
1255 if (EI == EE)
1256 return false;
1257
1258 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1259 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1260 isa<MemberExpr>(EI->getAssociatedExpression())) {
1261 IsVariableAssociatedWithSection = true;
1262 // There is nothing more we need to know about this variable.
1263 return true;
1264 }
1265
1266 // Keep looking for more map info.
1267 return false;
1268 });
1269
1270 if (IsVariableUsedInMapClause) {
1271 // If variable is identified in a map clause it is always captured by
1272 // reference except if it is a pointer that is dereferenced somehow.
1273 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1274 } else {
1275 // By default, all the data that has a scalar type is mapped by copy.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001276 IsByRef = !Ty->isScalarType() ||
1277 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar;
Samuel Antao86ace552016-04-27 22:40:57 +00001278 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001279 }
1280
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001281 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1282 IsByRef = !DSAStack->hasExplicitDSA(
1283 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1284 Level, /*NotLastprivate=*/true);
1285 }
1286
Samuel Antao86ace552016-04-27 22:40:57 +00001287 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001288 // and alignment, because the runtime library only deals with uintptr types.
1289 // If it does not fit the uintptr size, we need to pass the data by reference
1290 // instead.
1291 if (!IsByRef &&
1292 (Ctx.getTypeSizeInChars(Ty) >
1293 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001294 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001295 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001296 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001297
1298 return IsByRef;
1299}
1300
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001301unsigned Sema::getOpenMPNestingLevel() const {
1302 assert(getLangOpts().OpenMP);
1303 return DSAStack->getNestingLevel();
1304}
1305
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001306bool Sema::isInOpenMPTargetExecutionDirective() const {
1307 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1308 !DSAStack->isClauseParsingMode()) ||
1309 DSAStack->hasDirective(
1310 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1311 SourceLocation) -> bool {
1312 return isOpenMPTargetExecutionDirective(K);
1313 },
1314 false);
1315}
1316
Alexey Bataev90c228f2016-02-08 09:29:13 +00001317VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001318 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001319 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001320
1321 // If we are attempting to capture a global variable in a directive with
1322 // 'target' we return true so that this global is also mapped to the device.
1323 //
1324 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1325 // then it should not be captured. Therefore, an extra check has to be
1326 // inserted here once support for 'declare target' is added.
1327 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001328 auto *VD = dyn_cast<VarDecl>(D);
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001329 if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective())
1330 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001331
Alexey Bataev48977c32015-08-04 08:10:48 +00001332 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1333 (!DSAStack->isClauseParsingMode() ||
1334 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001335 auto &&Info = DSAStack->isLoopControlVariable(D);
1336 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001337 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001338 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001339 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001340 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001341 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001342 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001343 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001344 DVarPrivate = DSAStack->hasDSA(
1345 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1346 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001347 if (DVarPrivate.CKind != OMPC_unknown)
1348 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001349 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001350 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001351}
1352
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001353bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001354 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1355 return DSAStack->hasExplicitDSA(
Alexey Bataev88202be2017-07-27 13:20:36 +00001356 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
1357 Level) ||
1358 // Consider taskgroup reduction descriptor variable a private to avoid
1359 // possible capture in the region.
1360 (DSAStack->hasExplicitDirective(
1361 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1362 Level) &&
1363 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001364}
1365
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001366void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
1367 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1368 D = getCanonicalDecl(D);
1369 OpenMPClauseKind OMPC = OMPC_unknown;
1370 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1371 const unsigned NewLevel = I - 1;
1372 if (DSAStack->hasExplicitDSA(D,
1373 [&OMPC](const OpenMPClauseKind K) {
1374 if (isOpenMPPrivate(K)) {
1375 OMPC = K;
1376 return true;
1377 }
1378 return false;
1379 },
1380 NewLevel))
1381 break;
1382 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1383 D, NewLevel,
1384 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1385 OpenMPClauseKind) { return true; })) {
1386 OMPC = OMPC_map;
1387 break;
1388 }
1389 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1390 NewLevel)) {
1391 OMPC = OMPC_firstprivate;
1392 break;
1393 }
1394 }
1395 if (OMPC != OMPC_unknown)
1396 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1397}
1398
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001399bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001400 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1401 // Return true if the current level is no longer enclosed in a target region.
1402
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001403 auto *VD = dyn_cast<VarDecl>(D);
1404 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001405 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1406 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001407}
1408
Alexey Bataeved09d242014-05-28 05:53:51 +00001409void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001410
1411void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1412 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001413 Scope *CurScope, SourceLocation Loc) {
1414 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001415 PushExpressionEvaluationContext(
1416 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001417}
1418
Alexey Bataevaac108a2015-06-23 04:51:00 +00001419void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1420 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001421}
1422
Alexey Bataevaac108a2015-06-23 04:51:00 +00001423void Sema::EndOpenMPClause() {
1424 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001425}
1426
Alexey Bataev758e55e2013-09-06 18:03:48 +00001427void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001428 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1429 // A variable of class type (or array thereof) that appears in a lastprivate
1430 // clause requires an accessible, unambiguous default constructor for the
1431 // class type, unless the list item is also specified in a firstprivate
1432 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001433 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001434 for (auto *C : D->clauses()) {
1435 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1436 SmallVector<Expr *, 8> PrivateCopies;
1437 for (auto *DE : Clause->varlists()) {
1438 if (DE->isValueDependent() || DE->isTypeDependent()) {
1439 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001440 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001441 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001442 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001443 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1444 QualType Type = VD->getType().getNonReferenceType();
1445 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001446 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001447 // Generate helper private variable and initialize it with the
1448 // default value. The address of the original variable is replaced
1449 // by the address of the new private variable in CodeGen. This new
1450 // variable is not added to IdResolver, so the code in the OpenMP
1451 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001452 auto *VDPrivate = buildVarDecl(
1453 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001454 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001455 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001456 if (VDPrivate->isInvalidDecl())
1457 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001458 PrivateCopies.push_back(buildDeclRefExpr(
1459 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001460 } else {
1461 // The variable is also a firstprivate, so initialization sequence
1462 // for private copy is generated already.
1463 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001464 }
1465 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001466 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001467 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001468 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001469 }
1470 }
1471 }
1472
Alexey Bataev758e55e2013-09-06 18:03:48 +00001473 DSAStack->pop();
1474 DiscardCleanupsInEvaluationContext();
1475 PopExpressionEvaluationContext();
1476}
1477
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001478static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1479 Expr *NumIterations, Sema &SemaRef,
1480 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001481
Alexey Bataeva769e072013-03-22 06:34:35 +00001482namespace {
1483
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001484class VarDeclFilterCCC : public CorrectionCandidateCallback {
1485private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001486 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001487
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001488public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001489 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001490 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001491 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001492 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001493 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001494 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1495 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001496 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001497 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001498 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001499};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001500
1501class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1502private:
1503 Sema &SemaRef;
1504
1505public:
1506 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1507 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1508 NamedDecl *ND = Candidate.getCorrectionDecl();
1509 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1510 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1511 SemaRef.getCurScope());
1512 }
1513 return false;
1514 }
1515};
1516
Alexey Bataeved09d242014-05-28 05:53:51 +00001517} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001518
1519ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1520 CXXScopeSpec &ScopeSpec,
1521 const DeclarationNameInfo &Id) {
1522 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1523 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1524
1525 if (Lookup.isAmbiguous())
1526 return ExprError();
1527
1528 VarDecl *VD;
1529 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001530 if (TypoCorrection Corrected = CorrectTypo(
1531 Id, LookupOrdinaryName, CurScope, nullptr,
1532 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001533 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001534 PDiag(Lookup.empty()
1535 ? diag::err_undeclared_var_use_suggest
1536 : diag::err_omp_expected_var_arg_suggest)
1537 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001538 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001539 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001540 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1541 : diag::err_omp_expected_var_arg)
1542 << Id.getName();
1543 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001544 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001545 } else {
1546 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001547 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001548 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1549 return ExprError();
1550 }
1551 }
1552 Lookup.suppressDiagnostics();
1553
1554 // OpenMP [2.9.2, Syntax, C/C++]
1555 // Variables must be file-scope, namespace-scope, or static block-scope.
1556 if (!VD->hasGlobalStorage()) {
1557 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001558 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1559 bool IsDecl =
1560 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001561 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001562 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1563 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001564 return ExprError();
1565 }
1566
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001567 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1568 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001569 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1570 // A threadprivate directive for file-scope variables must appear outside
1571 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001572 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1573 !getCurLexicalContext()->isTranslationUnit()) {
1574 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001575 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1576 bool IsDecl =
1577 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1578 Diag(VD->getLocation(),
1579 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1580 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001581 return ExprError();
1582 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001583 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1584 // A threadprivate directive for static class member variables must appear
1585 // in the class definition, in the same scope in which the member
1586 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001587 if (CanonicalVD->isStaticDataMember() &&
1588 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1589 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001590 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1591 bool IsDecl =
1592 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1593 Diag(VD->getLocation(),
1594 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1595 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001596 return ExprError();
1597 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001598 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1599 // A threadprivate directive for namespace-scope variables must appear
1600 // outside any definition or declaration other than the namespace
1601 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001602 if (CanonicalVD->getDeclContext()->isNamespace() &&
1603 (!getCurLexicalContext()->isFileContext() ||
1604 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1605 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001606 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1607 bool IsDecl =
1608 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1609 Diag(VD->getLocation(),
1610 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1611 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001612 return ExprError();
1613 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001614 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1615 // A threadprivate directive for static block-scope variables must appear
1616 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001617 if (CanonicalVD->isStaticLocal() && CurScope &&
1618 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001619 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001620 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1621 bool IsDecl =
1622 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1623 Diag(VD->getLocation(),
1624 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1625 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001626 return ExprError();
1627 }
1628
1629 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1630 // A threadprivate directive must lexically precede all references to any
1631 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001632 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001633 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001634 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001635 return ExprError();
1636 }
1637
1638 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001639 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1640 SourceLocation(), VD,
1641 /*RefersToEnclosingVariableOrCapture=*/false,
1642 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001643}
1644
Alexey Bataeved09d242014-05-28 05:53:51 +00001645Sema::DeclGroupPtrTy
1646Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1647 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001648 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001649 CurContext->addDecl(D);
1650 return DeclGroupPtrTy::make(DeclGroupRef(D));
1651 }
David Blaikie0403cb12016-01-15 23:43:25 +00001652 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001653}
1654
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001655namespace {
1656class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1657 Sema &SemaRef;
1658
1659public:
1660 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001661 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001662 if (VD->hasLocalStorage()) {
1663 SemaRef.Diag(E->getLocStart(),
1664 diag::err_omp_local_var_in_threadprivate_init)
1665 << E->getSourceRange();
1666 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1667 << VD << VD->getSourceRange();
1668 return true;
1669 }
1670 }
1671 return false;
1672 }
1673 bool VisitStmt(const Stmt *S) {
1674 for (auto Child : S->children()) {
1675 if (Child && Visit(Child))
1676 return true;
1677 }
1678 return false;
1679 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001680 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001681};
1682} // namespace
1683
Alexey Bataeved09d242014-05-28 05:53:51 +00001684OMPThreadPrivateDecl *
1685Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001686 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001687 for (auto &RefExpr : VarList) {
1688 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001689 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1690 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001691
Alexey Bataev376b4a42016-02-09 09:41:09 +00001692 // Mark variable as used.
1693 VD->setReferenced();
1694 VD->markUsed(Context);
1695
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001696 QualType QType = VD->getType();
1697 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1698 // It will be analyzed later.
1699 Vars.push_back(DE);
1700 continue;
1701 }
1702
Alexey Bataeva769e072013-03-22 06:34:35 +00001703 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1704 // A threadprivate variable must not have an incomplete type.
1705 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001706 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001707 continue;
1708 }
1709
1710 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1711 // A threadprivate variable must not have a reference type.
1712 if (VD->getType()->isReferenceType()) {
1713 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001714 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1715 bool IsDecl =
1716 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1717 Diag(VD->getLocation(),
1718 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1719 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001720 continue;
1721 }
1722
Samuel Antaof8b50122015-07-13 22:54:53 +00001723 // Check if this is a TLS variable. If TLS is not being supported, produce
1724 // the corresponding diagnostic.
1725 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1726 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1727 getLangOpts().OpenMPUseTLS &&
1728 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001729 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1730 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001731 Diag(ILoc, diag::err_omp_var_thread_local)
1732 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001733 bool IsDecl =
1734 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1735 Diag(VD->getLocation(),
1736 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1737 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001738 continue;
1739 }
1740
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001741 // Check if initial value of threadprivate variable reference variable with
1742 // local storage (it is not supported by runtime).
1743 if (auto Init = VD->getAnyInitializer()) {
1744 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001745 if (Checker.Visit(Init))
1746 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001747 }
1748
Alexey Bataeved09d242014-05-28 05:53:51 +00001749 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001750 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001751 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1752 Context, SourceRange(Loc, Loc)));
1753 if (auto *ML = Context.getASTMutationListener())
1754 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001755 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001756 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001757 if (!Vars.empty()) {
1758 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1759 Vars);
1760 D->setAccess(AS_public);
1761 }
1762 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001763}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001764
Alexey Bataev7ff55242014-06-19 09:13:45 +00001765static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001766 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001767 bool IsLoopIterVar = false) {
1768 if (DVar.RefExpr) {
1769 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1770 << getOpenMPClauseName(DVar.CKind);
1771 return;
1772 }
1773 enum {
1774 PDSA_StaticMemberShared,
1775 PDSA_StaticLocalVarShared,
1776 PDSA_LoopIterVarPrivate,
1777 PDSA_LoopIterVarLinear,
1778 PDSA_LoopIterVarLastprivate,
1779 PDSA_ConstVarShared,
1780 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001781 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001782 PDSA_LocalVarPrivate,
1783 PDSA_Implicit
1784 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001785 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001786 auto ReportLoc = D->getLocation();
1787 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001788 if (IsLoopIterVar) {
1789 if (DVar.CKind == OMPC_private)
1790 Reason = PDSA_LoopIterVarPrivate;
1791 else if (DVar.CKind == OMPC_lastprivate)
1792 Reason = PDSA_LoopIterVarLastprivate;
1793 else
1794 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001795 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1796 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001797 Reason = PDSA_TaskVarFirstprivate;
1798 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001799 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001800 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001801 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001802 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001803 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001804 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001805 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001806 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001807 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001808 ReportHint = true;
1809 Reason = PDSA_LocalVarPrivate;
1810 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001811 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001812 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001813 << Reason << ReportHint
1814 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1815 } else if (DVar.ImplicitDSALoc.isValid()) {
1816 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1817 << getOpenMPClauseName(DVar.CKind);
1818 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001819}
1820
Alexey Bataev758e55e2013-09-06 18:03:48 +00001821namespace {
1822class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1823 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001824 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001825 bool ErrorFound;
1826 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001827 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001828 llvm::SmallVector<Expr *, 8> ImplicitMap;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001829 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001830 llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00001831
Alexey Bataev758e55e2013-09-06 18:03:48 +00001832public:
1833 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001834 if (E->isTypeDependent() || E->isValueDependent() ||
1835 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1836 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001837 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001838 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001839 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001840 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00001841 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001842
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001843 auto DVar = Stack->getTopDSA(VD, false);
1844 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001845 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00001846 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001847
Alexey Bataevafe50572017-10-06 17:00:28 +00001848 // Skip internally declared static variables.
1849 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD))
1850 return;
1851
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001852 auto ELoc = E->getExprLoc();
1853 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001854 // The default(none) clause requires that each variable that is referenced
1855 // in the construct, and does not have a predetermined data-sharing
1856 // attribute, must have its data-sharing attribute explicitly determined
1857 // by being listed in a data-sharing attribute clause.
1858 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001859 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001860 VarsWithInheritedDSA.count(VD) == 0) {
1861 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001862 return;
1863 }
1864
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001865 if (isOpenMPTargetExecutionDirective(DKind) &&
1866 !Stack->isLoopControlVariable(VD).first) {
1867 if (!Stack->checkMappableExprComponentListsForDecl(
1868 VD, /*CurrentRegionOnly=*/true,
1869 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1870 StackComponents,
1871 OpenMPClauseKind) {
1872 // Variable is used if it has been marked as an array, array
1873 // section or the variable iself.
1874 return StackComponents.size() == 1 ||
1875 std::all_of(
1876 std::next(StackComponents.rbegin()),
1877 StackComponents.rend(),
1878 [](const OMPClauseMappableExprCommon::
1879 MappableComponent &MC) {
1880 return MC.getAssociatedDeclaration() ==
1881 nullptr &&
1882 (isa<OMPArraySectionExpr>(
1883 MC.getAssociatedExpression()) ||
1884 isa<ArraySubscriptExpr>(
1885 MC.getAssociatedExpression()));
1886 });
1887 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001888 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001889 // By default lambdas are captured as firstprivates.
1890 if (const auto *RD =
1891 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001892 IsFirstprivate = RD->isLambda();
1893 IsFirstprivate =
1894 IsFirstprivate ||
1895 (VD->getType().getNonReferenceType()->isScalarType() &&
1896 Stack->getDefaultDMA() != DMA_tofrom_scalar);
1897 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001898 ImplicitFirstprivate.emplace_back(E);
1899 else
1900 ImplicitMap.emplace_back(E);
1901 return;
1902 }
1903 }
1904
Alexey Bataev758e55e2013-09-06 18:03:48 +00001905 // OpenMP [2.9.3.6, Restrictions, p.2]
1906 // A list item that appears in a reduction clause of the innermost
1907 // enclosing worksharing or parallel construct may not be accessed in an
1908 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001909 DVar = Stack->hasInnermostDSA(
1910 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1911 [](OpenMPDirectiveKind K) -> bool {
1912 return isOpenMPParallelDirective(K) ||
1913 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1914 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001915 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001916 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001917 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001918 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1919 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001920 return;
1921 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001922
1923 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001924 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001925 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1926 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001927 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001928 }
1929 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001930 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001931 if (E->isTypeDependent() || E->isValueDependent() ||
1932 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1933 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001934 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1935 if (!FD)
1936 return;
1937 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001938 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001939 auto DVar = Stack->getTopDSA(FD, false);
1940 // Check if the variable has explicit DSA set and stop analysis if it
1941 // so.
1942 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
1943 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001944
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001945 if (isOpenMPTargetExecutionDirective(DKind) &&
1946 !Stack->isLoopControlVariable(FD).first &&
1947 !Stack->checkMappableExprComponentListsForDecl(
1948 FD, /*CurrentRegionOnly=*/true,
1949 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1950 StackComponents,
1951 OpenMPClauseKind) {
1952 return isa<CXXThisExpr>(
1953 cast<MemberExpr>(
1954 StackComponents.back().getAssociatedExpression())
1955 ->getBase()
1956 ->IgnoreParens());
1957 })) {
1958 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
1959 // A bit-field cannot appear in a map clause.
1960 //
1961 if (FD->isBitField()) {
1962 SemaRef.Diag(E->getMemberLoc(),
1963 diag::err_omp_bit_fields_forbidden_in_clause)
1964 << E->getSourceRange() << getOpenMPClauseName(OMPC_map);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001965 return;
1966 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001967 ImplicitMap.emplace_back(E);
1968 return;
1969 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001970
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001971 auto ELoc = E->getExprLoc();
1972 // OpenMP [2.9.3.6, Restrictions, p.2]
1973 // A list item that appears in a reduction clause of the innermost
1974 // enclosing worksharing or parallel construct may not be accessed in
1975 // an explicit task.
1976 DVar = Stack->hasInnermostDSA(
1977 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1978 [](OpenMPDirectiveKind K) -> bool {
1979 return isOpenMPParallelDirective(K) ||
1980 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1981 },
1982 /*FromParent=*/true);
1983 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1984 ErrorFound = true;
1985 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1986 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1987 return;
1988 }
1989
1990 // Define implicit data-sharing attributes for task.
1991 DVar = Stack->getImplicitDSA(FD, false);
1992 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1993 !Stack->isLoopControlVariable(FD).first)
1994 ImplicitFirstprivate.push_back(E);
1995 return;
1996 }
1997 if (isOpenMPTargetExecutionDirective(DKind) && !FD->isBitField()) {
1998 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
1999 CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map);
2000 auto *VD = cast<ValueDecl>(
2001 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2002 if (!Stack->checkMappableExprComponentListsForDecl(
2003 VD, /*CurrentRegionOnly=*/true,
2004 [&CurComponents](
2005 OMPClauseMappableExprCommon::MappableExprComponentListRef
2006 StackComponents,
2007 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002008 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002009 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002010 for (const auto &SC : llvm::reverse(StackComponents)) {
2011 // Do both expressions have the same kind?
2012 if (CCI->getAssociatedExpression()->getStmtClass() !=
2013 SC.getAssociatedExpression()->getStmtClass())
2014 if (!(isa<OMPArraySectionExpr>(
2015 SC.getAssociatedExpression()) &&
2016 isa<ArraySubscriptExpr>(
2017 CCI->getAssociatedExpression())))
2018 return false;
2019
2020 Decl *CCD = CCI->getAssociatedDeclaration();
2021 Decl *SCD = SC.getAssociatedDeclaration();
2022 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2023 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2024 if (SCD != CCD)
2025 return false;
2026 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002027 if (CCI == CCE)
2028 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002029 }
2030 return true;
2031 })) {
2032 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002033 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002034 } else
2035 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002036 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002037 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002038 for (auto *C : S->clauses()) {
2039 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002040 // for task|target directives.
2041 // Skip analysis of arguments of implicitly defined map clause for target
2042 // directives.
2043 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2044 C->isImplicit())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002045 for (auto *CC : C->children()) {
2046 if (CC)
2047 Visit(CC);
2048 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002049 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002050 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002051 }
2052 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002053 for (auto *C : S->children()) {
2054 if (C && !isa<OMPExecutableDirective>(C))
2055 Visit(C);
2056 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002057 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002058
2059 bool isErrorFound() { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002060 ArrayRef<Expr *> getImplicitFirstprivate() const {
2061 return ImplicitFirstprivate;
2062 }
2063 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002064 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002065 return VarsWithInheritedDSA;
2066 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002067
Alexey Bataev7ff55242014-06-19 09:13:45 +00002068 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2069 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002070};
Alexey Bataeved09d242014-05-28 05:53:51 +00002071} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002072
Alexey Bataevbae9a792014-06-27 10:37:06 +00002073void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002074 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002075 case OMPD_parallel:
2076 case OMPD_parallel_for:
2077 case OMPD_parallel_for_simd:
2078 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002079 case OMPD_teams:
2080 case OMPD_teams_distribute: {
Alexey Bataev9959db52014-05-06 10:08:46 +00002081 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002082 QualType KmpInt32PtrTy =
2083 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002084 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002085 std::make_pair(".global_tid.", KmpInt32PtrTy),
2086 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2087 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002088 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002089 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2090 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002091 break;
2092 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002093 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002094 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002095 case OMPD_target_parallel_for:
2096 case OMPD_target_parallel_for_simd: {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002097 Sema::CapturedParamNameType ParamsTarget[] = {
2098 std::make_pair(StringRef(), QualType()) // __context with shared vars
2099 };
2100 // Start a captured region for 'target' with no implicit parameters.
2101 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2102 ParamsTarget);
2103 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2104 QualType KmpInt32PtrTy =
2105 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002106 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002107 std::make_pair(".global_tid.", KmpInt32PtrTy),
2108 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2109 std::make_pair(StringRef(), QualType()) // __context with shared vars
2110 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002111 // Start a captured region for 'teams' or 'parallel'. Both regions have
2112 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002113 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002114 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002115 break;
2116 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002117 case OMPD_simd:
2118 case OMPD_for:
2119 case OMPD_for_simd:
2120 case OMPD_sections:
2121 case OMPD_section:
2122 case OMPD_single:
2123 case OMPD_master:
2124 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002125 case OMPD_taskgroup:
2126 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00002127 case OMPD_ordered:
2128 case OMPD_atomic:
2129 case OMPD_target_data:
2130 case OMPD_target:
Kelvin Li986330c2016-07-20 22:57:10 +00002131 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002132 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002133 std::make_pair(StringRef(), QualType()) // __context with shared vars
2134 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002135 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2136 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002137 break;
2138 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002139 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002140 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002141 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2142 FunctionProtoType::ExtProtoInfo EPI;
2143 EPI.Variadic = true;
2144 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002145 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002146 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002147 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2148 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2149 std::make_pair(".copy_fn.",
2150 Context.getPointerType(CopyFnType).withConst()),
2151 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002152 std::make_pair(StringRef(), QualType()) // __context with shared vars
2153 };
2154 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2155 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002156 // Mark this captured region as inlined, because we don't use outlined
2157 // function directly.
2158 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2159 AlwaysInlineAttr::CreateImplicit(
2160 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002161 break;
2162 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002163 case OMPD_taskloop:
2164 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002165 QualType KmpInt32Ty =
2166 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2167 QualType KmpUInt64Ty =
2168 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
2169 QualType KmpInt64Ty =
2170 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
2171 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2172 FunctionProtoType::ExtProtoInfo EPI;
2173 EPI.Variadic = true;
2174 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002175 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002176 std::make_pair(".global_tid.", KmpInt32Ty),
2177 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2178 std::make_pair(".privates.",
2179 Context.VoidPtrTy.withConst().withRestrict()),
2180 std::make_pair(
2181 ".copy_fn.",
2182 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2183 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2184 std::make_pair(".lb.", KmpUInt64Ty),
2185 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
2186 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002187 std::make_pair(".reductions.",
2188 Context.VoidPtrTy.withConst().withRestrict()),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002189 std::make_pair(StringRef(), QualType()) // __context with shared vars
2190 };
2191 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2192 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002193 // Mark this captured region as inlined, because we don't use outlined
2194 // function directly.
2195 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2196 AlwaysInlineAttr::CreateImplicit(
2197 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002198 break;
2199 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002200 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00002201 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00002202 case OMPD_distribute_parallel_for:
Kelvin Li579e41c2016-11-30 23:51:03 +00002203 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00002204 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li80e8f562016-12-29 22:16:30 +00002205 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00002206 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00002207 case OMPD_target_teams_distribute_parallel_for_simd:
2208 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00002209 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2210 QualType KmpInt32PtrTy =
2211 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2212 Sema::CapturedParamNameType Params[] = {
2213 std::make_pair(".global_tid.", KmpInt32PtrTy),
2214 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2215 std::make_pair(".previous.lb.", Context.getSizeType()),
2216 std::make_pair(".previous.ub.", Context.getSizeType()),
2217 std::make_pair(StringRef(), QualType()) // __context with shared vars
2218 };
2219 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2220 Params);
2221 break;
2222 }
Carlo Bertolli62fae152017-11-20 20:46:39 +00002223 case OMPD_teams_distribute_parallel_for: {
2224 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2225 QualType KmpInt32PtrTy =
2226 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2227
2228 Sema::CapturedParamNameType ParamsTeams[] = {
2229 std::make_pair(".global_tid.", KmpInt32PtrTy),
2230 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2231 std::make_pair(StringRef(), QualType()) // __context with shared vars
2232 };
2233 // Start a captured region for 'target' with no implicit parameters.
2234 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2235 ParamsTeams);
2236
2237 Sema::CapturedParamNameType ParamsParallel[] = {
2238 std::make_pair(".global_tid.", KmpInt32PtrTy),
2239 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2240 std::make_pair(".previous.lb.", Context.getSizeType()),
2241 std::make_pair(".previous.ub.", Context.getSizeType()),
2242 std::make_pair(StringRef(), QualType()) // __context with shared vars
2243 };
2244 // Start a captured region for 'teams' or 'parallel'. Both regions have
2245 // the same implicit parameters.
2246 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2247 ParamsParallel);
2248 break;
2249 }
Alexey Bataev7828b252017-11-21 17:08:48 +00002250 case OMPD_target_update:
2251 case OMPD_target_enter_data:
2252 case OMPD_target_exit_data: {
2253 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2254 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2255 FunctionProtoType::ExtProtoInfo EPI;
2256 EPI.Variadic = true;
2257 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2258 Sema::CapturedParamNameType Params[] = {
2259 std::make_pair(".global_tid.", KmpInt32Ty),
2260 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2261 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2262 std::make_pair(".copy_fn.",
2263 Context.getPointerType(CopyFnType).withConst()),
2264 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2265 std::make_pair(StringRef(), QualType()) // __context with shared vars
2266 };
2267 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2268 Params);
2269 // Mark this captured region as inlined, because we don't use outlined
2270 // function directly.
2271 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2272 AlwaysInlineAttr::CreateImplicit(
2273 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2274 break;
2275 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002276 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002277 case OMPD_taskyield:
2278 case OMPD_barrier:
2279 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002280 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002281 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002282 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002283 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002284 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002285 case OMPD_declare_target:
2286 case OMPD_end_declare_target:
Alexey Bataev9959db52014-05-06 10:08:46 +00002287 llvm_unreachable("OpenMP Directive is not allowed");
2288 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002289 llvm_unreachable("Unknown OpenMP directive");
2290 }
2291}
2292
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002293int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2294 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2295 getOpenMPCaptureRegions(CaptureRegions, DKind);
2296 return CaptureRegions.size();
2297}
2298
Alexey Bataev3392d762016-02-16 11:18:12 +00002299static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002300 Expr *CaptureExpr, bool WithInit,
2301 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002302 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002303 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002304 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002305 QualType Ty = Init->getType();
2306 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2307 if (S.getLangOpts().CPlusPlus)
2308 Ty = C.getLValueReferenceType(Ty);
2309 else {
2310 Ty = C.getPointerType(Ty);
2311 ExprResult Res =
2312 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2313 if (!Res.isUsable())
2314 return nullptr;
2315 Init = Res.get();
2316 }
Alexey Bataev61205072016-03-02 04:57:40 +00002317 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002318 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002319 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2320 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002321 if (!WithInit)
2322 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00002323 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002324 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002325 return CED;
2326}
2327
Alexey Bataev61205072016-03-02 04:57:40 +00002328static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2329 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002330 OMPCapturedExprDecl *CD;
2331 if (auto *VD = S.IsOpenMPCapturedDecl(D))
2332 CD = cast<OMPCapturedExprDecl>(VD);
2333 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00002334 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2335 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002336 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002337 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002338}
2339
Alexey Bataev5a3af132016-03-29 08:58:54 +00002340static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2341 if (!Ref) {
2342 auto *CD =
2343 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
2344 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
2345 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2346 CaptureExpr->getExprLoc());
2347 }
2348 ExprResult Res = Ref;
2349 if (!S.getLangOpts().CPlusPlus &&
2350 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2351 Ref->getType()->isPointerType())
2352 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2353 if (!Res.isUsable())
2354 return ExprError();
2355 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002356}
2357
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002358namespace {
2359// OpenMP directives parsed in this section are represented as a
2360// CapturedStatement with an associated statement. If a syntax error
2361// is detected during the parsing of the associated statement, the
2362// compiler must abort processing and close the CapturedStatement.
2363//
2364// Combined directives such as 'target parallel' have more than one
2365// nested CapturedStatements. This RAII ensures that we unwind out
2366// of all the nested CapturedStatements when an error is found.
2367class CaptureRegionUnwinderRAII {
2368private:
2369 Sema &S;
2370 bool &ErrorFound;
2371 OpenMPDirectiveKind DKind;
2372
2373public:
2374 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2375 OpenMPDirectiveKind DKind)
2376 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2377 ~CaptureRegionUnwinderRAII() {
2378 if (ErrorFound) {
2379 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2380 while (--ThisCaptureLevel >= 0)
2381 S.ActOnCapturedRegionError();
2382 }
2383 }
2384};
2385} // namespace
2386
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002387StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2388 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002389 bool ErrorFound = false;
2390 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2391 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002392 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002393 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002394 return StmtError();
2395 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002396
2397 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002398 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00002399 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002400 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002401 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002402 for (auto *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002403 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2404 Clause->getClauseKind() == OMPC_in_reduction) {
2405 // Capture taskgroup task_reduction descriptors inside the tasking regions
2406 // with the corresponding in_reduction items.
2407 auto *IRC = cast<OMPInReductionClause>(Clause);
2408 for (auto *E : IRC->taskgroup_descriptors())
2409 if (E)
2410 MarkDeclarationsReferencedInExpr(E);
2411 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002412 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002413 Clause->getClauseKind() == OMPC_copyprivate ||
2414 (getLangOpts().OpenMPUseTLS &&
2415 getASTContext().getTargetInfo().isTLSSupported() &&
2416 Clause->getClauseKind() == OMPC_copyin)) {
2417 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002418 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002419 for (auto *VarRef : Clause->children()) {
2420 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002421 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002422 }
2423 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002424 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002425 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002426 if (auto *C = OMPClauseWithPreInit::get(Clause))
2427 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002428 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2429 if (auto *E = C->getPostUpdateExpr())
2430 MarkDeclarationsReferencedInExpr(E);
2431 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002432 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002433 if (Clause->getClauseKind() == OMPC_schedule)
2434 SC = cast<OMPScheduleClause>(Clause);
2435 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002436 OC = cast<OMPOrderedClause>(Clause);
2437 else if (Clause->getClauseKind() == OMPC_linear)
2438 LCs.push_back(cast<OMPLinearClause>(Clause));
2439 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002440 // OpenMP, 2.7.1 Loop Construct, Restrictions
2441 // The nonmonotonic modifier cannot be specified if an ordered clause is
2442 // specified.
2443 if (SC &&
2444 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2445 SC->getSecondScheduleModifier() ==
2446 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2447 OC) {
2448 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2449 ? SC->getFirstScheduleModifierLoc()
2450 : SC->getSecondScheduleModifierLoc(),
2451 diag::err_omp_schedule_nonmonotonic_ordered)
2452 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2453 ErrorFound = true;
2454 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002455 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2456 for (auto *C : LCs) {
2457 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2458 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2459 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002460 ErrorFound = true;
2461 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002462 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2463 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2464 OC->getNumForLoops()) {
2465 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2466 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2467 ErrorFound = true;
2468 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002469 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002470 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002471 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002472 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002473 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2474 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2475 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2476 // Mark all variables in private list clauses as used in inner region.
2477 // Required for proper codegen of combined directives.
2478 // TODO: add processing for other clauses.
2479 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
2480 for (auto *C : PICs) {
2481 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2482 // Find the particular capture region for the clause if the
2483 // directive is a combined one with multiple capture regions.
2484 // If the directive is not a combined one, the capture region
2485 // associated with the clause is OMPD_unknown and is generated
2486 // only once.
2487 if (CaptureRegion == ThisCaptureRegion ||
2488 CaptureRegion == OMPD_unknown) {
2489 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2490 for (auto *D : DS->decls())
2491 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2492 }
2493 }
2494 }
2495 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002496 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002497 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002498 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002499}
2500
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002501static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2502 OpenMPDirectiveKind CancelRegion,
2503 SourceLocation StartLoc) {
2504 // CancelRegion is only needed for cancel and cancellation_point.
2505 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2506 return false;
2507
2508 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2509 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2510 return false;
2511
2512 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2513 << getOpenMPDirectiveName(CancelRegion);
2514 return true;
2515}
2516
2517static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002518 OpenMPDirectiveKind CurrentRegion,
2519 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002520 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002521 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002522 if (Stack->getCurScope()) {
2523 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002524 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002525 bool NestingProhibited = false;
2526 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002527 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002528 enum {
2529 NoRecommend,
2530 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002531 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002532 ShouldBeInTargetRegion,
2533 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002534 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002535 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002536 // OpenMP [2.16, Nesting of Regions]
2537 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002538 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002539 // An ordered construct with the simd clause is the only OpenMP
2540 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002541 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002542 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2543 // message.
2544 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2545 ? diag::err_omp_prohibited_region_simd
2546 : diag::warn_omp_nesting_simd);
2547 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002548 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002549 if (ParentRegion == OMPD_atomic) {
2550 // OpenMP [2.16, Nesting of Regions]
2551 // OpenMP constructs may not be nested inside an atomic region.
2552 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2553 return true;
2554 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002555 if (CurrentRegion == OMPD_section) {
2556 // OpenMP [2.7.2, sections Construct, Restrictions]
2557 // Orphaned section directives are prohibited. That is, the section
2558 // directives must appear within the sections construct and must not be
2559 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002560 if (ParentRegion != OMPD_sections &&
2561 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002562 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2563 << (ParentRegion != OMPD_unknown)
2564 << getOpenMPDirectiveName(ParentRegion);
2565 return true;
2566 }
2567 return false;
2568 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002569 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002570 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002571 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002572 if (ParentRegion == OMPD_unknown &&
2573 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002574 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002575 if (CurrentRegion == OMPD_cancellation_point ||
2576 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002577 // OpenMP [2.16, Nesting of Regions]
2578 // A cancellation point construct for which construct-type-clause is
2579 // taskgroup must be nested inside a task construct. A cancellation
2580 // point construct for which construct-type-clause is not taskgroup must
2581 // be closely nested inside an OpenMP construct that matches the type
2582 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002583 // A cancel construct for which construct-type-clause is taskgroup must be
2584 // nested inside a task construct. A cancel construct for which
2585 // construct-type-clause is not taskgroup must be closely nested inside an
2586 // OpenMP construct that matches the type specified in
2587 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002588 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002589 !((CancelRegion == OMPD_parallel &&
2590 (ParentRegion == OMPD_parallel ||
2591 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002592 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002593 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2594 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002595 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2596 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002597 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2598 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002599 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002600 // OpenMP [2.16, Nesting of Regions]
2601 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002602 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002603 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002604 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002605 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2606 // OpenMP [2.16, Nesting of Regions]
2607 // A critical region may not be nested (closely or otherwise) inside a
2608 // critical region with the same name. Note that this restriction is not
2609 // sufficient to prevent deadlock.
2610 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002611 bool DeadLock = Stack->hasDirective(
2612 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2613 const DeclarationNameInfo &DNI,
2614 SourceLocation Loc) -> bool {
2615 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2616 PreviousCriticalLoc = Loc;
2617 return true;
2618 } else
2619 return false;
2620 },
2621 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002622 if (DeadLock) {
2623 SemaRef.Diag(StartLoc,
2624 diag::err_omp_prohibited_region_critical_same_name)
2625 << CurrentName.getName();
2626 if (PreviousCriticalLoc.isValid())
2627 SemaRef.Diag(PreviousCriticalLoc,
2628 diag::note_omp_previous_critical_region);
2629 return true;
2630 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002631 } else if (CurrentRegion == OMPD_barrier) {
2632 // OpenMP [2.16, Nesting of Regions]
2633 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002634 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002635 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2636 isOpenMPTaskingDirective(ParentRegion) ||
2637 ParentRegion == OMPD_master ||
2638 ParentRegion == OMPD_critical ||
2639 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002640 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002641 !isOpenMPParallelDirective(CurrentRegion) &&
2642 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002643 // OpenMP [2.16, Nesting of Regions]
2644 // A worksharing region may not be closely nested inside a worksharing,
2645 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002646 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2647 isOpenMPTaskingDirective(ParentRegion) ||
2648 ParentRegion == OMPD_master ||
2649 ParentRegion == OMPD_critical ||
2650 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002651 Recommend = ShouldBeInParallelRegion;
2652 } else if (CurrentRegion == OMPD_ordered) {
2653 // OpenMP [2.16, Nesting of Regions]
2654 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002655 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002656 // An ordered region must be closely nested inside a loop region (or
2657 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002658 // OpenMP [2.8.1,simd Construct, Restrictions]
2659 // An ordered construct with the simd clause is the only OpenMP construct
2660 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002661 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002662 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002663 !(isOpenMPSimdDirective(ParentRegion) ||
2664 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002665 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002666 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002667 // OpenMP [2.16, Nesting of Regions]
2668 // If specified, a teams construct must be contained within a target
2669 // construct.
2670 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002671 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002672 Recommend = ShouldBeInTargetRegion;
2673 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2674 }
Kelvin Libf594a52016-12-17 05:48:59 +00002675 if (!NestingProhibited &&
2676 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2677 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2678 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002679 // OpenMP [2.16, Nesting of Regions]
2680 // distribute, parallel, parallel sections, parallel workshare, and the
2681 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2682 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002683 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2684 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002685 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002686 }
David Majnemer9d168222016-08-05 17:44:54 +00002687 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002688 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002689 // OpenMP 4.5 [2.17 Nesting of Regions]
2690 // The region associated with the distribute construct must be strictly
2691 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002692 NestingProhibited =
2693 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002694 Recommend = ShouldBeInTeamsRegion;
2695 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002696 if (!NestingProhibited &&
2697 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2698 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2699 // OpenMP 4.5 [2.17 Nesting of Regions]
2700 // If a target, target update, target data, target enter data, or
2701 // target exit data construct is encountered during execution of a
2702 // target region, the behavior is unspecified.
2703 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002704 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2705 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002706 if (isOpenMPTargetExecutionDirective(K)) {
2707 OffendingRegion = K;
2708 return true;
2709 } else
2710 return false;
2711 },
2712 false /* don't skip top directive */);
2713 CloseNesting = false;
2714 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002715 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002716 if (OrphanSeen) {
2717 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2718 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2719 } else {
2720 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2721 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2722 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2723 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002724 return true;
2725 }
2726 }
2727 return false;
2728}
2729
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002730static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2731 ArrayRef<OMPClause *> Clauses,
2732 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2733 bool ErrorFound = false;
2734 unsigned NamedModifiersNumber = 0;
2735 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2736 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002737 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002738 for (const auto *C : Clauses) {
2739 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2740 // At most one if clause without a directive-name-modifier can appear on
2741 // the directive.
2742 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2743 if (FoundNameModifiers[CurNM]) {
2744 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2745 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2746 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2747 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002748 } else if (CurNM != OMPD_unknown) {
2749 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002750 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002751 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002752 FoundNameModifiers[CurNM] = IC;
2753 if (CurNM == OMPD_unknown)
2754 continue;
2755 // Check if the specified name modifier is allowed for the current
2756 // directive.
2757 // At most one if clause with the particular directive-name-modifier can
2758 // appear on the directive.
2759 bool MatchFound = false;
2760 for (auto NM : AllowedNameModifiers) {
2761 if (CurNM == NM) {
2762 MatchFound = true;
2763 break;
2764 }
2765 }
2766 if (!MatchFound) {
2767 S.Diag(IC->getNameModifierLoc(),
2768 diag::err_omp_wrong_if_directive_name_modifier)
2769 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2770 ErrorFound = true;
2771 }
2772 }
2773 }
2774 // If any if clause on the directive includes a directive-name-modifier then
2775 // all if clauses on the directive must include a directive-name-modifier.
2776 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2777 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2778 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2779 diag::err_omp_no_more_if_clause);
2780 } else {
2781 std::string Values;
2782 std::string Sep(", ");
2783 unsigned AllowedCnt = 0;
2784 unsigned TotalAllowedNum =
2785 AllowedNameModifiers.size() - NamedModifiersNumber;
2786 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2787 ++Cnt) {
2788 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2789 if (!FoundNameModifiers[NM]) {
2790 Values += "'";
2791 Values += getOpenMPDirectiveName(NM);
2792 Values += "'";
2793 if (AllowedCnt + 2 == TotalAllowedNum)
2794 Values += " or ";
2795 else if (AllowedCnt + 1 != TotalAllowedNum)
2796 Values += Sep;
2797 ++AllowedCnt;
2798 }
2799 }
2800 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2801 diag::err_omp_unnamed_if_clause)
2802 << (TotalAllowedNum > 1) << Values;
2803 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002804 for (auto Loc : NameModifierLoc) {
2805 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2806 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002807 ErrorFound = true;
2808 }
2809 return ErrorFound;
2810}
2811
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002812StmtResult Sema::ActOnOpenMPExecutableDirective(
2813 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2814 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2815 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002816 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002817 // First check CancelRegion which is then used in checkNestingOfRegions.
2818 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2819 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002820 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002821 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002822
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002823 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002824 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002825 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002826 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002827 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002828 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2829
2830 // Check default data sharing attributes for referenced variables.
2831 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002832 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2833 Stmt *S = AStmt;
2834 while (--ThisCaptureLevel >= 0)
2835 S = cast<CapturedStmt>(S)->getCapturedStmt();
2836 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002837 if (DSAChecker.isErrorFound())
2838 return StmtError();
2839 // Generate list of implicitly defined firstprivate variables.
2840 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002841
Alexey Bataev88202be2017-07-27 13:20:36 +00002842 SmallVector<Expr *, 4> ImplicitFirstprivates(
2843 DSAChecker.getImplicitFirstprivate().begin(),
2844 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002845 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
2846 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00002847 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
2848 for (auto *C : Clauses) {
2849 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
2850 for (auto *E : IRC->taskgroup_descriptors())
2851 if (E)
2852 ImplicitFirstprivates.emplace_back(E);
2853 }
2854 }
2855 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002856 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00002857 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
2858 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002859 ClausesWithImplicit.push_back(Implicit);
2860 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00002861 ImplicitFirstprivates.size();
Alexey Bataev68446b72014-07-18 07:47:19 +00002862 } else
2863 ErrorFound = true;
2864 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002865 if (!ImplicitMaps.empty()) {
2866 if (OMPClause *Implicit = ActOnOpenMPMapClause(
2867 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
2868 SourceLocation(), SourceLocation(), ImplicitMaps,
2869 SourceLocation(), SourceLocation(), SourceLocation())) {
2870 ClausesWithImplicit.emplace_back(Implicit);
2871 ErrorFound |=
2872 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
2873 } else
2874 ErrorFound = true;
2875 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002876 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002877
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002878 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002879 switch (Kind) {
2880 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002881 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2882 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002883 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002884 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002885 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002886 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2887 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002888 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002889 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002890 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2891 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002892 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002893 case OMPD_for_simd:
2894 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2895 EndLoc, VarsWithInheritedDSA);
2896 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002897 case OMPD_sections:
2898 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2899 EndLoc);
2900 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002901 case OMPD_section:
2902 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002903 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002904 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2905 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002906 case OMPD_single:
2907 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2908 EndLoc);
2909 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002910 case OMPD_master:
2911 assert(ClausesWithImplicit.empty() &&
2912 "No clauses are allowed for 'omp master' directive");
2913 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2914 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002915 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002916 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2917 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002918 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002919 case OMPD_parallel_for:
2920 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2921 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002922 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002923 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002924 case OMPD_parallel_for_simd:
2925 Res = ActOnOpenMPParallelForSimdDirective(
2926 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002927 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002928 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002929 case OMPD_parallel_sections:
2930 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2931 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002932 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002933 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002934 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002935 Res =
2936 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002937 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002938 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002939 case OMPD_taskyield:
2940 assert(ClausesWithImplicit.empty() &&
2941 "No clauses are allowed for 'omp taskyield' directive");
2942 assert(AStmt == nullptr &&
2943 "No associated statement allowed for 'omp taskyield' directive");
2944 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2945 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002946 case OMPD_barrier:
2947 assert(ClausesWithImplicit.empty() &&
2948 "No clauses are allowed for 'omp barrier' directive");
2949 assert(AStmt == nullptr &&
2950 "No associated statement allowed for 'omp barrier' directive");
2951 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2952 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002953 case OMPD_taskwait:
2954 assert(ClausesWithImplicit.empty() &&
2955 "No clauses are allowed for 'omp taskwait' directive");
2956 assert(AStmt == nullptr &&
2957 "No associated statement allowed for 'omp taskwait' directive");
2958 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2959 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002960 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00002961 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
2962 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002963 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002964 case OMPD_flush:
2965 assert(AStmt == nullptr &&
2966 "No associated statement allowed for 'omp flush' directive");
2967 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2968 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002969 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002970 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2971 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002972 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002973 case OMPD_atomic:
2974 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2975 EndLoc);
2976 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002977 case OMPD_teams:
2978 Res =
2979 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2980 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002981 case OMPD_target:
2982 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2983 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002984 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002985 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002986 case OMPD_target_parallel:
2987 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2988 StartLoc, EndLoc);
2989 AllowedNameModifiers.push_back(OMPD_target);
2990 AllowedNameModifiers.push_back(OMPD_parallel);
2991 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002992 case OMPD_target_parallel_for:
2993 Res = ActOnOpenMPTargetParallelForDirective(
2994 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2995 AllowedNameModifiers.push_back(OMPD_target);
2996 AllowedNameModifiers.push_back(OMPD_parallel);
2997 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002998 case OMPD_cancellation_point:
2999 assert(ClausesWithImplicit.empty() &&
3000 "No clauses are allowed for 'omp cancellation point' directive");
3001 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3002 "cancellation point' directive");
3003 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3004 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003005 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003006 assert(AStmt == nullptr &&
3007 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003008 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3009 CancelRegion);
3010 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003011 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003012 case OMPD_target_data:
3013 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3014 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003015 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003016 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003017 case OMPD_target_enter_data:
3018 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003019 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003020 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3021 break;
Samuel Antao72590762016-01-19 20:04:50 +00003022 case OMPD_target_exit_data:
3023 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003024 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003025 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3026 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003027 case OMPD_taskloop:
3028 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3029 EndLoc, VarsWithInheritedDSA);
3030 AllowedNameModifiers.push_back(OMPD_taskloop);
3031 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003032 case OMPD_taskloop_simd:
3033 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3034 EndLoc, VarsWithInheritedDSA);
3035 AllowedNameModifiers.push_back(OMPD_taskloop);
3036 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003037 case OMPD_distribute:
3038 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3039 EndLoc, VarsWithInheritedDSA);
3040 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003041 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003042 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3043 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003044 AllowedNameModifiers.push_back(OMPD_target_update);
3045 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003046 case OMPD_distribute_parallel_for:
3047 Res = ActOnOpenMPDistributeParallelForDirective(
3048 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3049 AllowedNameModifiers.push_back(OMPD_parallel);
3050 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003051 case OMPD_distribute_parallel_for_simd:
3052 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3053 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3054 AllowedNameModifiers.push_back(OMPD_parallel);
3055 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003056 case OMPD_distribute_simd:
3057 Res = ActOnOpenMPDistributeSimdDirective(
3058 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3059 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003060 case OMPD_target_parallel_for_simd:
3061 Res = ActOnOpenMPTargetParallelForSimdDirective(
3062 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3063 AllowedNameModifiers.push_back(OMPD_target);
3064 AllowedNameModifiers.push_back(OMPD_parallel);
3065 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003066 case OMPD_target_simd:
3067 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3068 EndLoc, VarsWithInheritedDSA);
3069 AllowedNameModifiers.push_back(OMPD_target);
3070 break;
Kelvin Li02532872016-08-05 14:37:37 +00003071 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003072 Res = ActOnOpenMPTeamsDistributeDirective(
3073 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003074 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003075 case OMPD_teams_distribute_simd:
3076 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3077 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3078 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003079 case OMPD_teams_distribute_parallel_for_simd:
3080 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3081 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3082 AllowedNameModifiers.push_back(OMPD_parallel);
3083 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003084 case OMPD_teams_distribute_parallel_for:
3085 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3086 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3087 AllowedNameModifiers.push_back(OMPD_parallel);
3088 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003089 case OMPD_target_teams:
3090 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3091 EndLoc);
3092 AllowedNameModifiers.push_back(OMPD_target);
3093 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003094 case OMPD_target_teams_distribute:
3095 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3096 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3097 AllowedNameModifiers.push_back(OMPD_target);
3098 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003099 case OMPD_target_teams_distribute_parallel_for:
3100 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3101 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3102 AllowedNameModifiers.push_back(OMPD_target);
3103 AllowedNameModifiers.push_back(OMPD_parallel);
3104 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003105 case OMPD_target_teams_distribute_parallel_for_simd:
3106 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3107 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3108 AllowedNameModifiers.push_back(OMPD_target);
3109 AllowedNameModifiers.push_back(OMPD_parallel);
3110 break;
Kelvin Lida681182017-01-10 18:08:18 +00003111 case OMPD_target_teams_distribute_simd:
3112 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3113 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3114 AllowedNameModifiers.push_back(OMPD_target);
3115 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003116 case OMPD_declare_target:
3117 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003118 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003119 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003120 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003121 llvm_unreachable("OpenMP Directive is not allowed");
3122 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003123 llvm_unreachable("Unknown OpenMP directive");
3124 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003125
Alexey Bataev4acb8592014-07-07 13:01:15 +00003126 for (auto P : VarsWithInheritedDSA) {
3127 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3128 << P.first << P.second->getSourceRange();
3129 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003130 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3131
3132 if (!AllowedNameModifiers.empty())
3133 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3134 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003135
Alexey Bataeved09d242014-05-28 05:53:51 +00003136 if (ErrorFound)
3137 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003138 return Res;
3139}
3140
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003141Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3142 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003143 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003144 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3145 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003146 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003147 assert(Linears.size() == LinModifiers.size());
3148 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003149 if (!DG || DG.get().isNull())
3150 return DeclGroupPtrTy();
3151
3152 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003153 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003154 return DG;
3155 }
3156 auto *ADecl = DG.get().getSingleDecl();
3157 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3158 ADecl = FTD->getTemplatedDecl();
3159
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003160 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3161 if (!FD) {
3162 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003163 return DeclGroupPtrTy();
3164 }
3165
Alexey Bataev2af33e32016-04-07 12:45:37 +00003166 // OpenMP [2.8.2, declare simd construct, Description]
3167 // The parameter of the simdlen clause must be a constant positive integer
3168 // expression.
3169 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003170 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003171 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003172 // OpenMP [2.8.2, declare simd construct, Description]
3173 // The special this pointer can be used as if was one of the arguments to the
3174 // function in any of the linear, aligned, or uniform clauses.
3175 // The uniform clause declares one or more arguments to have an invariant
3176 // value for all concurrent invocations of the function in the execution of a
3177 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00003178 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3179 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003180 for (auto *E : Uniforms) {
3181 E = E->IgnoreParenImpCasts();
3182 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3183 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3184 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3185 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003186 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3187 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003188 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003189 }
3190 if (isa<CXXThisExpr>(E)) {
3191 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003192 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003193 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003194 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3195 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003196 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003197 // OpenMP [2.8.2, declare simd construct, Description]
3198 // The aligned clause declares that the object to which each list item points
3199 // is aligned to the number of bytes expressed in the optional parameter of
3200 // the aligned clause.
3201 // The special this pointer can be used as if was one of the arguments to the
3202 // function in any of the linear, aligned, or uniform clauses.
3203 // The type of list items appearing in the aligned clause must be array,
3204 // pointer, reference to array, or reference to pointer.
3205 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3206 Expr *AlignedThis = nullptr;
3207 for (auto *E : Aligneds) {
3208 E = E->IgnoreParenImpCasts();
3209 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3210 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3211 auto *CanonPVD = PVD->getCanonicalDecl();
3212 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3213 FD->getParamDecl(PVD->getFunctionScopeIndex())
3214 ->getCanonicalDecl() == CanonPVD) {
3215 // OpenMP [2.8.1, simd construct, Restrictions]
3216 // A list-item cannot appear in more than one aligned clause.
3217 if (AlignedArgs.count(CanonPVD) > 0) {
3218 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3219 << 1 << E->getSourceRange();
3220 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3221 diag::note_omp_explicit_dsa)
3222 << getOpenMPClauseName(OMPC_aligned);
3223 continue;
3224 }
3225 AlignedArgs[CanonPVD] = E;
3226 QualType QTy = PVD->getType()
3227 .getNonReferenceType()
3228 .getUnqualifiedType()
3229 .getCanonicalType();
3230 const Type *Ty = QTy.getTypePtrOrNull();
3231 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3232 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3233 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3234 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3235 }
3236 continue;
3237 }
3238 }
3239 if (isa<CXXThisExpr>(E)) {
3240 if (AlignedThis) {
3241 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3242 << 2 << E->getSourceRange();
3243 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3244 << getOpenMPClauseName(OMPC_aligned);
3245 }
3246 AlignedThis = E;
3247 continue;
3248 }
3249 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3250 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3251 }
3252 // The optional parameter of the aligned clause, alignment, must be a constant
3253 // positive integer expression. If no optional parameter is specified,
3254 // implementation-defined default alignments for SIMD instructions on the
3255 // target platforms are assumed.
3256 SmallVector<Expr *, 4> NewAligns;
3257 for (auto *E : Alignments) {
3258 ExprResult Align;
3259 if (E)
3260 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3261 NewAligns.push_back(Align.get());
3262 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003263 // OpenMP [2.8.2, declare simd construct, Description]
3264 // The linear clause declares one or more list items to be private to a SIMD
3265 // lane and to have a linear relationship with respect to the iteration space
3266 // of a loop.
3267 // The special this pointer can be used as if was one of the arguments to the
3268 // function in any of the linear, aligned, or uniform clauses.
3269 // When a linear-step expression is specified in a linear clause it must be
3270 // either a constant integer expression or an integer-typed parameter that is
3271 // specified in a uniform clause on the directive.
3272 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3273 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3274 auto MI = LinModifiers.begin();
3275 for (auto *E : Linears) {
3276 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3277 ++MI;
3278 E = E->IgnoreParenImpCasts();
3279 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3280 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3281 auto *CanonPVD = PVD->getCanonicalDecl();
3282 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3283 FD->getParamDecl(PVD->getFunctionScopeIndex())
3284 ->getCanonicalDecl() == CanonPVD) {
3285 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3286 // A list-item cannot appear in more than one linear clause.
3287 if (LinearArgs.count(CanonPVD) > 0) {
3288 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3289 << getOpenMPClauseName(OMPC_linear)
3290 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3291 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3292 diag::note_omp_explicit_dsa)
3293 << getOpenMPClauseName(OMPC_linear);
3294 continue;
3295 }
3296 // Each argument can appear in at most one uniform or linear clause.
3297 if (UniformedArgs.count(CanonPVD) > 0) {
3298 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3299 << getOpenMPClauseName(OMPC_linear)
3300 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3301 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3302 diag::note_omp_explicit_dsa)
3303 << getOpenMPClauseName(OMPC_uniform);
3304 continue;
3305 }
3306 LinearArgs[CanonPVD] = E;
3307 if (E->isValueDependent() || E->isTypeDependent() ||
3308 E->isInstantiationDependent() ||
3309 E->containsUnexpandedParameterPack())
3310 continue;
3311 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3312 PVD->getOriginalType());
3313 continue;
3314 }
3315 }
3316 if (isa<CXXThisExpr>(E)) {
3317 if (UniformedLinearThis) {
3318 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3319 << getOpenMPClauseName(OMPC_linear)
3320 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3321 << E->getSourceRange();
3322 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3323 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3324 : OMPC_linear);
3325 continue;
3326 }
3327 UniformedLinearThis = E;
3328 if (E->isValueDependent() || E->isTypeDependent() ||
3329 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3330 continue;
3331 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3332 E->getType());
3333 continue;
3334 }
3335 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3336 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3337 }
3338 Expr *Step = nullptr;
3339 Expr *NewStep = nullptr;
3340 SmallVector<Expr *, 4> NewSteps;
3341 for (auto *E : Steps) {
3342 // Skip the same step expression, it was checked already.
3343 if (Step == E || !E) {
3344 NewSteps.push_back(E ? NewStep : nullptr);
3345 continue;
3346 }
3347 Step = E;
3348 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3349 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3350 auto *CanonPVD = PVD->getCanonicalDecl();
3351 if (UniformedArgs.count(CanonPVD) == 0) {
3352 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3353 << Step->getSourceRange();
3354 } else if (E->isValueDependent() || E->isTypeDependent() ||
3355 E->isInstantiationDependent() ||
3356 E->containsUnexpandedParameterPack() ||
3357 CanonPVD->getType()->hasIntegerRepresentation())
3358 NewSteps.push_back(Step);
3359 else {
3360 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3361 << Step->getSourceRange();
3362 }
3363 continue;
3364 }
3365 NewStep = Step;
3366 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3367 !Step->isInstantiationDependent() &&
3368 !Step->containsUnexpandedParameterPack()) {
3369 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3370 .get();
3371 if (NewStep)
3372 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3373 }
3374 NewSteps.push_back(NewStep);
3375 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003376 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3377 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003378 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003379 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3380 const_cast<Expr **>(Linears.data()), Linears.size(),
3381 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3382 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003383 ADecl->addAttr(NewAttr);
3384 return ConvertDeclToDeclGroup(ADecl);
3385}
3386
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003387StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3388 Stmt *AStmt,
3389 SourceLocation StartLoc,
3390 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003391 if (!AStmt)
3392 return StmtError();
3393
Alexey Bataev9959db52014-05-06 10:08:46 +00003394 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3395 // 1.2.2 OpenMP Language Terminology
3396 // Structured block - An executable statement with a single entry at the
3397 // top and a single exit at the bottom.
3398 // The point of exit cannot be a branch out of the structured block.
3399 // longjmp() and throw() must not violate the entry/exit criteria.
3400 CS->getCapturedDecl()->setNothrow();
3401
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003402 getCurFunction()->setHasBranchProtectedScope();
3403
Alexey Bataev25e5b442015-09-15 12:52:43 +00003404 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3405 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003406}
3407
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003408namespace {
3409/// \brief Helper class for checking canonical form of the OpenMP loops and
3410/// extracting iteration space of each loop in the loop nest, that will be used
3411/// for IR generation.
3412class OpenMPIterationSpaceChecker {
3413 /// \brief Reference to Sema.
3414 Sema &SemaRef;
3415 /// \brief A location for diagnostics (when there is no some better location).
3416 SourceLocation DefaultLoc;
3417 /// \brief A location for diagnostics (when increment is not compatible).
3418 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003419 /// \brief A source location for referring to loop init later.
3420 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003421 /// \brief A source location for referring to condition later.
3422 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003423 /// \brief A source location for referring to increment later.
3424 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003425 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003426 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003427 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003428 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003429 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003430 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003431 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003432 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003433 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003434 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003435 /// \brief This flag is true when condition is one of:
3436 /// Var < UB
3437 /// Var <= UB
3438 /// UB > Var
3439 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003440 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003441 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003442 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003443 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003444 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003445
3446public:
3447 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003448 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003449 /// \brief Check init-expr for canonical loop form and save loop counter
3450 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003451 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003452 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3453 /// for less/greater and for strict/non-strict comparison.
3454 bool CheckCond(Expr *S);
3455 /// \brief Check incr-expr for canonical loop form and return true if it
3456 /// does not conform, otherwise save loop step (#Step).
3457 bool CheckInc(Expr *S);
3458 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003459 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003460 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003461 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003462 /// \brief Source range of the loop init.
3463 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3464 /// \brief Source range of the loop condition.
3465 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3466 /// \brief Source range of the loop increment.
3467 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3468 /// \brief True if the step should be subtracted.
3469 bool ShouldSubtractStep() const { return SubtractStep; }
3470 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003471 Expr *
3472 BuildNumIterations(Scope *S, const bool LimitedType,
3473 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003474 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003475 Expr *BuildPreCond(Scope *S, Expr *Cond,
3476 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003477 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003478 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3479 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003480 /// \brief Build reference expression to the private counter be used for
3481 /// codegen.
3482 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003483 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003484 Expr *BuildCounterInit() const;
3485 /// \brief Build step of the counter be used for codegen.
3486 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003487 /// \brief Return true if any expression is dependent.
3488 bool Dependent() const;
3489
3490private:
3491 /// \brief Check the right-hand side of an assignment in the increment
3492 /// expression.
3493 bool CheckIncRHS(Expr *RHS);
3494 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003495 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003496 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003497 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003498 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003499 /// \brief Helper to set loop increment.
3500 bool SetStep(Expr *NewStep, bool Subtract);
3501};
3502
3503bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003504 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003505 assert(!LB && !UB && !Step);
3506 return false;
3507 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003508 return LCDecl->getType()->isDependentType() ||
3509 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3510 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003511}
3512
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003513bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3514 Expr *NewLCRefExpr,
3515 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003516 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003517 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003518 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003519 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003520 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003521 LCDecl = getCanonicalDecl(NewLCDecl);
3522 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003523 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3524 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003525 if ((Ctor->isCopyOrMoveConstructor() ||
3526 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3527 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003528 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003529 LB = NewLB;
3530 return false;
3531}
3532
3533bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003534 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003535 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003536 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3537 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003538 if (!NewUB)
3539 return true;
3540 UB = NewUB;
3541 TestIsLessOp = LessOp;
3542 TestIsStrictOp = StrictOp;
3543 ConditionSrcRange = SR;
3544 ConditionLoc = SL;
3545 return false;
3546}
3547
3548bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3549 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003550 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003551 if (!NewStep)
3552 return true;
3553 if (!NewStep->isValueDependent()) {
3554 // Check that the step is integer expression.
3555 SourceLocation StepLoc = NewStep->getLocStart();
Alexey Bataev5372fb82017-08-31 23:06:52 +00003556 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3557 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003558 if (Val.isInvalid())
3559 return true;
3560 NewStep = Val.get();
3561
3562 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3563 // If test-expr is of form var relational-op b and relational-op is < or
3564 // <= then incr-expr must cause var to increase on each iteration of the
3565 // loop. If test-expr is of form var relational-op b and relational-op is
3566 // > or >= then incr-expr must cause var to decrease on each iteration of
3567 // the loop.
3568 // If test-expr is of form b relational-op var and relational-op is < or
3569 // <= then incr-expr must cause var to decrease on each iteration of the
3570 // loop. If test-expr is of form b relational-op var and relational-op is
3571 // > or >= then incr-expr must cause var to increase on each iteration of
3572 // the loop.
3573 llvm::APSInt Result;
3574 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3575 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3576 bool IsConstNeg =
3577 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003578 bool IsConstPos =
3579 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003580 bool IsConstZero = IsConstant && !Result.getBoolValue();
3581 if (UB && (IsConstZero ||
3582 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003583 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003584 SemaRef.Diag(NewStep->getExprLoc(),
3585 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003586 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003587 SemaRef.Diag(ConditionLoc,
3588 diag::note_omp_loop_cond_requres_compatible_incr)
3589 << TestIsLessOp << ConditionSrcRange;
3590 return true;
3591 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003592 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003593 NewStep =
3594 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3595 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003596 Subtract = !Subtract;
3597 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003598 }
3599
3600 Step = NewStep;
3601 SubtractStep = Subtract;
3602 return false;
3603}
3604
Alexey Bataev9c821032015-04-30 04:23:23 +00003605bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003606 // Check init-expr for canonical loop form and save loop counter
3607 // variable - #Var and its initialization value - #LB.
3608 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3609 // var = lb
3610 // integer-type var = lb
3611 // random-access-iterator-type var = lb
3612 // pointer-type var = lb
3613 //
3614 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003615 if (EmitDiags) {
3616 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3617 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003618 return true;
3619 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003620 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3621 if (!ExprTemp->cleanupsHaveSideEffects())
3622 S = ExprTemp->getSubExpr();
3623
Alexander Musmana5f070a2014-10-01 06:03:56 +00003624 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003625 if (Expr *E = dyn_cast<Expr>(S))
3626 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003627 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003628 if (BO->getOpcode() == BO_Assign) {
3629 auto *LHS = BO->getLHS()->IgnoreParens();
3630 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3631 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3632 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3633 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3634 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3635 }
3636 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3637 if (ME->isArrow() &&
3638 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3639 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3640 }
3641 }
David Majnemer9d168222016-08-05 17:44:54 +00003642 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003643 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003644 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003645 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003646 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003647 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003648 SemaRef.Diag(S->getLocStart(),
3649 diag::ext_omp_loop_not_canonical_init)
3650 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003651 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003652 }
3653 }
3654 }
David Majnemer9d168222016-08-05 17:44:54 +00003655 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003656 if (CE->getOperator() == OO_Equal) {
3657 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003658 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003659 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3660 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3661 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3662 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3663 }
3664 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3665 if (ME->isArrow() &&
3666 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3667 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3668 }
3669 }
3670 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003671
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003672 if (Dependent() || SemaRef.CurContext->isDependentContext())
3673 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003674 if (EmitDiags) {
3675 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3676 << S->getSourceRange();
3677 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003678 return true;
3679}
3680
Alexey Bataev23b69422014-06-18 07:08:49 +00003681/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003682/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003683static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003684 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003685 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003686 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003687 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3688 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003689 if ((Ctor->isCopyOrMoveConstructor() ||
3690 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3691 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003692 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003693 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003694 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003695 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003696 }
3697 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3698 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3699 return getCanonicalDecl(ME->getMemberDecl());
3700 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003701}
3702
3703bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3704 // Check test-expr for canonical form, save upper-bound UB, flags for
3705 // less/greater and for strict/non-strict comparison.
3706 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3707 // var relational-op b
3708 // b relational-op var
3709 //
3710 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003711 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003712 return true;
3713 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003714 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003715 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003716 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003717 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003718 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003719 return SetUB(BO->getRHS(),
3720 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3721 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3722 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003723 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003724 return SetUB(BO->getLHS(),
3725 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3726 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3727 BO->getSourceRange(), BO->getOperatorLoc());
3728 }
David Majnemer9d168222016-08-05 17:44:54 +00003729 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003730 if (CE->getNumArgs() == 2) {
3731 auto Op = CE->getOperator();
3732 switch (Op) {
3733 case OO_Greater:
3734 case OO_GreaterEqual:
3735 case OO_Less:
3736 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003737 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003738 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3739 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3740 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003741 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003742 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3743 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3744 CE->getOperatorLoc());
3745 break;
3746 default:
3747 break;
3748 }
3749 }
3750 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003751 if (Dependent() || SemaRef.CurContext->isDependentContext())
3752 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003753 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003754 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003755 return true;
3756}
3757
3758bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3759 // RHS of canonical loop form increment can be:
3760 // var + incr
3761 // incr + var
3762 // var - incr
3763 //
3764 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003765 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003766 if (BO->isAdditiveOp()) {
3767 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003768 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003769 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003770 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003771 return SetStep(BO->getLHS(), false);
3772 }
David Majnemer9d168222016-08-05 17:44:54 +00003773 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003774 bool IsAdd = CE->getOperator() == OO_Plus;
3775 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003776 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003777 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003778 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003779 return SetStep(CE->getArg(0), false);
3780 }
3781 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003782 if (Dependent() || SemaRef.CurContext->isDependentContext())
3783 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003784 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003785 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003786 return true;
3787}
3788
3789bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3790 // Check incr-expr for canonical loop form and return true if it
3791 // does not conform.
3792 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3793 // ++var
3794 // var++
3795 // --var
3796 // var--
3797 // var += incr
3798 // var -= incr
3799 // var = var + incr
3800 // var = incr + var
3801 // var = var - incr
3802 //
3803 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003804 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003805 return true;
3806 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003807 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3808 if (!ExprTemp->cleanupsHaveSideEffects())
3809 S = ExprTemp->getSubExpr();
3810
Alexander Musmana5f070a2014-10-01 06:03:56 +00003811 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003812 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003813 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003814 if (UO->isIncrementDecrementOp() &&
3815 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003816 return SetStep(SemaRef
3817 .ActOnIntegerConstant(UO->getLocStart(),
3818 (UO->isDecrementOp() ? -1 : 1))
3819 .get(),
3820 false);
3821 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003822 switch (BO->getOpcode()) {
3823 case BO_AddAssign:
3824 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003825 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003826 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3827 break;
3828 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003829 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003830 return CheckIncRHS(BO->getRHS());
3831 break;
3832 default:
3833 break;
3834 }
David Majnemer9d168222016-08-05 17:44:54 +00003835 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003836 switch (CE->getOperator()) {
3837 case OO_PlusPlus:
3838 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003839 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003840 return SetStep(SemaRef
3841 .ActOnIntegerConstant(
3842 CE->getLocStart(),
3843 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3844 .get(),
3845 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003846 break;
3847 case OO_PlusEqual:
3848 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003849 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003850 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3851 break;
3852 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003853 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003854 return CheckIncRHS(CE->getArg(1));
3855 break;
3856 default:
3857 break;
3858 }
3859 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003860 if (Dependent() || SemaRef.CurContext->isDependentContext())
3861 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003862 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003863 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003864 return true;
3865}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003866
Alexey Bataev5a3af132016-03-29 08:58:54 +00003867static ExprResult
3868tryBuildCapture(Sema &SemaRef, Expr *Capture,
3869 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003870 if (SemaRef.CurContext->isDependentContext())
3871 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003872 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3873 return SemaRef.PerformImplicitConversion(
3874 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3875 /*AllowExplicit=*/true);
3876 auto I = Captures.find(Capture);
3877 if (I != Captures.end())
3878 return buildCapture(SemaRef, Capture, I->second);
3879 DeclRefExpr *Ref = nullptr;
3880 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3881 Captures[Capture] = Ref;
3882 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003883}
3884
Alexander Musmana5f070a2014-10-01 06:03:56 +00003885/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003886Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3887 Scope *S, const bool LimitedType,
3888 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003889 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003890 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003891 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003892 SemaRef.getLangOpts().CPlusPlus) {
3893 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003894 auto *UBExpr = TestIsLessOp ? UB : LB;
3895 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003896 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3897 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003898 if (!Upper || !Lower)
3899 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003900
3901 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3902
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003903 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003904 // BuildBinOp already emitted error, this one is to point user to upper
3905 // and lower bound, and to tell what is passed to 'operator-'.
3906 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3907 << Upper->getSourceRange() << Lower->getSourceRange();
3908 return nullptr;
3909 }
3910 }
3911
3912 if (!Diff.isUsable())
3913 return nullptr;
3914
3915 // Upper - Lower [- 1]
3916 if (TestIsStrictOp)
3917 Diff = SemaRef.BuildBinOp(
3918 S, DefaultLoc, BO_Sub, Diff.get(),
3919 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3920 if (!Diff.isUsable())
3921 return nullptr;
3922
3923 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003924 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3925 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003926 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003927 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003928 if (!Diff.isUsable())
3929 return nullptr;
3930
3931 // Parentheses (for dumping/debugging purposes only).
3932 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3933 if (!Diff.isUsable())
3934 return nullptr;
3935
3936 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003937 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003938 if (!Diff.isUsable())
3939 return nullptr;
3940
Alexander Musman174b3ca2014-10-06 11:16:29 +00003941 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003942 QualType Type = Diff.get()->getType();
3943 auto &C = SemaRef.Context;
3944 bool UseVarType = VarType->hasIntegerRepresentation() &&
3945 C.getTypeSize(Type) > C.getTypeSize(VarType);
3946 if (!Type->isIntegerType() || UseVarType) {
3947 unsigned NewSize =
3948 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3949 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3950 : Type->hasSignedIntegerRepresentation();
3951 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003952 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3953 Diff = SemaRef.PerformImplicitConversion(
3954 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3955 if (!Diff.isUsable())
3956 return nullptr;
3957 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003958 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003959 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003960 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3961 if (NewSize != C.getTypeSize(Type)) {
3962 if (NewSize < C.getTypeSize(Type)) {
3963 assert(NewSize == 64 && "incorrect loop var size");
3964 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3965 << InitSrcRange << ConditionSrcRange;
3966 }
3967 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003968 NewSize, Type->hasSignedIntegerRepresentation() ||
3969 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003970 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3971 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3972 Sema::AA_Converting, true);
3973 if (!Diff.isUsable())
3974 return nullptr;
3975 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003976 }
3977 }
3978
Alexander Musmana5f070a2014-10-01 06:03:56 +00003979 return Diff.get();
3980}
3981
Alexey Bataev5a3af132016-03-29 08:58:54 +00003982Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3983 Scope *S, Expr *Cond,
3984 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003985 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3986 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3987 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003988
Alexey Bataev5a3af132016-03-29 08:58:54 +00003989 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3990 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3991 if (!NewLB.isUsable() || !NewUB.isUsable())
3992 return nullptr;
3993
Alexey Bataev62dbb972015-04-22 11:59:37 +00003994 auto CondExpr = SemaRef.BuildBinOp(
3995 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3996 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003997 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003998 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003999 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4000 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004001 CondExpr = SemaRef.PerformImplicitConversion(
4002 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4003 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004004 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004005 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4006 // Otherwise use original loop conditon and evaluate it in runtime.
4007 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4008}
4009
Alexander Musmana5f070a2014-10-01 06:03:56 +00004010/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004011DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004012 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004013 auto *VD = dyn_cast<VarDecl>(LCDecl);
4014 if (!VD) {
4015 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
4016 auto *Ref = buildDeclRefExpr(
4017 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004018 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4019 // If the loop control decl is explicitly marked as private, do not mark it
4020 // as captured again.
4021 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4022 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004023 return Ref;
4024 }
4025 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004026 DefaultLoc);
4027}
4028
4029Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004030 if (LCDecl && !LCDecl->isInvalidDecl()) {
4031 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00004032 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004033 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
4034 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004035 if (PrivateVar->isInvalidDecl())
4036 return nullptr;
4037 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4038 }
4039 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004040}
4041
Samuel Antao4c8035b2016-12-12 18:00:20 +00004042/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004043Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
4044
4045/// \brief Build step of the counter be used for codegen.
4046Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
4047
4048/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004049struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004050 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004051 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004052 /// \brief This expression calculates the number of iterations in the loop.
4053 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004054 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004055 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004056 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00004057 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004058 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004059 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004060 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004061 /// \brief This is step for the #CounterVar used to generate its update:
4062 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004063 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004064 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004065 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004066 /// \brief Source range of the loop init.
4067 SourceRange InitSrcRange;
4068 /// \brief Source range of the loop condition.
4069 SourceRange CondSrcRange;
4070 /// \brief Source range of the loop increment.
4071 SourceRange IncSrcRange;
4072};
4073
Alexey Bataev23b69422014-06-18 07:08:49 +00004074} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004075
Alexey Bataev9c821032015-04-30 04:23:23 +00004076void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4077 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4078 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004079 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4080 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004081 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4082 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004083 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4084 if (auto *D = ISC.GetLoopDecl()) {
4085 auto *VD = dyn_cast<VarDecl>(D);
4086 if (!VD) {
4087 if (auto *Private = IsOpenMPCapturedDecl(D))
4088 VD = Private;
4089 else {
4090 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4091 /*WithInit=*/false);
4092 VD = cast<VarDecl>(Ref->getDecl());
4093 }
4094 }
4095 DSAStack->addLoopControlVariable(D, VD);
4096 }
4097 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004098 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004099 }
4100}
4101
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004102/// \brief Called on a for stmt to check and extract its iteration space
4103/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00004104static bool CheckOpenMPIterationSpace(
4105 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4106 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004107 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004108 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004109 LoopIterationSpace &ResultIterSpace,
4110 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004111 // OpenMP [2.6, Canonical Loop Form]
4112 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004113 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004114 if (!For) {
4115 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004116 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4117 << getOpenMPDirectiveName(DKind) << NestedLoopCount
4118 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4119 if (NestedLoopCount > 1) {
4120 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4121 SemaRef.Diag(DSA.getConstructLoc(),
4122 diag::note_omp_collapse_ordered_expr)
4123 << 2 << CollapseLoopCountExpr->getSourceRange()
4124 << OrderedLoopCountExpr->getSourceRange();
4125 else if (CollapseLoopCountExpr)
4126 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4127 diag::note_omp_collapse_ordered_expr)
4128 << 0 << CollapseLoopCountExpr->getSourceRange();
4129 else
4130 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4131 diag::note_omp_collapse_ordered_expr)
4132 << 1 << OrderedLoopCountExpr->getSourceRange();
4133 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004134 return true;
4135 }
4136 assert(For->getBody());
4137
4138 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4139
4140 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00004141 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004142 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004143 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004144
4145 bool HasErrors = false;
4146
4147 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004148 if (auto *LCDecl = ISC.GetLoopDecl()) {
4149 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004150
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004151 // OpenMP [2.6, Canonical Loop Form]
4152 // Var is one of the following:
4153 // A variable of signed or unsigned integer type.
4154 // For C++, a variable of a random access iterator type.
4155 // For C, a variable of a pointer type.
4156 auto VarType = LCDecl->getType().getNonReferenceType();
4157 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4158 !VarType->isPointerType() &&
4159 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4160 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4161 << SemaRef.getLangOpts().CPlusPlus;
4162 HasErrors = true;
4163 }
4164
4165 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4166 // a Construct
4167 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4168 // parallel for construct is (are) private.
4169 // The loop iteration variable in the associated for-loop of a simd
4170 // construct with just one associated for-loop is linear with a
4171 // constant-linear-step that is the increment of the associated for-loop.
4172 // Exclude loop var from the list of variables with implicitly defined data
4173 // sharing attributes.
4174 VarsWithImplicitDSA.erase(LCDecl);
4175
4176 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4177 // in a Construct, C/C++].
4178 // The loop iteration variable in the associated for-loop of a simd
4179 // construct with just one associated for-loop may be listed in a linear
4180 // clause with a constant-linear-step that is the increment of the
4181 // associated for-loop.
4182 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4183 // parallel for construct may be listed in a private or lastprivate clause.
4184 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4185 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4186 // declared in the loop and it is predetermined as a private.
4187 auto PredeterminedCKind =
4188 isOpenMPSimdDirective(DKind)
4189 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4190 : OMPC_private;
4191 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4192 DVar.CKind != PredeterminedCKind) ||
4193 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4194 isOpenMPDistributeDirective(DKind)) &&
4195 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4196 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4197 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4198 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4199 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4200 << getOpenMPClauseName(PredeterminedCKind);
4201 if (DVar.RefExpr == nullptr)
4202 DVar.CKind = PredeterminedCKind;
4203 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4204 HasErrors = true;
4205 } else if (LoopDeclRefExpr != nullptr) {
4206 // Make the loop iteration variable private (for worksharing constructs),
4207 // linear (for simd directives with the only one associated loop) or
4208 // lastprivate (for simd directives with several collapsed or ordered
4209 // loops).
4210 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004211 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4212 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004213 /*FromParent=*/false);
4214 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4215 }
4216
4217 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4218
4219 // Check test-expr.
4220 HasErrors |= ISC.CheckCond(For->getCond());
4221
4222 // Check incr-expr.
4223 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004224 }
4225
Alexander Musmana5f070a2014-10-01 06:03:56 +00004226 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004227 return HasErrors;
4228
Alexander Musmana5f070a2014-10-01 06:03:56 +00004229 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004230 ResultIterSpace.PreCond =
4231 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00004232 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004233 DSA.getCurScope(),
4234 (isOpenMPWorksharingDirective(DKind) ||
4235 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4236 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004237 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00004238 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004239 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4240 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4241 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4242 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4243 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4244 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4245
Alexey Bataev62dbb972015-04-22 11:59:37 +00004246 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4247 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004248 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004249 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004250 ResultIterSpace.CounterInit == nullptr ||
4251 ResultIterSpace.CounterStep == nullptr);
4252
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004253 return HasErrors;
4254}
4255
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004256/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004257static ExprResult
4258BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4259 ExprResult Start,
4260 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004261 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004262 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4263 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004264 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004265 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004266 VarRef.get()->getType())) {
4267 NewStart = SemaRef.PerformImplicitConversion(
4268 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4269 /*AllowExplicit=*/true);
4270 if (!NewStart.isUsable())
4271 return ExprError();
4272 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004273
4274 auto Init =
4275 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4276 return Init;
4277}
4278
Alexander Musmana5f070a2014-10-01 06:03:56 +00004279/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004280static ExprResult
4281BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4282 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4283 ExprResult Step, bool Subtract,
4284 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004285 // Add parentheses (for debugging purposes only).
4286 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4287 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4288 !Step.isUsable())
4289 return ExprError();
4290
Alexey Bataev5a3af132016-03-29 08:58:54 +00004291 ExprResult NewStep = Step;
4292 if (Captures)
4293 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004294 if (NewStep.isInvalid())
4295 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004296 ExprResult Update =
4297 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004298 if (!Update.isUsable())
4299 return ExprError();
4300
Alexey Bataevc0214e02016-02-16 12:13:49 +00004301 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4302 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004303 ExprResult NewStart = Start;
4304 if (Captures)
4305 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004306 if (NewStart.isInvalid())
4307 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004308
Alexey Bataevc0214e02016-02-16 12:13:49 +00004309 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4310 ExprResult SavedUpdate = Update;
4311 ExprResult UpdateVal;
4312 if (VarRef.get()->getType()->isOverloadableType() ||
4313 NewStart.get()->getType()->isOverloadableType() ||
4314 Update.get()->getType()->isOverloadableType()) {
4315 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4316 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4317 Update =
4318 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4319 if (Update.isUsable()) {
4320 UpdateVal =
4321 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4322 VarRef.get(), SavedUpdate.get());
4323 if (UpdateVal.isUsable()) {
4324 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4325 UpdateVal.get());
4326 }
4327 }
4328 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4329 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004330
Alexey Bataevc0214e02016-02-16 12:13:49 +00004331 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4332 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4333 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4334 NewStart.get(), SavedUpdate.get());
4335 if (!Update.isUsable())
4336 return ExprError();
4337
Alexey Bataev11481f52016-02-17 10:29:05 +00004338 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4339 VarRef.get()->getType())) {
4340 Update = SemaRef.PerformImplicitConversion(
4341 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4342 if (!Update.isUsable())
4343 return ExprError();
4344 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004345
4346 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4347 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004348 return Update;
4349}
4350
4351/// \brief Convert integer expression \a E to make it have at least \a Bits
4352/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004353static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004354 if (E == nullptr)
4355 return ExprError();
4356 auto &C = SemaRef.Context;
4357 QualType OldType = E->getType();
4358 unsigned HasBits = C.getTypeSize(OldType);
4359 if (HasBits >= Bits)
4360 return ExprResult(E);
4361 // OK to convert to signed, because new type has more bits than old.
4362 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4363 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4364 true);
4365}
4366
4367/// \brief Check if the given expression \a E is a constant integer that fits
4368/// into \a Bits bits.
4369static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4370 if (E == nullptr)
4371 return false;
4372 llvm::APSInt Result;
4373 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4374 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4375 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004376}
4377
Alexey Bataev5a3af132016-03-29 08:58:54 +00004378/// Build preinits statement for the given declarations.
4379static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00004380 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004381 if (!PreInits.empty()) {
4382 return new (Context) DeclStmt(
4383 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4384 SourceLocation(), SourceLocation());
4385 }
4386 return nullptr;
4387}
4388
4389/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00004390static Stmt *
4391buildPreInits(ASTContext &Context,
4392 const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004393 if (!Captures.empty()) {
4394 SmallVector<Decl *, 16> PreInits;
4395 for (auto &Pair : Captures)
4396 PreInits.push_back(Pair.second->getDecl());
4397 return buildPreInits(Context, PreInits);
4398 }
4399 return nullptr;
4400}
4401
4402/// Build postupdate expression for the given list of postupdates expressions.
4403static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4404 Expr *PostUpdate = nullptr;
4405 if (!PostUpdates.empty()) {
4406 for (auto *E : PostUpdates) {
4407 Expr *ConvE = S.BuildCStyleCastExpr(
4408 E->getExprLoc(),
4409 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4410 E->getExprLoc(), E)
4411 .get();
4412 PostUpdate = PostUpdate
4413 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4414 PostUpdate, ConvE)
4415 .get()
4416 : ConvE;
4417 }
4418 }
4419 return PostUpdate;
4420}
4421
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004422/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004423/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4424/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004425static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004426CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4427 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4428 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004429 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004430 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004431 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004432 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004433 // Found 'collapse' clause - calculate collapse number.
4434 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004435 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004436 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004437 }
4438 if (OrderedLoopCountExpr) {
4439 // Found 'ordered' clause - calculate collapse number.
4440 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004441 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4442 if (Result.getLimitedValue() < NestedLoopCount) {
4443 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4444 diag::err_omp_wrong_ordered_loop_count)
4445 << OrderedLoopCountExpr->getSourceRange();
4446 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4447 diag::note_collapse_loop_count)
4448 << CollapseLoopCountExpr->getSourceRange();
4449 }
4450 NestedLoopCount = Result.getLimitedValue();
4451 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004452 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004453 // This is helper routine for loop directives (e.g., 'for', 'simd',
4454 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004455 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004456 SmallVector<LoopIterationSpace, 4> IterSpaces;
4457 IterSpaces.resize(NestedLoopCount);
4458 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004459 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004460 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004461 NestedLoopCount, CollapseLoopCountExpr,
4462 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004463 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004464 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004465 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004466 // OpenMP [2.8.1, simd construct, Restrictions]
4467 // All loops associated with the construct must be perfectly nested; that
4468 // is, there must be no intervening code nor any OpenMP directive between
4469 // any two loops.
4470 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004471 }
4472
Alexander Musmana5f070a2014-10-01 06:03:56 +00004473 Built.clear(/* size */ NestedLoopCount);
4474
4475 if (SemaRef.CurContext->isDependentContext())
4476 return NestedLoopCount;
4477
4478 // An example of what is generated for the following code:
4479 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004480 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004481 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004482 // for (k = 0; k < NK; ++k)
4483 // for (j = J0; j < NJ; j+=2) {
4484 // <loop body>
4485 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004486 //
4487 // We generate the code below.
4488 // Note: the loop body may be outlined in CodeGen.
4489 // Note: some counters may be C++ classes, operator- is used to find number of
4490 // iterations and operator+= to calculate counter value.
4491 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4492 // or i64 is currently supported).
4493 //
4494 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4495 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4496 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4497 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4498 // // similar updates for vars in clauses (e.g. 'linear')
4499 // <loop body (using local i and j)>
4500 // }
4501 // i = NI; // assign final values of counters
4502 // j = NJ;
4503 //
4504
4505 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4506 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004507 // Precondition tests if there is at least one iteration (all conditions are
4508 // true).
4509 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004510 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004511 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004512 32 /* Bits */, SemaRef
4513 .PerformImplicitConversion(
4514 N0->IgnoreImpCasts(), N0->getType(),
4515 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004516 .get(),
4517 SemaRef);
4518 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004519 64 /* Bits */, SemaRef
4520 .PerformImplicitConversion(
4521 N0->IgnoreImpCasts(), N0->getType(),
4522 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004523 .get(),
4524 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004525
4526 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4527 return NestedLoopCount;
4528
4529 auto &C = SemaRef.Context;
4530 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4531
4532 Scope *CurScope = DSA.getCurScope();
4533 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004534 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004535 PreCond =
4536 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4537 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004538 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004539 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004540 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004541 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4542 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004543 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004544 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004545 SemaRef
4546 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4547 Sema::AA_Converting,
4548 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004549 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004550 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004551 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004552 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004553 SemaRef
4554 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4555 Sema::AA_Converting,
4556 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004557 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004558 }
4559
4560 // Choose either the 32-bit or 64-bit version.
4561 ExprResult LastIteration = LastIteration64;
4562 if (LastIteration32.isUsable() &&
4563 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4564 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4565 FitsInto(
4566 32 /* Bits */,
4567 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4568 LastIteration64.get(), SemaRef)))
4569 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004570 QualType VType = LastIteration.get()->getType();
4571 QualType RealVType = VType;
4572 QualType StrideVType = VType;
4573 if (isOpenMPTaskLoopDirective(DKind)) {
4574 VType =
4575 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4576 StrideVType =
4577 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4578 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004579
4580 if (!LastIteration.isUsable())
4581 return 0;
4582
4583 // Save the number of iterations.
4584 ExprResult NumIterations = LastIteration;
4585 {
4586 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004587 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4588 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004589 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4590 if (!LastIteration.isUsable())
4591 return 0;
4592 }
4593
4594 // Calculate the last iteration number beforehand instead of doing this on
4595 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4596 llvm::APSInt Result;
4597 bool IsConstant =
4598 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4599 ExprResult CalcLastIteration;
4600 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004601 ExprResult SaveRef =
4602 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004603 LastIteration = SaveRef;
4604
4605 // Prepare SaveRef + 1.
4606 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004607 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004608 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4609 if (!NumIterations.isUsable())
4610 return 0;
4611 }
4612
4613 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4614
David Majnemer9d168222016-08-05 17:44:54 +00004615 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004616 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004617 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4618 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004619 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004620 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4621 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004622 SemaRef.AddInitializerToDecl(LBDecl,
4623 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4624 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004625
4626 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004627 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4628 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004629 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004630 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004631
4632 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4633 // This will be used to implement clause 'lastprivate'.
4634 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004635 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4636 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004637 SemaRef.AddInitializerToDecl(ILDecl,
4638 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4639 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004640
4641 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004642 VarDecl *STDecl =
4643 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4644 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004645 SemaRef.AddInitializerToDecl(STDecl,
4646 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4647 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004648
4649 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004650 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004651 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4652 UB.get(), LastIteration.get());
4653 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4654 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4655 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4656 CondOp.get());
4657 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004658
4659 // If we have a combined directive that combines 'distribute', 'for' or
4660 // 'simd' we need to be able to access the bounds of the schedule of the
4661 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4662 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4663 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004664
Carlo Bertolliffafe102017-04-20 00:39:39 +00004665 // Lower bound variable, initialized with zero.
4666 VarDecl *CombLBDecl =
4667 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4668 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4669 SemaRef.AddInitializerToDecl(
4670 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4671 /*DirectInit*/ false);
4672
4673 // Upper bound variable, initialized with last iteration number.
4674 VarDecl *CombUBDecl =
4675 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4676 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4677 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4678 /*DirectInit*/ false);
4679
4680 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4681 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4682 ExprResult CombCondOp =
4683 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4684 LastIteration.get(), CombUB.get());
4685 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4686 CombCondOp.get());
4687 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4688
4689 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004690 // We expect to have at least 2 more parameters than the 'parallel'
4691 // directive does - the lower and upper bounds of the previous schedule.
4692 assert(CD->getNumParams() >= 4 &&
4693 "Unexpected number of parameters in loop combined directive");
4694
4695 // Set the proper type for the bounds given what we learned from the
4696 // enclosed loops.
4697 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4698 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4699
4700 // Previous lower and upper bounds are obtained from the region
4701 // parameters.
4702 PrevLB =
4703 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4704 PrevUB =
4705 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4706 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004707 }
4708
4709 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004710 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004711 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004712 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004713 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4714 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004715 Expr *RHS =
4716 (isOpenMPWorksharingDirective(DKind) ||
4717 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4718 ? LB.get()
4719 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004720 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4721 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004722
4723 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4724 Expr *CombRHS =
4725 (isOpenMPWorksharingDirective(DKind) ||
4726 isOpenMPTaskLoopDirective(DKind) ||
4727 isOpenMPDistributeDirective(DKind))
4728 ? CombLB.get()
4729 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4730 CombInit =
4731 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4732 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4733 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004734 }
4735
Alexander Musmanc6388682014-12-15 07:07:06 +00004736 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004737 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004738 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004739 (isOpenMPWorksharingDirective(DKind) ||
4740 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004741 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4742 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4743 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004744 ExprResult CombCond;
4745 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4746 CombCond =
4747 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4748 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004749 // Loop increment (IV = IV + 1)
4750 SourceLocation IncLoc;
4751 ExprResult Inc =
4752 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4753 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4754 if (!Inc.isUsable())
4755 return 0;
4756 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004757 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4758 if (!Inc.isUsable())
4759 return 0;
4760
4761 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4762 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004763 // In combined construct, add combined version that use CombLB and CombUB
4764 // base variables for the update
4765 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004766 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4767 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004768 // LB + ST
4769 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4770 if (!NextLB.isUsable())
4771 return 0;
4772 // LB = LB + ST
4773 NextLB =
4774 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4775 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4776 if (!NextLB.isUsable())
4777 return 0;
4778 // UB + ST
4779 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4780 if (!NextUB.isUsable())
4781 return 0;
4782 // UB = UB + ST
4783 NextUB =
4784 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4785 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4786 if (!NextUB.isUsable())
4787 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004788 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4789 CombNextLB =
4790 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4791 if (!NextLB.isUsable())
4792 return 0;
4793 // LB = LB + ST
4794 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4795 CombNextLB.get());
4796 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4797 if (!CombNextLB.isUsable())
4798 return 0;
4799 // UB + ST
4800 CombNextUB =
4801 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4802 if (!CombNextUB.isUsable())
4803 return 0;
4804 // UB = UB + ST
4805 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4806 CombNextUB.get());
4807 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4808 if (!CombNextUB.isUsable())
4809 return 0;
4810 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004811 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004812
Carlo Bertolliffafe102017-04-20 00:39:39 +00004813 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004814 // directive with for as IV = IV + ST; ensure upper bound expression based
4815 // on PrevUB instead of NumIterations - used to implement 'for' when found
4816 // in combination with 'distribute', like in 'distribute parallel for'
4817 SourceLocation DistIncLoc;
4818 ExprResult DistCond, DistInc, PrevEUB;
4819 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4820 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4821 assert(DistCond.isUsable() && "distribute cond expr was not built");
4822
4823 DistInc =
4824 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4825 assert(DistInc.isUsable() && "distribute inc expr was not built");
4826 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4827 DistInc.get());
4828 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4829 assert(DistInc.isUsable() && "distribute inc expr was not built");
4830
4831 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4832 // construct
4833 SourceLocation DistEUBLoc;
4834 ExprResult IsUBGreater =
4835 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4836 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4837 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4838 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4839 CondOp.get());
4840 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4841 }
4842
Alexander Musmana5f070a2014-10-01 06:03:56 +00004843 // Build updates and final values of the loop counters.
4844 bool HasErrors = false;
4845 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004846 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004847 Built.Updates.resize(NestedLoopCount);
4848 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004849 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004850 {
4851 ExprResult Div;
4852 // Go from inner nested loop to outer.
4853 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4854 LoopIterationSpace &IS = IterSpaces[Cnt];
4855 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4856 // Build: Iter = (IV / Div) % IS.NumIters
4857 // where Div is product of previous iterations' IS.NumIters.
4858 ExprResult Iter;
4859 if (Div.isUsable()) {
4860 Iter =
4861 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4862 } else {
4863 Iter = IV;
4864 assert((Cnt == (int)NestedLoopCount - 1) &&
4865 "unusable div expected on first iteration only");
4866 }
4867
4868 if (Cnt != 0 && Iter.isUsable())
4869 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4870 IS.NumIterations);
4871 if (!Iter.isUsable()) {
4872 HasErrors = true;
4873 break;
4874 }
4875
Alexey Bataev39f915b82015-05-08 10:41:21 +00004876 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004877 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4878 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4879 IS.CounterVar->getExprLoc(),
4880 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004881 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004882 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004883 if (!Init.isUsable()) {
4884 HasErrors = true;
4885 break;
4886 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004887 ExprResult Update = BuildCounterUpdate(
4888 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4889 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004890 if (!Update.isUsable()) {
4891 HasErrors = true;
4892 break;
4893 }
4894
4895 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4896 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004897 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004898 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004899 if (!Final.isUsable()) {
4900 HasErrors = true;
4901 break;
4902 }
4903
4904 // Build Div for the next iteration: Div <- Div * IS.NumIters
4905 if (Cnt != 0) {
4906 if (Div.isUnset())
4907 Div = IS.NumIterations;
4908 else
4909 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4910 IS.NumIterations);
4911
4912 // Add parentheses (for debugging purposes only).
4913 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004914 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004915 if (!Div.isUsable()) {
4916 HasErrors = true;
4917 break;
4918 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004919 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004920 }
4921 if (!Update.isUsable() || !Final.isUsable()) {
4922 HasErrors = true;
4923 break;
4924 }
4925 // Save results
4926 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004927 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004928 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004929 Built.Updates[Cnt] = Update.get();
4930 Built.Finals[Cnt] = Final.get();
4931 }
4932 }
4933
4934 if (HasErrors)
4935 return 0;
4936
4937 // Save results
4938 Built.IterationVarRef = IV.get();
4939 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004940 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004941 Built.CalcLastIteration =
4942 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004943 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004944 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004945 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004946 Built.Init = Init.get();
4947 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004948 Built.LB = LB.get();
4949 Built.UB = UB.get();
4950 Built.IL = IL.get();
4951 Built.ST = ST.get();
4952 Built.EUB = EUB.get();
4953 Built.NLB = NextLB.get();
4954 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004955 Built.PrevLB = PrevLB.get();
4956 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004957 Built.DistInc = DistInc.get();
4958 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004959 Built.DistCombinedFields.LB = CombLB.get();
4960 Built.DistCombinedFields.UB = CombUB.get();
4961 Built.DistCombinedFields.EUB = CombEUB.get();
4962 Built.DistCombinedFields.Init = CombInit.get();
4963 Built.DistCombinedFields.Cond = CombCond.get();
4964 Built.DistCombinedFields.NLB = CombNextLB.get();
4965 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004966
Alexey Bataev8b427062016-05-25 12:36:08 +00004967 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4968 // Fill data for doacross depend clauses.
4969 for (auto Pair : DSA.getDoacrossDependClauses()) {
4970 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4971 Pair.first->setCounterValue(CounterVal);
4972 else {
4973 if (NestedLoopCount != Pair.second.size() ||
4974 NestedLoopCount != LoopMultipliers.size() + 1) {
4975 // Erroneous case - clause has some problems.
4976 Pair.first->setCounterValue(CounterVal);
4977 continue;
4978 }
4979 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4980 auto I = Pair.second.rbegin();
4981 auto IS = IterSpaces.rbegin();
4982 auto ILM = LoopMultipliers.rbegin();
4983 Expr *UpCounterVal = CounterVal;
4984 Expr *Multiplier = nullptr;
4985 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4986 if (I->first) {
4987 assert(IS->CounterStep);
4988 Expr *NormalizedOffset =
4989 SemaRef
4990 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4991 I->first, IS->CounterStep)
4992 .get();
4993 if (Multiplier) {
4994 NormalizedOffset =
4995 SemaRef
4996 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4997 NormalizedOffset, Multiplier)
4998 .get();
4999 }
5000 assert(I->second == OO_Plus || I->second == OO_Minus);
5001 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00005002 UpCounterVal = SemaRef
5003 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
5004 UpCounterVal, NormalizedOffset)
5005 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00005006 }
5007 Multiplier = *ILM;
5008 ++I;
5009 ++IS;
5010 ++ILM;
5011 }
5012 Pair.first->setCounterValue(UpCounterVal);
5013 }
5014 }
5015
Alexey Bataevabfc0692014-06-25 06:52:00 +00005016 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005017}
5018
Alexey Bataev10e775f2015-07-30 11:36:16 +00005019static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005020 auto CollapseClauses =
5021 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5022 if (CollapseClauses.begin() != CollapseClauses.end())
5023 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005024 return nullptr;
5025}
5026
Alexey Bataev10e775f2015-07-30 11:36:16 +00005027static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005028 auto OrderedClauses =
5029 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5030 if (OrderedClauses.begin() != OrderedClauses.end())
5031 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005032 return nullptr;
5033}
5034
Kelvin Lic5609492016-07-15 04:39:07 +00005035static bool checkSimdlenSafelenSpecified(Sema &S,
5036 const ArrayRef<OMPClause *> Clauses) {
5037 OMPSafelenClause *Safelen = nullptr;
5038 OMPSimdlenClause *Simdlen = nullptr;
5039
5040 for (auto *Clause : Clauses) {
5041 if (Clause->getClauseKind() == OMPC_safelen)
5042 Safelen = cast<OMPSafelenClause>(Clause);
5043 else if (Clause->getClauseKind() == OMPC_simdlen)
5044 Simdlen = cast<OMPSimdlenClause>(Clause);
5045 if (Safelen && Simdlen)
5046 break;
5047 }
5048
5049 if (Simdlen && Safelen) {
5050 llvm::APSInt SimdlenRes, SafelenRes;
5051 auto SimdlenLength = Simdlen->getSimdlen();
5052 auto SafelenLength = Safelen->getSafelen();
5053 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5054 SimdlenLength->isInstantiationDependent() ||
5055 SimdlenLength->containsUnexpandedParameterPack())
5056 return false;
5057 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5058 SafelenLength->isInstantiationDependent() ||
5059 SafelenLength->containsUnexpandedParameterPack())
5060 return false;
5061 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5062 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5063 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5064 // If both simdlen and safelen clauses are specified, the value of the
5065 // simdlen parameter must be less than or equal to the value of the safelen
5066 // parameter.
5067 if (SimdlenRes > SafelenRes) {
5068 S.Diag(SimdlenLength->getExprLoc(),
5069 diag::err_omp_wrong_simdlen_safelen_values)
5070 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5071 return true;
5072 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005073 }
5074 return false;
5075}
5076
Alexey Bataev4acb8592014-07-07 13:01:15 +00005077StmtResult Sema::ActOnOpenMPSimdDirective(
5078 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5079 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005080 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005081 if (!AStmt)
5082 return StmtError();
5083
5084 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005085 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005086 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5087 // define the nested loops number.
5088 unsigned NestedLoopCount = CheckOpenMPLoop(
5089 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5090 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005091 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005092 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005093
Alexander Musmana5f070a2014-10-01 06:03:56 +00005094 assert((CurContext->isDependentContext() || B.builtAll()) &&
5095 "omp simd loop exprs were not built");
5096
Alexander Musman3276a272015-03-21 10:12:56 +00005097 if (!CurContext->isDependentContext()) {
5098 // Finalize the clauses that need pre-built expressions for CodeGen.
5099 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005100 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005101 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005102 B.NumIterations, *this, CurScope,
5103 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005104 return StmtError();
5105 }
5106 }
5107
Kelvin Lic5609492016-07-15 04:39:07 +00005108 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005109 return StmtError();
5110
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005111 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005112 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5113 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005114}
5115
Alexey Bataev4acb8592014-07-07 13:01:15 +00005116StmtResult Sema::ActOnOpenMPForDirective(
5117 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5118 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005119 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005120 if (!AStmt)
5121 return StmtError();
5122
5123 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005124 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005125 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5126 // define the nested loops number.
5127 unsigned NestedLoopCount = CheckOpenMPLoop(
5128 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5129 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005130 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005131 return StmtError();
5132
Alexander Musmana5f070a2014-10-01 06:03:56 +00005133 assert((CurContext->isDependentContext() || B.builtAll()) &&
5134 "omp for loop exprs were not built");
5135
Alexey Bataev54acd402015-08-04 11:18:19 +00005136 if (!CurContext->isDependentContext()) {
5137 // Finalize the clauses that need pre-built expressions for CodeGen.
5138 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005139 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005140 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005141 B.NumIterations, *this, CurScope,
5142 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005143 return StmtError();
5144 }
5145 }
5146
Alexey Bataevf29276e2014-06-18 04:14:57 +00005147 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005148 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005149 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005150}
5151
Alexander Musmanf82886e2014-09-18 05:12:34 +00005152StmtResult Sema::ActOnOpenMPForSimdDirective(
5153 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5154 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005155 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005156 if (!AStmt)
5157 return StmtError();
5158
5159 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005160 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005161 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5162 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005163 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005164 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5165 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5166 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005167 if (NestedLoopCount == 0)
5168 return StmtError();
5169
Alexander Musmanc6388682014-12-15 07:07:06 +00005170 assert((CurContext->isDependentContext() || B.builtAll()) &&
5171 "omp for simd loop exprs were not built");
5172
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005173 if (!CurContext->isDependentContext()) {
5174 // Finalize the clauses that need pre-built expressions for CodeGen.
5175 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005176 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005177 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005178 B.NumIterations, *this, CurScope,
5179 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005180 return StmtError();
5181 }
5182 }
5183
Kelvin Lic5609492016-07-15 04:39:07 +00005184 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005185 return StmtError();
5186
Alexander Musmanf82886e2014-09-18 05:12:34 +00005187 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005188 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5189 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005190}
5191
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005192StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5193 Stmt *AStmt,
5194 SourceLocation StartLoc,
5195 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005196 if (!AStmt)
5197 return StmtError();
5198
5199 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005200 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005201 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005202 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005203 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005204 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005205 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005206 return StmtError();
5207 // All associated statements must be '#pragma omp section' except for
5208 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005209 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005210 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5211 if (SectionStmt)
5212 Diag(SectionStmt->getLocStart(),
5213 diag::err_omp_sections_substmt_not_section);
5214 return StmtError();
5215 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005216 cast<OMPSectionDirective>(SectionStmt)
5217 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005218 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005219 } else {
5220 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5221 return StmtError();
5222 }
5223
5224 getCurFunction()->setHasBranchProtectedScope();
5225
Alexey Bataev25e5b442015-09-15 12:52:43 +00005226 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5227 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005228}
5229
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005230StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5231 SourceLocation StartLoc,
5232 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005233 if (!AStmt)
5234 return StmtError();
5235
5236 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005237
5238 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005239 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005240
Alexey Bataev25e5b442015-09-15 12:52:43 +00005241 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5242 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005243}
5244
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005245StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5246 Stmt *AStmt,
5247 SourceLocation StartLoc,
5248 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005249 if (!AStmt)
5250 return StmtError();
5251
5252 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005253
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005254 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005255
Alexey Bataev3255bf32015-01-19 05:20:46 +00005256 // OpenMP [2.7.3, single Construct, Restrictions]
5257 // The copyprivate clause must not be used with the nowait clause.
5258 OMPClause *Nowait = nullptr;
5259 OMPClause *Copyprivate = nullptr;
5260 for (auto *Clause : Clauses) {
5261 if (Clause->getClauseKind() == OMPC_nowait)
5262 Nowait = Clause;
5263 else if (Clause->getClauseKind() == OMPC_copyprivate)
5264 Copyprivate = Clause;
5265 if (Copyprivate && Nowait) {
5266 Diag(Copyprivate->getLocStart(),
5267 diag::err_omp_single_copyprivate_with_nowait);
5268 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5269 return StmtError();
5270 }
5271 }
5272
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005273 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5274}
5275
Alexander Musman80c22892014-07-17 08:54:58 +00005276StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5277 SourceLocation StartLoc,
5278 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005279 if (!AStmt)
5280 return StmtError();
5281
5282 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005283
5284 getCurFunction()->setHasBranchProtectedScope();
5285
5286 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5287}
5288
Alexey Bataev28c75412015-12-15 08:19:24 +00005289StmtResult Sema::ActOnOpenMPCriticalDirective(
5290 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5291 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005292 if (!AStmt)
5293 return StmtError();
5294
5295 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005296
Alexey Bataev28c75412015-12-15 08:19:24 +00005297 bool ErrorFound = false;
5298 llvm::APSInt Hint;
5299 SourceLocation HintLoc;
5300 bool DependentHint = false;
5301 for (auto *C : Clauses) {
5302 if (C->getClauseKind() == OMPC_hint) {
5303 if (!DirName.getName()) {
5304 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5305 ErrorFound = true;
5306 }
5307 Expr *E = cast<OMPHintClause>(C)->getHint();
5308 if (E->isTypeDependent() || E->isValueDependent() ||
5309 E->isInstantiationDependent())
5310 DependentHint = true;
5311 else {
5312 Hint = E->EvaluateKnownConstInt(Context);
5313 HintLoc = C->getLocStart();
5314 }
5315 }
5316 }
5317 if (ErrorFound)
5318 return StmtError();
5319 auto Pair = DSAStack->getCriticalWithHint(DirName);
5320 if (Pair.first && DirName.getName() && !DependentHint) {
5321 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5322 Diag(StartLoc, diag::err_omp_critical_with_hint);
5323 if (HintLoc.isValid()) {
5324 Diag(HintLoc, diag::note_omp_critical_hint_here)
5325 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5326 } else
5327 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5328 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5329 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5330 << 1
5331 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5332 /*Radix=*/10, /*Signed=*/false);
5333 } else
5334 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5335 }
5336 }
5337
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005338 getCurFunction()->setHasBranchProtectedScope();
5339
Alexey Bataev28c75412015-12-15 08:19:24 +00005340 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5341 Clauses, AStmt);
5342 if (!Pair.first && DirName.getName() && !DependentHint)
5343 DSAStack->addCriticalWithHint(Dir, Hint);
5344 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005345}
5346
Alexey Bataev4acb8592014-07-07 13:01:15 +00005347StmtResult Sema::ActOnOpenMPParallelForDirective(
5348 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5349 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005350 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005351 if (!AStmt)
5352 return StmtError();
5353
Alexey Bataev4acb8592014-07-07 13:01:15 +00005354 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5355 // 1.2.2 OpenMP Language Terminology
5356 // Structured block - An executable statement with a single entry at the
5357 // top and a single exit at the bottom.
5358 // The point of exit cannot be a branch out of the structured block.
5359 // longjmp() and throw() must not violate the entry/exit criteria.
5360 CS->getCapturedDecl()->setNothrow();
5361
Alexander Musmanc6388682014-12-15 07:07:06 +00005362 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005363 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5364 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005365 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005366 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5367 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5368 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005369 if (NestedLoopCount == 0)
5370 return StmtError();
5371
Alexander Musmana5f070a2014-10-01 06:03:56 +00005372 assert((CurContext->isDependentContext() || B.builtAll()) &&
5373 "omp parallel for loop exprs were not built");
5374
Alexey Bataev54acd402015-08-04 11:18:19 +00005375 if (!CurContext->isDependentContext()) {
5376 // Finalize the clauses that need pre-built expressions for CodeGen.
5377 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005378 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005379 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005380 B.NumIterations, *this, CurScope,
5381 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005382 return StmtError();
5383 }
5384 }
5385
Alexey Bataev4acb8592014-07-07 13:01:15 +00005386 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005387 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005388 NestedLoopCount, Clauses, AStmt, B,
5389 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005390}
5391
Alexander Musmane4e893b2014-09-23 09:33:00 +00005392StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5393 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5394 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005395 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005396 if (!AStmt)
5397 return StmtError();
5398
Alexander Musmane4e893b2014-09-23 09:33:00 +00005399 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5400 // 1.2.2 OpenMP Language Terminology
5401 // Structured block - An executable statement with a single entry at the
5402 // top and a single exit at the bottom.
5403 // The point of exit cannot be a branch out of the structured block.
5404 // longjmp() and throw() must not violate the entry/exit criteria.
5405 CS->getCapturedDecl()->setNothrow();
5406
Alexander Musmanc6388682014-12-15 07:07:06 +00005407 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005408 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5409 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005410 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005411 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5412 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5413 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005414 if (NestedLoopCount == 0)
5415 return StmtError();
5416
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005417 if (!CurContext->isDependentContext()) {
5418 // Finalize the clauses that need pre-built expressions for CodeGen.
5419 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005420 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005421 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005422 B.NumIterations, *this, CurScope,
5423 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005424 return StmtError();
5425 }
5426 }
5427
Kelvin Lic5609492016-07-15 04:39:07 +00005428 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005429 return StmtError();
5430
Alexander Musmane4e893b2014-09-23 09:33:00 +00005431 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005432 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005433 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005434}
5435
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005436StmtResult
5437Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5438 Stmt *AStmt, SourceLocation StartLoc,
5439 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005440 if (!AStmt)
5441 return StmtError();
5442
5443 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005444 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005445 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005446 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005447 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005448 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005449 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005450 return StmtError();
5451 // All associated statements must be '#pragma omp section' except for
5452 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005453 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005454 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5455 if (SectionStmt)
5456 Diag(SectionStmt->getLocStart(),
5457 diag::err_omp_parallel_sections_substmt_not_section);
5458 return StmtError();
5459 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005460 cast<OMPSectionDirective>(SectionStmt)
5461 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005462 }
5463 } else {
5464 Diag(AStmt->getLocStart(),
5465 diag::err_omp_parallel_sections_not_compound_stmt);
5466 return StmtError();
5467 }
5468
5469 getCurFunction()->setHasBranchProtectedScope();
5470
Alexey Bataev25e5b442015-09-15 12:52:43 +00005471 return OMPParallelSectionsDirective::Create(
5472 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005473}
5474
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005475StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5476 Stmt *AStmt, SourceLocation StartLoc,
5477 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005478 if (!AStmt)
5479 return StmtError();
5480
David Majnemer9d168222016-08-05 17:44:54 +00005481 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005482 // 1.2.2 OpenMP Language Terminology
5483 // Structured block - An executable statement with a single entry at the
5484 // top and a single exit at the bottom.
5485 // The point of exit cannot be a branch out of the structured block.
5486 // longjmp() and throw() must not violate the entry/exit criteria.
5487 CS->getCapturedDecl()->setNothrow();
5488
5489 getCurFunction()->setHasBranchProtectedScope();
5490
Alexey Bataev25e5b442015-09-15 12:52:43 +00005491 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5492 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005493}
5494
Alexey Bataev68446b72014-07-18 07:47:19 +00005495StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5496 SourceLocation EndLoc) {
5497 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5498}
5499
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005500StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5501 SourceLocation EndLoc) {
5502 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5503}
5504
Alexey Bataev2df347a2014-07-18 10:17:07 +00005505StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5506 SourceLocation EndLoc) {
5507 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5508}
5509
Alexey Bataev169d96a2017-07-18 20:17:46 +00005510StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5511 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005512 SourceLocation StartLoc,
5513 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005514 if (!AStmt)
5515 return StmtError();
5516
5517 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005518
5519 getCurFunction()->setHasBranchProtectedScope();
5520
Alexey Bataev169d96a2017-07-18 20:17:46 +00005521 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00005522 AStmt,
5523 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005524}
5525
Alexey Bataev6125da92014-07-21 11:26:11 +00005526StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5527 SourceLocation StartLoc,
5528 SourceLocation EndLoc) {
5529 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5530 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5531}
5532
Alexey Bataev346265e2015-09-25 10:37:12 +00005533StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5534 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005535 SourceLocation StartLoc,
5536 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005537 OMPClause *DependFound = nullptr;
5538 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005539 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005540 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005541 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005542 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005543 for (auto *C : Clauses) {
5544 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5545 DependFound = C;
5546 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5547 if (DependSourceClause) {
5548 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5549 << getOpenMPDirectiveName(OMPD_ordered)
5550 << getOpenMPClauseName(OMPC_depend) << 2;
5551 ErrorFound = true;
5552 } else
5553 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005554 if (DependSinkClause) {
5555 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5556 << 0;
5557 ErrorFound = true;
5558 }
5559 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5560 if (DependSourceClause) {
5561 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5562 << 1;
5563 ErrorFound = true;
5564 }
5565 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005566 }
5567 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005568 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005569 else if (C->getClauseKind() == OMPC_simd)
5570 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005571 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005572 if (!ErrorFound && !SC &&
5573 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005574 // OpenMP [2.8.1,simd Construct, Restrictions]
5575 // An ordered construct with the simd clause is the only OpenMP construct
5576 // that can appear in the simd region.
5577 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005578 ErrorFound = true;
5579 } else if (DependFound && (TC || SC)) {
5580 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5581 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5582 ErrorFound = true;
5583 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5584 Diag(DependFound->getLocStart(),
5585 diag::err_omp_ordered_directive_without_param);
5586 ErrorFound = true;
5587 } else if (TC || Clauses.empty()) {
5588 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5589 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5590 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5591 << (TC != nullptr);
5592 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5593 ErrorFound = true;
5594 }
5595 }
5596 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005597 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005598
5599 if (AStmt) {
5600 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5601
5602 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005603 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005604
5605 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005606}
5607
Alexey Bataev1d160b12015-03-13 12:27:31 +00005608namespace {
5609/// \brief Helper class for checking expression in 'omp atomic [update]'
5610/// construct.
5611class OpenMPAtomicUpdateChecker {
5612 /// \brief Error results for atomic update expressions.
5613 enum ExprAnalysisErrorCode {
5614 /// \brief A statement is not an expression statement.
5615 NotAnExpression,
5616 /// \brief Expression is not builtin binary or unary operation.
5617 NotABinaryOrUnaryExpression,
5618 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5619 NotAnUnaryIncDecExpression,
5620 /// \brief An expression is not of scalar type.
5621 NotAScalarType,
5622 /// \brief A binary operation is not an assignment operation.
5623 NotAnAssignmentOp,
5624 /// \brief RHS part of the binary operation is not a binary expression.
5625 NotABinaryExpression,
5626 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5627 /// expression.
5628 NotABinaryOperator,
5629 /// \brief RHS binary operation does not have reference to the updated LHS
5630 /// part.
5631 NotAnUpdateExpression,
5632 /// \brief No errors is found.
5633 NoError
5634 };
5635 /// \brief Reference to Sema.
5636 Sema &SemaRef;
5637 /// \brief A location for note diagnostics (when error is found).
5638 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005639 /// \brief 'x' lvalue part of the source atomic expression.
5640 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005641 /// \brief 'expr' rvalue part of the source atomic expression.
5642 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005643 /// \brief Helper expression of the form
5644 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5645 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5646 Expr *UpdateExpr;
5647 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5648 /// important for non-associative operations.
5649 bool IsXLHSInRHSPart;
5650 BinaryOperatorKind Op;
5651 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005652 /// \brief true if the source expression is a postfix unary operation, false
5653 /// if it is a prefix unary operation.
5654 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005655
5656public:
5657 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005658 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005659 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005660 /// \brief Check specified statement that it is suitable for 'atomic update'
5661 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005662 /// expression. If DiagId and NoteId == 0, then only check is performed
5663 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005664 /// \param DiagId Diagnostic which should be emitted if error is found.
5665 /// \param NoteId Diagnostic note for the main error message.
5666 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005667 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005668 /// \brief Return the 'x' lvalue part of the source atomic expression.
5669 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005670 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5671 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005672 /// \brief Return the update expression used in calculation of the updated
5673 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5674 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5675 Expr *getUpdateExpr() const { return UpdateExpr; }
5676 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5677 /// false otherwise.
5678 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5679
Alexey Bataevb78ca832015-04-01 03:33:17 +00005680 /// \brief true if the source expression is a postfix unary operation, false
5681 /// if it is a prefix unary operation.
5682 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5683
Alexey Bataev1d160b12015-03-13 12:27:31 +00005684private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005685 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5686 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005687};
5688} // namespace
5689
5690bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5691 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5692 ExprAnalysisErrorCode ErrorFound = NoError;
5693 SourceLocation ErrorLoc, NoteLoc;
5694 SourceRange ErrorRange, NoteRange;
5695 // Allowed constructs are:
5696 // x = x binop expr;
5697 // x = expr binop x;
5698 if (AtomicBinOp->getOpcode() == BO_Assign) {
5699 X = AtomicBinOp->getLHS();
5700 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5701 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5702 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5703 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5704 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005705 Op = AtomicInnerBinOp->getOpcode();
5706 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005707 auto *LHS = AtomicInnerBinOp->getLHS();
5708 auto *RHS = AtomicInnerBinOp->getRHS();
5709 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5710 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5711 /*Canonical=*/true);
5712 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5713 /*Canonical=*/true);
5714 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5715 /*Canonical=*/true);
5716 if (XId == LHSId) {
5717 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005718 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005719 } else if (XId == RHSId) {
5720 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005721 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005722 } else {
5723 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5724 ErrorRange = AtomicInnerBinOp->getSourceRange();
5725 NoteLoc = X->getExprLoc();
5726 NoteRange = X->getSourceRange();
5727 ErrorFound = NotAnUpdateExpression;
5728 }
5729 } else {
5730 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5731 ErrorRange = AtomicInnerBinOp->getSourceRange();
5732 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5733 NoteRange = SourceRange(NoteLoc, NoteLoc);
5734 ErrorFound = NotABinaryOperator;
5735 }
5736 } else {
5737 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5738 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5739 ErrorFound = NotABinaryExpression;
5740 }
5741 } else {
5742 ErrorLoc = AtomicBinOp->getExprLoc();
5743 ErrorRange = AtomicBinOp->getSourceRange();
5744 NoteLoc = AtomicBinOp->getOperatorLoc();
5745 NoteRange = SourceRange(NoteLoc, NoteLoc);
5746 ErrorFound = NotAnAssignmentOp;
5747 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005748 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005749 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5750 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5751 return true;
5752 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005753 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005754 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005755}
5756
5757bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5758 unsigned NoteId) {
5759 ExprAnalysisErrorCode ErrorFound = NoError;
5760 SourceLocation ErrorLoc, NoteLoc;
5761 SourceRange ErrorRange, NoteRange;
5762 // Allowed constructs are:
5763 // x++;
5764 // x--;
5765 // ++x;
5766 // --x;
5767 // x binop= expr;
5768 // x = x binop expr;
5769 // x = expr binop x;
5770 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5771 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5772 if (AtomicBody->getType()->isScalarType() ||
5773 AtomicBody->isInstantiationDependent()) {
5774 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5775 AtomicBody->IgnoreParenImpCasts())) {
5776 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005777 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005778 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005779 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005780 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005781 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005782 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005783 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5784 AtomicBody->IgnoreParenImpCasts())) {
5785 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005786 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005787 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005788 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5789 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005790 // Check for Unary Operation
5791 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005792 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005793 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5794 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005795 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005796 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5797 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005798 } else {
5799 ErrorFound = NotAnUnaryIncDecExpression;
5800 ErrorLoc = AtomicUnaryOp->getExprLoc();
5801 ErrorRange = AtomicUnaryOp->getSourceRange();
5802 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5803 NoteRange = SourceRange(NoteLoc, NoteLoc);
5804 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005805 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005806 ErrorFound = NotABinaryOrUnaryExpression;
5807 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5808 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5809 }
5810 } else {
5811 ErrorFound = NotAScalarType;
5812 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5813 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5814 }
5815 } else {
5816 ErrorFound = NotAnExpression;
5817 NoteLoc = ErrorLoc = S->getLocStart();
5818 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5819 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005820 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005821 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5822 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5823 return true;
5824 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005825 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005826 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005827 // Build an update expression of form 'OpaqueValueExpr(x) binop
5828 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5829 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5830 auto *OVEX = new (SemaRef.getASTContext())
5831 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5832 auto *OVEExpr = new (SemaRef.getASTContext())
5833 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5834 auto Update =
5835 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5836 IsXLHSInRHSPart ? OVEExpr : OVEX);
5837 if (Update.isInvalid())
5838 return true;
5839 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5840 Sema::AA_Casting);
5841 if (Update.isInvalid())
5842 return true;
5843 UpdateExpr = Update.get();
5844 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005845 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005846}
5847
Alexey Bataev0162e452014-07-22 10:10:35 +00005848StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5849 Stmt *AStmt,
5850 SourceLocation StartLoc,
5851 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005852 if (!AStmt)
5853 return StmtError();
5854
David Majnemer9d168222016-08-05 17:44:54 +00005855 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005856 // 1.2.2 OpenMP Language Terminology
5857 // Structured block - An executable statement with a single entry at the
5858 // top and a single exit at the bottom.
5859 // The point of exit cannot be a branch out of the structured block.
5860 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005861 OpenMPClauseKind AtomicKind = OMPC_unknown;
5862 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005863 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005864 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005865 C->getClauseKind() == OMPC_update ||
5866 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005867 if (AtomicKind != OMPC_unknown) {
5868 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5869 << SourceRange(C->getLocStart(), C->getLocEnd());
5870 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5871 << getOpenMPClauseName(AtomicKind);
5872 } else {
5873 AtomicKind = C->getClauseKind();
5874 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005875 }
5876 }
5877 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005878
Alexey Bataev459dec02014-07-24 06:46:57 +00005879 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005880 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5881 Body = EWC->getSubExpr();
5882
Alexey Bataev62cec442014-11-18 10:14:22 +00005883 Expr *X = nullptr;
5884 Expr *V = nullptr;
5885 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005886 Expr *UE = nullptr;
5887 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005888 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005889 // OpenMP [2.12.6, atomic Construct]
5890 // In the next expressions:
5891 // * x and v (as applicable) are both l-value expressions with scalar type.
5892 // * During the execution of an atomic region, multiple syntactic
5893 // occurrences of x must designate the same storage location.
5894 // * Neither of v and expr (as applicable) may access the storage location
5895 // designated by x.
5896 // * Neither of x and expr (as applicable) may access the storage location
5897 // designated by v.
5898 // * expr is an expression with scalar type.
5899 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5900 // * binop, binop=, ++, and -- are not overloaded operators.
5901 // * The expression x binop expr must be numerically equivalent to x binop
5902 // (expr). This requirement is satisfied if the operators in expr have
5903 // precedence greater than binop, or by using parentheses around expr or
5904 // subexpressions of expr.
5905 // * The expression expr binop x must be numerically equivalent to (expr)
5906 // binop x. This requirement is satisfied if the operators in expr have
5907 // precedence equal to or greater than binop, or by using parentheses around
5908 // expr or subexpressions of expr.
5909 // * For forms that allow multiple occurrences of x, the number of times
5910 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005911 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005912 enum {
5913 NotAnExpression,
5914 NotAnAssignmentOp,
5915 NotAScalarType,
5916 NotAnLValue,
5917 NoError
5918 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005919 SourceLocation ErrorLoc, NoteLoc;
5920 SourceRange ErrorRange, NoteRange;
5921 // If clause is read:
5922 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005923 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5924 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005925 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5926 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5927 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5928 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5929 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5930 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5931 if (!X->isLValue() || !V->isLValue()) {
5932 auto NotLValueExpr = X->isLValue() ? V : X;
5933 ErrorFound = NotAnLValue;
5934 ErrorLoc = AtomicBinOp->getExprLoc();
5935 ErrorRange = AtomicBinOp->getSourceRange();
5936 NoteLoc = NotLValueExpr->getExprLoc();
5937 NoteRange = NotLValueExpr->getSourceRange();
5938 }
5939 } else if (!X->isInstantiationDependent() ||
5940 !V->isInstantiationDependent()) {
5941 auto NotScalarExpr =
5942 (X->isInstantiationDependent() || X->getType()->isScalarType())
5943 ? V
5944 : X;
5945 ErrorFound = NotAScalarType;
5946 ErrorLoc = AtomicBinOp->getExprLoc();
5947 ErrorRange = AtomicBinOp->getSourceRange();
5948 NoteLoc = NotScalarExpr->getExprLoc();
5949 NoteRange = NotScalarExpr->getSourceRange();
5950 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005951 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005952 ErrorFound = NotAnAssignmentOp;
5953 ErrorLoc = AtomicBody->getExprLoc();
5954 ErrorRange = AtomicBody->getSourceRange();
5955 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5956 : AtomicBody->getExprLoc();
5957 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5958 : AtomicBody->getSourceRange();
5959 }
5960 } else {
5961 ErrorFound = NotAnExpression;
5962 NoteLoc = ErrorLoc = Body->getLocStart();
5963 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005964 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005965 if (ErrorFound != NoError) {
5966 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5967 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005968 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5969 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005970 return StmtError();
5971 } else if (CurContext->isDependentContext())
5972 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005973 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005974 enum {
5975 NotAnExpression,
5976 NotAnAssignmentOp,
5977 NotAScalarType,
5978 NotAnLValue,
5979 NoError
5980 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005981 SourceLocation ErrorLoc, NoteLoc;
5982 SourceRange ErrorRange, NoteRange;
5983 // If clause is write:
5984 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005985 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5986 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005987 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5988 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005989 X = AtomicBinOp->getLHS();
5990 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005991 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5992 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5993 if (!X->isLValue()) {
5994 ErrorFound = NotAnLValue;
5995 ErrorLoc = AtomicBinOp->getExprLoc();
5996 ErrorRange = AtomicBinOp->getSourceRange();
5997 NoteLoc = X->getExprLoc();
5998 NoteRange = X->getSourceRange();
5999 }
6000 } else if (!X->isInstantiationDependent() ||
6001 !E->isInstantiationDependent()) {
6002 auto NotScalarExpr =
6003 (X->isInstantiationDependent() || X->getType()->isScalarType())
6004 ? E
6005 : X;
6006 ErrorFound = NotAScalarType;
6007 ErrorLoc = AtomicBinOp->getExprLoc();
6008 ErrorRange = AtomicBinOp->getSourceRange();
6009 NoteLoc = NotScalarExpr->getExprLoc();
6010 NoteRange = NotScalarExpr->getSourceRange();
6011 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006012 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00006013 ErrorFound = NotAnAssignmentOp;
6014 ErrorLoc = AtomicBody->getExprLoc();
6015 ErrorRange = AtomicBody->getSourceRange();
6016 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6017 : AtomicBody->getExprLoc();
6018 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6019 : AtomicBody->getSourceRange();
6020 }
6021 } else {
6022 ErrorFound = NotAnExpression;
6023 NoteLoc = ErrorLoc = Body->getLocStart();
6024 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006025 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00006026 if (ErrorFound != NoError) {
6027 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6028 << ErrorRange;
6029 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6030 << NoteRange;
6031 return StmtError();
6032 } else if (CurContext->isDependentContext())
6033 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006034 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006035 // If clause is update:
6036 // x++;
6037 // x--;
6038 // ++x;
6039 // --x;
6040 // x binop= expr;
6041 // x = x binop expr;
6042 // x = expr binop x;
6043 OpenMPAtomicUpdateChecker Checker(*this);
6044 if (Checker.checkStatement(
6045 Body, (AtomicKind == OMPC_update)
6046 ? diag::err_omp_atomic_update_not_expression_statement
6047 : diag::err_omp_atomic_not_expression_statement,
6048 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006049 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006050 if (!CurContext->isDependentContext()) {
6051 E = Checker.getExpr();
6052 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006053 UE = Checker.getUpdateExpr();
6054 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006055 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006056 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006057 enum {
6058 NotAnAssignmentOp,
6059 NotACompoundStatement,
6060 NotTwoSubstatements,
6061 NotASpecificExpression,
6062 NoError
6063 } ErrorFound = NoError;
6064 SourceLocation ErrorLoc, NoteLoc;
6065 SourceRange ErrorRange, NoteRange;
6066 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6067 // If clause is a capture:
6068 // v = x++;
6069 // v = x--;
6070 // v = ++x;
6071 // v = --x;
6072 // v = x binop= expr;
6073 // v = x = x binop expr;
6074 // v = x = expr binop x;
6075 auto *AtomicBinOp =
6076 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6077 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6078 V = AtomicBinOp->getLHS();
6079 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6080 OpenMPAtomicUpdateChecker Checker(*this);
6081 if (Checker.checkStatement(
6082 Body, diag::err_omp_atomic_capture_not_expression_statement,
6083 diag::note_omp_atomic_update))
6084 return StmtError();
6085 E = Checker.getExpr();
6086 X = Checker.getX();
6087 UE = Checker.getUpdateExpr();
6088 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6089 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006090 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006091 ErrorLoc = AtomicBody->getExprLoc();
6092 ErrorRange = AtomicBody->getSourceRange();
6093 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6094 : AtomicBody->getExprLoc();
6095 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6096 : AtomicBody->getSourceRange();
6097 ErrorFound = NotAnAssignmentOp;
6098 }
6099 if (ErrorFound != NoError) {
6100 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6101 << ErrorRange;
6102 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6103 return StmtError();
6104 } else if (CurContext->isDependentContext()) {
6105 UE = V = E = X = nullptr;
6106 }
6107 } else {
6108 // If clause is a capture:
6109 // { v = x; x = expr; }
6110 // { v = x; x++; }
6111 // { v = x; x--; }
6112 // { v = x; ++x; }
6113 // { v = x; --x; }
6114 // { v = x; x binop= expr; }
6115 // { v = x; x = x binop expr; }
6116 // { v = x; x = expr binop x; }
6117 // { x++; v = x; }
6118 // { x--; v = x; }
6119 // { ++x; v = x; }
6120 // { --x; v = x; }
6121 // { x binop= expr; v = x; }
6122 // { x = x binop expr; v = x; }
6123 // { x = expr binop x; v = x; }
6124 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6125 // Check that this is { expr1; expr2; }
6126 if (CS->size() == 2) {
6127 auto *First = CS->body_front();
6128 auto *Second = CS->body_back();
6129 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6130 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6131 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6132 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6133 // Need to find what subexpression is 'v' and what is 'x'.
6134 OpenMPAtomicUpdateChecker Checker(*this);
6135 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6136 BinaryOperator *BinOp = nullptr;
6137 if (IsUpdateExprFound) {
6138 BinOp = dyn_cast<BinaryOperator>(First);
6139 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6140 }
6141 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6142 // { v = x; x++; }
6143 // { v = x; x--; }
6144 // { v = x; ++x; }
6145 // { v = x; --x; }
6146 // { v = x; x binop= expr; }
6147 // { v = x; x = x binop expr; }
6148 // { v = x; x = expr binop x; }
6149 // Check that the first expression has form v = x.
6150 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6151 llvm::FoldingSetNodeID XId, PossibleXId;
6152 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6153 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6154 IsUpdateExprFound = XId == PossibleXId;
6155 if (IsUpdateExprFound) {
6156 V = BinOp->getLHS();
6157 X = Checker.getX();
6158 E = Checker.getExpr();
6159 UE = Checker.getUpdateExpr();
6160 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006161 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006162 }
6163 }
6164 if (!IsUpdateExprFound) {
6165 IsUpdateExprFound = !Checker.checkStatement(First);
6166 BinOp = nullptr;
6167 if (IsUpdateExprFound) {
6168 BinOp = dyn_cast<BinaryOperator>(Second);
6169 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6170 }
6171 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6172 // { x++; v = x; }
6173 // { x--; v = x; }
6174 // { ++x; v = x; }
6175 // { --x; v = x; }
6176 // { x binop= expr; v = x; }
6177 // { x = x binop expr; v = x; }
6178 // { x = expr binop x; v = x; }
6179 // Check that the second expression has form v = x.
6180 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6181 llvm::FoldingSetNodeID XId, PossibleXId;
6182 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6183 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6184 IsUpdateExprFound = XId == PossibleXId;
6185 if (IsUpdateExprFound) {
6186 V = BinOp->getLHS();
6187 X = Checker.getX();
6188 E = Checker.getExpr();
6189 UE = Checker.getUpdateExpr();
6190 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006191 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006192 }
6193 }
6194 }
6195 if (!IsUpdateExprFound) {
6196 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00006197 auto *FirstExpr = dyn_cast<Expr>(First);
6198 auto *SecondExpr = dyn_cast<Expr>(Second);
6199 if (!FirstExpr || !SecondExpr ||
6200 !(FirstExpr->isInstantiationDependent() ||
6201 SecondExpr->isInstantiationDependent())) {
6202 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6203 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006204 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00006205 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6206 : First->getLocStart();
6207 NoteRange = ErrorRange = FirstBinOp
6208 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00006209 : SourceRange(ErrorLoc, ErrorLoc);
6210 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006211 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6212 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6213 ErrorFound = NotAnAssignmentOp;
6214 NoteLoc = ErrorLoc = SecondBinOp
6215 ? SecondBinOp->getOperatorLoc()
6216 : Second->getLocStart();
6217 NoteRange = ErrorRange =
6218 SecondBinOp ? SecondBinOp->getSourceRange()
6219 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006220 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006221 auto *PossibleXRHSInFirst =
6222 FirstBinOp->getRHS()->IgnoreParenImpCasts();
6223 auto *PossibleXLHSInSecond =
6224 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6225 llvm::FoldingSetNodeID X1Id, X2Id;
6226 PossibleXRHSInFirst->Profile(X1Id, Context,
6227 /*Canonical=*/true);
6228 PossibleXLHSInSecond->Profile(X2Id, Context,
6229 /*Canonical=*/true);
6230 IsUpdateExprFound = X1Id == X2Id;
6231 if (IsUpdateExprFound) {
6232 V = FirstBinOp->getLHS();
6233 X = SecondBinOp->getLHS();
6234 E = SecondBinOp->getRHS();
6235 UE = nullptr;
6236 IsXLHSInRHSPart = false;
6237 IsPostfixUpdate = true;
6238 } else {
6239 ErrorFound = NotASpecificExpression;
6240 ErrorLoc = FirstBinOp->getExprLoc();
6241 ErrorRange = FirstBinOp->getSourceRange();
6242 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6243 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6244 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006245 }
6246 }
6247 }
6248 }
6249 } else {
6250 NoteLoc = ErrorLoc = Body->getLocStart();
6251 NoteRange = ErrorRange =
6252 SourceRange(Body->getLocStart(), Body->getLocStart());
6253 ErrorFound = NotTwoSubstatements;
6254 }
6255 } else {
6256 NoteLoc = ErrorLoc = Body->getLocStart();
6257 NoteRange = ErrorRange =
6258 SourceRange(Body->getLocStart(), Body->getLocStart());
6259 ErrorFound = NotACompoundStatement;
6260 }
6261 if (ErrorFound != NoError) {
6262 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6263 << ErrorRange;
6264 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6265 return StmtError();
6266 } else if (CurContext->isDependentContext()) {
6267 UE = V = E = X = nullptr;
6268 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006269 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006270 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006271
6272 getCurFunction()->setHasBranchProtectedScope();
6273
Alexey Bataev62cec442014-11-18 10:14:22 +00006274 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006275 X, V, E, UE, IsXLHSInRHSPart,
6276 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006277}
6278
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006279StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6280 Stmt *AStmt,
6281 SourceLocation StartLoc,
6282 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006283 if (!AStmt)
6284 return StmtError();
6285
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006286 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6287 // 1.2.2 OpenMP Language Terminology
6288 // Structured block - An executable statement with a single entry at the
6289 // top and a single exit at the bottom.
6290 // The point of exit cannot be a branch out of the structured block.
6291 // longjmp() and throw() must not violate the entry/exit criteria.
6292 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006293
Alexey Bataev13314bf2014-10-09 04:18:56 +00006294 // OpenMP [2.16, Nesting of Regions]
6295 // If specified, a teams construct must be contained within a target
6296 // construct. That target construct must contain no statements or directives
6297 // outside of the teams construct.
6298 if (DSAStack->hasInnerTeamsRegion()) {
6299 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
6300 bool OMPTeamsFound = true;
6301 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6302 auto I = CS->body_begin();
6303 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00006304 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006305 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6306 OMPTeamsFound = false;
6307 break;
6308 }
6309 ++I;
6310 }
6311 assert(I != CS->body_end() && "Not found statement");
6312 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00006313 } else {
6314 auto *OED = dyn_cast<OMPExecutableDirective>(S);
6315 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00006316 }
6317 if (!OMPTeamsFound) {
6318 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6319 Diag(DSAStack->getInnerTeamsRegionLoc(),
6320 diag::note_omp_nested_teams_construct_here);
6321 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6322 << isa<OMPExecutableDirective>(S);
6323 return StmtError();
6324 }
6325 }
6326
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006327 getCurFunction()->setHasBranchProtectedScope();
6328
6329 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6330}
6331
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006332StmtResult
6333Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6334 Stmt *AStmt, SourceLocation StartLoc,
6335 SourceLocation EndLoc) {
6336 if (!AStmt)
6337 return StmtError();
6338
6339 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6340 // 1.2.2 OpenMP Language Terminology
6341 // Structured block - An executable statement with a single entry at the
6342 // top and a single exit at the bottom.
6343 // The point of exit cannot be a branch out of the structured block.
6344 // longjmp() and throw() must not violate the entry/exit criteria.
6345 CS->getCapturedDecl()->setNothrow();
6346
6347 getCurFunction()->setHasBranchProtectedScope();
6348
6349 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6350 AStmt);
6351}
6352
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006353StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6354 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6355 SourceLocation EndLoc,
6356 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6357 if (!AStmt)
6358 return StmtError();
6359
6360 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6361 // 1.2.2 OpenMP Language Terminology
6362 // Structured block - An executable statement with a single entry at the
6363 // top and a single exit at the bottom.
6364 // The point of exit cannot be a branch out of the structured block.
6365 // longjmp() and throw() must not violate the entry/exit criteria.
6366 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006367 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6368 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6369 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6370 // 1.2.2 OpenMP Language Terminology
6371 // Structured block - An executable statement with a single entry at the
6372 // top and a single exit at the bottom.
6373 // The point of exit cannot be a branch out of the structured block.
6374 // longjmp() and throw() must not violate the entry/exit criteria.
6375 CS->getCapturedDecl()->setNothrow();
6376 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006377
6378 OMPLoopDirective::HelperExprs B;
6379 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6380 // define the nested loops number.
6381 unsigned NestedLoopCount =
6382 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006383 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006384 VarsWithImplicitDSA, B);
6385 if (NestedLoopCount == 0)
6386 return StmtError();
6387
6388 assert((CurContext->isDependentContext() || B.builtAll()) &&
6389 "omp target parallel for loop exprs were not built");
6390
6391 if (!CurContext->isDependentContext()) {
6392 // Finalize the clauses that need pre-built expressions for CodeGen.
6393 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006394 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006395 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006396 B.NumIterations, *this, CurScope,
6397 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006398 return StmtError();
6399 }
6400 }
6401
6402 getCurFunction()->setHasBranchProtectedScope();
6403 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6404 NestedLoopCount, Clauses, AStmt,
6405 B, DSAStack->isCancelRegion());
6406}
6407
Alexey Bataev95b64a92017-05-30 16:00:04 +00006408/// Check for existence of a map clause in the list of clauses.
6409static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6410 const OpenMPClauseKind K) {
6411 return llvm::any_of(
6412 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6413}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006414
Alexey Bataev95b64a92017-05-30 16:00:04 +00006415template <typename... Params>
6416static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6417 const Params... ClauseTypes) {
6418 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006419}
6420
Michael Wong65f367f2015-07-21 13:44:28 +00006421StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6422 Stmt *AStmt,
6423 SourceLocation StartLoc,
6424 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006425 if (!AStmt)
6426 return StmtError();
6427
6428 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6429
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006430 // OpenMP [2.10.1, Restrictions, p. 97]
6431 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006432 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6433 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6434 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006435 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006436 return StmtError();
6437 }
6438
Michael Wong65f367f2015-07-21 13:44:28 +00006439 getCurFunction()->setHasBranchProtectedScope();
6440
6441 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6442 AStmt);
6443}
6444
Samuel Antaodf67fc42016-01-19 19:15:56 +00006445StmtResult
6446Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6447 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006448 SourceLocation EndLoc, Stmt *AStmt) {
6449 if (!AStmt)
6450 return StmtError();
6451
6452 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6453 // 1.2.2 OpenMP Language Terminology
6454 // Structured block - An executable statement with a single entry at the
6455 // top and a single exit at the bottom.
6456 // The point of exit cannot be a branch out of the structured block.
6457 // longjmp() and throw() must not violate the entry/exit criteria.
6458 CS->getCapturedDecl()->setNothrow();
6459 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
6460 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6461 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6462 // 1.2.2 OpenMP Language Terminology
6463 // Structured block - An executable statement with a single entry at the
6464 // top and a single exit at the bottom.
6465 // The point of exit cannot be a branch out of the structured block.
6466 // longjmp() and throw() must not violate the entry/exit criteria.
6467 CS->getCapturedDecl()->setNothrow();
6468 }
6469
Samuel Antaodf67fc42016-01-19 19:15:56 +00006470 // OpenMP [2.10.2, Restrictions, p. 99]
6471 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006472 if (!hasClauses(Clauses, OMPC_map)) {
6473 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6474 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006475 return StmtError();
6476 }
6477
Alexey Bataev7828b252017-11-21 17:08:48 +00006478 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6479 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006480}
6481
Samuel Antao72590762016-01-19 20:04:50 +00006482StmtResult
6483Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6484 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006485 SourceLocation EndLoc, Stmt *AStmt) {
6486 if (!AStmt)
6487 return StmtError();
6488
6489 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6490 // 1.2.2 OpenMP Language Terminology
6491 // Structured block - An executable statement with a single entry at the
6492 // top and a single exit at the bottom.
6493 // The point of exit cannot be a branch out of the structured block.
6494 // longjmp() and throw() must not violate the entry/exit criteria.
6495 CS->getCapturedDecl()->setNothrow();
6496 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
6497 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6498 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6499 // 1.2.2 OpenMP Language Terminology
6500 // Structured block - An executable statement with a single entry at the
6501 // top and a single exit at the bottom.
6502 // The point of exit cannot be a branch out of the structured block.
6503 // longjmp() and throw() must not violate the entry/exit criteria.
6504 CS->getCapturedDecl()->setNothrow();
6505 }
6506
Samuel Antao72590762016-01-19 20:04:50 +00006507 // OpenMP [2.10.3, Restrictions, p. 102]
6508 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006509 if (!hasClauses(Clauses, OMPC_map)) {
6510 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6511 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006512 return StmtError();
6513 }
6514
Alexey Bataev7828b252017-11-21 17:08:48 +00006515 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6516 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00006517}
6518
Samuel Antao686c70c2016-05-26 17:30:50 +00006519StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6520 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006521 SourceLocation EndLoc,
6522 Stmt *AStmt) {
6523 if (!AStmt)
6524 return StmtError();
6525
6526 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6527 // 1.2.2 OpenMP Language Terminology
6528 // Structured block - An executable statement with a single entry at the
6529 // top and a single exit at the bottom.
6530 // The point of exit cannot be a branch out of the structured block.
6531 // longjmp() and throw() must not violate the entry/exit criteria.
6532 CS->getCapturedDecl()->setNothrow();
6533 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
6534 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6535 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6536 // 1.2.2 OpenMP Language Terminology
6537 // Structured block - An executable statement with a single entry at the
6538 // top and a single exit at the bottom.
6539 // The point of exit cannot be a branch out of the structured block.
6540 // longjmp() and throw() must not violate the entry/exit criteria.
6541 CS->getCapturedDecl()->setNothrow();
6542 }
6543
Alexey Bataev95b64a92017-05-30 16:00:04 +00006544 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006545 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6546 return StmtError();
6547 }
Alexey Bataev7828b252017-11-21 17:08:48 +00006548 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
6549 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00006550}
6551
Alexey Bataev13314bf2014-10-09 04:18:56 +00006552StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6553 Stmt *AStmt, SourceLocation StartLoc,
6554 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006555 if (!AStmt)
6556 return StmtError();
6557
Alexey Bataev13314bf2014-10-09 04:18:56 +00006558 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6559 // 1.2.2 OpenMP Language Terminology
6560 // Structured block - An executable statement with a single entry at the
6561 // top and a single exit at the bottom.
6562 // The point of exit cannot be a branch out of the structured block.
6563 // longjmp() and throw() must not violate the entry/exit criteria.
6564 CS->getCapturedDecl()->setNothrow();
6565
6566 getCurFunction()->setHasBranchProtectedScope();
6567
6568 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6569}
6570
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006571StmtResult
6572Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6573 SourceLocation EndLoc,
6574 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006575 if (DSAStack->isParentNowaitRegion()) {
6576 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6577 return StmtError();
6578 }
6579 if (DSAStack->isParentOrderedRegion()) {
6580 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6581 return StmtError();
6582 }
6583 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6584 CancelRegion);
6585}
6586
Alexey Bataev87933c72015-09-18 08:07:34 +00006587StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6588 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006589 SourceLocation EndLoc,
6590 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006591 if (DSAStack->isParentNowaitRegion()) {
6592 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6593 return StmtError();
6594 }
6595 if (DSAStack->isParentOrderedRegion()) {
6596 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6597 return StmtError();
6598 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006599 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006600 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6601 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006602}
6603
Alexey Bataev382967a2015-12-08 12:06:20 +00006604static bool checkGrainsizeNumTasksClauses(Sema &S,
6605 ArrayRef<OMPClause *> Clauses) {
6606 OMPClause *PrevClause = nullptr;
6607 bool ErrorFound = false;
6608 for (auto *C : Clauses) {
6609 if (C->getClauseKind() == OMPC_grainsize ||
6610 C->getClauseKind() == OMPC_num_tasks) {
6611 if (!PrevClause)
6612 PrevClause = C;
6613 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6614 S.Diag(C->getLocStart(),
6615 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6616 << getOpenMPClauseName(C->getClauseKind())
6617 << getOpenMPClauseName(PrevClause->getClauseKind());
6618 S.Diag(PrevClause->getLocStart(),
6619 diag::note_omp_previous_grainsize_num_tasks)
6620 << getOpenMPClauseName(PrevClause->getClauseKind());
6621 ErrorFound = true;
6622 }
6623 }
6624 }
6625 return ErrorFound;
6626}
6627
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006628static bool checkReductionClauseWithNogroup(Sema &S,
6629 ArrayRef<OMPClause *> Clauses) {
6630 OMPClause *ReductionClause = nullptr;
6631 OMPClause *NogroupClause = nullptr;
6632 for (auto *C : Clauses) {
6633 if (C->getClauseKind() == OMPC_reduction) {
6634 ReductionClause = C;
6635 if (NogroupClause)
6636 break;
6637 continue;
6638 }
6639 if (C->getClauseKind() == OMPC_nogroup) {
6640 NogroupClause = C;
6641 if (ReductionClause)
6642 break;
6643 continue;
6644 }
6645 }
6646 if (ReductionClause && NogroupClause) {
6647 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6648 << SourceRange(NogroupClause->getLocStart(),
6649 NogroupClause->getLocEnd());
6650 return true;
6651 }
6652 return false;
6653}
6654
Alexey Bataev49f6e782015-12-01 04:18:41 +00006655StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6656 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6657 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006658 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006659 if (!AStmt)
6660 return StmtError();
6661
6662 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6663 OMPLoopDirective::HelperExprs B;
6664 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6665 // define the nested loops number.
6666 unsigned NestedLoopCount =
6667 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006668 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006669 VarsWithImplicitDSA, B);
6670 if (NestedLoopCount == 0)
6671 return StmtError();
6672
6673 assert((CurContext->isDependentContext() || B.builtAll()) &&
6674 "omp for loop exprs were not built");
6675
Alexey Bataev382967a2015-12-08 12:06:20 +00006676 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6677 // The grainsize clause and num_tasks clause are mutually exclusive and may
6678 // not appear on the same taskloop directive.
6679 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6680 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006681 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6682 // If a reduction clause is present on the taskloop directive, the nogroup
6683 // clause must not be specified.
6684 if (checkReductionClauseWithNogroup(*this, Clauses))
6685 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006686
Alexey Bataev49f6e782015-12-01 04:18:41 +00006687 getCurFunction()->setHasBranchProtectedScope();
6688 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6689 NestedLoopCount, Clauses, AStmt, B);
6690}
6691
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006692StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6693 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6694 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006695 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006696 if (!AStmt)
6697 return StmtError();
6698
6699 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6700 OMPLoopDirective::HelperExprs B;
6701 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6702 // define the nested loops number.
6703 unsigned NestedLoopCount =
6704 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6705 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6706 VarsWithImplicitDSA, B);
6707 if (NestedLoopCount == 0)
6708 return StmtError();
6709
6710 assert((CurContext->isDependentContext() || B.builtAll()) &&
6711 "omp for loop exprs were not built");
6712
Alexey Bataev5a3af132016-03-29 08:58:54 +00006713 if (!CurContext->isDependentContext()) {
6714 // Finalize the clauses that need pre-built expressions for CodeGen.
6715 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006716 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006717 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006718 B.NumIterations, *this, CurScope,
6719 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006720 return StmtError();
6721 }
6722 }
6723
Alexey Bataev382967a2015-12-08 12:06:20 +00006724 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6725 // The grainsize clause and num_tasks clause are mutually exclusive and may
6726 // not appear on the same taskloop directive.
6727 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6728 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006729 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6730 // If a reduction clause is present on the taskloop directive, the nogroup
6731 // clause must not be specified.
6732 if (checkReductionClauseWithNogroup(*this, Clauses))
6733 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00006734 if (checkSimdlenSafelenSpecified(*this, Clauses))
6735 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006736
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006737 getCurFunction()->setHasBranchProtectedScope();
6738 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6739 NestedLoopCount, Clauses, AStmt, B);
6740}
6741
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006742StmtResult Sema::ActOnOpenMPDistributeDirective(
6743 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6744 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006745 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006746 if (!AStmt)
6747 return StmtError();
6748
6749 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6750 OMPLoopDirective::HelperExprs B;
6751 // In presence of clause 'collapse' with number of loops, it will
6752 // define the nested loops number.
6753 unsigned NestedLoopCount =
6754 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6755 nullptr /*ordered not a clause on distribute*/, AStmt,
6756 *this, *DSAStack, VarsWithImplicitDSA, B);
6757 if (NestedLoopCount == 0)
6758 return StmtError();
6759
6760 assert((CurContext->isDependentContext() || B.builtAll()) &&
6761 "omp for loop exprs were not built");
6762
6763 getCurFunction()->setHasBranchProtectedScope();
6764 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6765 NestedLoopCount, Clauses, AStmt, B);
6766}
6767
Carlo Bertolli9925f152016-06-27 14:55:37 +00006768StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6769 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6770 SourceLocation EndLoc,
6771 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6772 if (!AStmt)
6773 return StmtError();
6774
6775 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6776 // 1.2.2 OpenMP Language Terminology
6777 // Structured block - An executable statement with a single entry at the
6778 // top and a single exit at the bottom.
6779 // The point of exit cannot be a branch out of the structured block.
6780 // longjmp() and throw() must not violate the entry/exit criteria.
6781 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00006782 for (int ThisCaptureLevel =
6783 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
6784 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6785 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6786 // 1.2.2 OpenMP Language Terminology
6787 // Structured block - An executable statement with a single entry at the
6788 // top and a single exit at the bottom.
6789 // The point of exit cannot be a branch out of the structured block.
6790 // longjmp() and throw() must not violate the entry/exit criteria.
6791 CS->getCapturedDecl()->setNothrow();
6792 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00006793
6794 OMPLoopDirective::HelperExprs B;
6795 // In presence of clause 'collapse' with number of loops, it will
6796 // define the nested loops number.
6797 unsigned NestedLoopCount = CheckOpenMPLoop(
6798 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00006799 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00006800 VarsWithImplicitDSA, B);
6801 if (NestedLoopCount == 0)
6802 return StmtError();
6803
6804 assert((CurContext->isDependentContext() || B.builtAll()) &&
6805 "omp for loop exprs were not built");
6806
Alexey Bataev438388c2017-11-22 18:34:02 +00006807 if (!CurContext->isDependentContext()) {
6808 // Finalize the clauses that need pre-built expressions for CodeGen.
6809 for (auto C : Clauses) {
6810 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6811 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6812 B.NumIterations, *this, CurScope,
6813 DSAStack))
6814 return StmtError();
6815 }
6816 }
6817
Carlo Bertolli9925f152016-06-27 14:55:37 +00006818 getCurFunction()->setHasBranchProtectedScope();
6819 return OMPDistributeParallelForDirective::Create(
6820 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6821}
6822
Kelvin Li4a39add2016-07-05 05:00:15 +00006823StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6824 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6825 SourceLocation EndLoc,
6826 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6827 if (!AStmt)
6828 return StmtError();
6829
6830 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6831 // 1.2.2 OpenMP Language Terminology
6832 // Structured block - An executable statement with a single entry at the
6833 // top and a single exit at the bottom.
6834 // The point of exit cannot be a branch out of the structured block.
6835 // longjmp() and throw() must not violate the entry/exit criteria.
6836 CS->getCapturedDecl()->setNothrow();
6837
6838 OMPLoopDirective::HelperExprs B;
6839 // In presence of clause 'collapse' with number of loops, it will
6840 // define the nested loops number.
6841 unsigned NestedLoopCount = CheckOpenMPLoop(
6842 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6843 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6844 VarsWithImplicitDSA, B);
6845 if (NestedLoopCount == 0)
6846 return StmtError();
6847
6848 assert((CurContext->isDependentContext() || B.builtAll()) &&
6849 "omp for loop exprs were not built");
6850
Alexey Bataev438388c2017-11-22 18:34:02 +00006851 if (!CurContext->isDependentContext()) {
6852 // Finalize the clauses that need pre-built expressions for CodeGen.
6853 for (auto C : Clauses) {
6854 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6855 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6856 B.NumIterations, *this, CurScope,
6857 DSAStack))
6858 return StmtError();
6859 }
6860 }
6861
Kelvin Lic5609492016-07-15 04:39:07 +00006862 if (checkSimdlenSafelenSpecified(*this, Clauses))
6863 return StmtError();
6864
Kelvin Li4a39add2016-07-05 05:00:15 +00006865 getCurFunction()->setHasBranchProtectedScope();
6866 return OMPDistributeParallelForSimdDirective::Create(
6867 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6868}
6869
Kelvin Li787f3fc2016-07-06 04:45:38 +00006870StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6871 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6872 SourceLocation EndLoc,
6873 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6874 if (!AStmt)
6875 return StmtError();
6876
6877 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6878 // 1.2.2 OpenMP Language Terminology
6879 // Structured block - An executable statement with a single entry at the
6880 // top and a single exit at the bottom.
6881 // The point of exit cannot be a branch out of the structured block.
6882 // longjmp() and throw() must not violate the entry/exit criteria.
6883 CS->getCapturedDecl()->setNothrow();
6884
6885 OMPLoopDirective::HelperExprs B;
6886 // In presence of clause 'collapse' with number of loops, it will
6887 // define the nested loops number.
6888 unsigned NestedLoopCount =
6889 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6890 nullptr /*ordered not a clause on distribute*/, AStmt,
6891 *this, *DSAStack, VarsWithImplicitDSA, B);
6892 if (NestedLoopCount == 0)
6893 return StmtError();
6894
6895 assert((CurContext->isDependentContext() || B.builtAll()) &&
6896 "omp for loop exprs were not built");
6897
Alexey Bataev438388c2017-11-22 18:34:02 +00006898 if (!CurContext->isDependentContext()) {
6899 // Finalize the clauses that need pre-built expressions for CodeGen.
6900 for (auto C : Clauses) {
6901 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6902 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6903 B.NumIterations, *this, CurScope,
6904 DSAStack))
6905 return StmtError();
6906 }
6907 }
6908
Kelvin Lic5609492016-07-15 04:39:07 +00006909 if (checkSimdlenSafelenSpecified(*this, Clauses))
6910 return StmtError();
6911
Kelvin Li787f3fc2016-07-06 04:45:38 +00006912 getCurFunction()->setHasBranchProtectedScope();
6913 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6914 NestedLoopCount, Clauses, AStmt, B);
6915}
6916
Kelvin Lia579b912016-07-14 02:54:56 +00006917StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6918 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6919 SourceLocation EndLoc,
6920 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6921 if (!AStmt)
6922 return StmtError();
6923
6924 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6925 // 1.2.2 OpenMP Language Terminology
6926 // Structured block - An executable statement with a single entry at the
6927 // top and a single exit at the bottom.
6928 // The point of exit cannot be a branch out of the structured block.
6929 // longjmp() and throw() must not violate the entry/exit criteria.
6930 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00006931 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6932 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6933 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6934 // 1.2.2 OpenMP Language Terminology
6935 // Structured block - An executable statement with a single entry at the
6936 // top and a single exit at the bottom.
6937 // The point of exit cannot be a branch out of the structured block.
6938 // longjmp() and throw() must not violate the entry/exit criteria.
6939 CS->getCapturedDecl()->setNothrow();
6940 }
Kelvin Lia579b912016-07-14 02:54:56 +00006941
6942 OMPLoopDirective::HelperExprs B;
6943 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6944 // define the nested loops number.
6945 unsigned NestedLoopCount = CheckOpenMPLoop(
6946 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00006947 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00006948 VarsWithImplicitDSA, B);
6949 if (NestedLoopCount == 0)
6950 return StmtError();
6951
6952 assert((CurContext->isDependentContext() || B.builtAll()) &&
6953 "omp target parallel for simd loop exprs were not built");
6954
6955 if (!CurContext->isDependentContext()) {
6956 // Finalize the clauses that need pre-built expressions for CodeGen.
6957 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006958 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006959 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6960 B.NumIterations, *this, CurScope,
6961 DSAStack))
6962 return StmtError();
6963 }
6964 }
Kelvin Lic5609492016-07-15 04:39:07 +00006965 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006966 return StmtError();
6967
6968 getCurFunction()->setHasBranchProtectedScope();
6969 return OMPTargetParallelForSimdDirective::Create(
6970 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6971}
6972
Kelvin Li986330c2016-07-20 22:57:10 +00006973StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6974 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6975 SourceLocation EndLoc,
6976 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6977 if (!AStmt)
6978 return StmtError();
6979
6980 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6981 // 1.2.2 OpenMP Language Terminology
6982 // Structured block - An executable statement with a single entry at the
6983 // top and a single exit at the bottom.
6984 // The point of exit cannot be a branch out of the structured block.
6985 // longjmp() and throw() must not violate the entry/exit criteria.
6986 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00006987 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
6988 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6989 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6990 // 1.2.2 OpenMP Language Terminology
6991 // Structured block - An executable statement with a single entry at the
6992 // top and a single exit at the bottom.
6993 // The point of exit cannot be a branch out of the structured block.
6994 // longjmp() and throw() must not violate the entry/exit criteria.
6995 CS->getCapturedDecl()->setNothrow();
6996 }
6997
Kelvin Li986330c2016-07-20 22:57:10 +00006998 OMPLoopDirective::HelperExprs B;
6999 // In presence of clause 'collapse' with number of loops, it will define the
7000 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00007001 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00007002 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00007003 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00007004 VarsWithImplicitDSA, B);
7005 if (NestedLoopCount == 0)
7006 return StmtError();
7007
7008 assert((CurContext->isDependentContext() || B.builtAll()) &&
7009 "omp target simd loop exprs were not built");
7010
7011 if (!CurContext->isDependentContext()) {
7012 // Finalize the clauses that need pre-built expressions for CodeGen.
7013 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007014 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00007015 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7016 B.NumIterations, *this, CurScope,
7017 DSAStack))
7018 return StmtError();
7019 }
7020 }
7021
7022 if (checkSimdlenSafelenSpecified(*this, Clauses))
7023 return StmtError();
7024
7025 getCurFunction()->setHasBranchProtectedScope();
7026 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7027 NestedLoopCount, Clauses, AStmt, B);
7028}
7029
Kelvin Li02532872016-08-05 14:37:37 +00007030StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7031 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7032 SourceLocation EndLoc,
7033 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7034 if (!AStmt)
7035 return StmtError();
7036
7037 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7038 // 1.2.2 OpenMP Language Terminology
7039 // Structured block - An executable statement with a single entry at the
7040 // top and a single exit at the bottom.
7041 // The point of exit cannot be a branch out of the structured block.
7042 // longjmp() and throw() must not violate the entry/exit criteria.
7043 CS->getCapturedDecl()->setNothrow();
7044
7045 OMPLoopDirective::HelperExprs B;
7046 // In presence of clause 'collapse' with number of loops, it will
7047 // define the nested loops number.
7048 unsigned NestedLoopCount =
7049 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
7050 nullptr /*ordered not a clause on distribute*/, AStmt,
7051 *this, *DSAStack, VarsWithImplicitDSA, B);
7052 if (NestedLoopCount == 0)
7053 return StmtError();
7054
7055 assert((CurContext->isDependentContext() || B.builtAll()) &&
7056 "omp teams distribute loop exprs were not built");
7057
7058 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00007059 return OMPTeamsDistributeDirective::Create(
7060 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00007061}
7062
Kelvin Li4e325f72016-10-25 12:50:55 +00007063StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7064 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7065 SourceLocation EndLoc,
7066 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7067 if (!AStmt)
7068 return StmtError();
7069
7070 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7071 // 1.2.2 OpenMP Language Terminology
7072 // Structured block - An executable statement with a single entry at the
7073 // top and a single exit at the bottom.
7074 // The point of exit cannot be a branch out of the structured block.
7075 // longjmp() and throw() must not violate the entry/exit criteria.
7076 CS->getCapturedDecl()->setNothrow();
7077
7078 OMPLoopDirective::HelperExprs B;
7079 // In presence of clause 'collapse' with number of loops, it will
7080 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00007081 unsigned NestedLoopCount = CheckOpenMPLoop(
7082 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7083 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7084 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00007085
7086 if (NestedLoopCount == 0)
7087 return StmtError();
7088
7089 assert((CurContext->isDependentContext() || B.builtAll()) &&
7090 "omp teams distribute simd loop exprs were not built");
7091
7092 if (!CurContext->isDependentContext()) {
7093 // Finalize the clauses that need pre-built expressions for CodeGen.
7094 for (auto C : Clauses) {
7095 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7096 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7097 B.NumIterations, *this, CurScope,
7098 DSAStack))
7099 return StmtError();
7100 }
7101 }
7102
7103 if (checkSimdlenSafelenSpecified(*this, Clauses))
7104 return StmtError();
7105
7106 getCurFunction()->setHasBranchProtectedScope();
7107 return OMPTeamsDistributeSimdDirective::Create(
7108 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7109}
7110
Kelvin Li579e41c2016-11-30 23:51:03 +00007111StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7112 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7113 SourceLocation EndLoc,
7114 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7115 if (!AStmt)
7116 return StmtError();
7117
7118 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7119 // 1.2.2 OpenMP Language Terminology
7120 // Structured block - An executable statement with a single entry at the
7121 // top and a single exit at the bottom.
7122 // The point of exit cannot be a branch out of the structured block.
7123 // longjmp() and throw() must not violate the entry/exit criteria.
7124 CS->getCapturedDecl()->setNothrow();
7125
7126 OMPLoopDirective::HelperExprs B;
7127 // In presence of clause 'collapse' with number of loops, it will
7128 // define the nested loops number.
7129 auto NestedLoopCount = CheckOpenMPLoop(
7130 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7131 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7132 VarsWithImplicitDSA, B);
7133
7134 if (NestedLoopCount == 0)
7135 return StmtError();
7136
7137 assert((CurContext->isDependentContext() || B.builtAll()) &&
7138 "omp for loop exprs were not built");
7139
7140 if (!CurContext->isDependentContext()) {
7141 // Finalize the clauses that need pre-built expressions for CodeGen.
7142 for (auto C : Clauses) {
7143 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7144 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7145 B.NumIterations, *this, CurScope,
7146 DSAStack))
7147 return StmtError();
7148 }
7149 }
7150
7151 if (checkSimdlenSafelenSpecified(*this, Clauses))
7152 return StmtError();
7153
7154 getCurFunction()->setHasBranchProtectedScope();
7155 return OMPTeamsDistributeParallelForSimdDirective::Create(
7156 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7157}
7158
Kelvin Li7ade93f2016-12-09 03:24:30 +00007159StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7160 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7161 SourceLocation EndLoc,
7162 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7163 if (!AStmt)
7164 return StmtError();
7165
7166 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7167 // 1.2.2 OpenMP Language Terminology
7168 // Structured block - An executable statement with a single entry at the
7169 // top and a single exit at the bottom.
7170 // The point of exit cannot be a branch out of the structured block.
7171 // longjmp() and throw() must not violate the entry/exit criteria.
7172 CS->getCapturedDecl()->setNothrow();
7173
Carlo Bertolli62fae152017-11-20 20:46:39 +00007174 for (int ThisCaptureLevel =
7175 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7176 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7177 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7178 // 1.2.2 OpenMP Language Terminology
7179 // Structured block - An executable statement with a single entry at the
7180 // top and a single exit at the bottom.
7181 // The point of exit cannot be a branch out of the structured block.
7182 // longjmp() and throw() must not violate the entry/exit criteria.
7183 CS->getCapturedDecl()->setNothrow();
7184 }
7185
Kelvin Li7ade93f2016-12-09 03:24:30 +00007186 OMPLoopDirective::HelperExprs B;
7187 // In presence of clause 'collapse' with number of loops, it will
7188 // define the nested loops number.
7189 unsigned NestedLoopCount = CheckOpenMPLoop(
7190 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00007191 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00007192 VarsWithImplicitDSA, B);
7193
7194 if (NestedLoopCount == 0)
7195 return StmtError();
7196
7197 assert((CurContext->isDependentContext() || B.builtAll()) &&
7198 "omp for loop exprs were not built");
7199
7200 if (!CurContext->isDependentContext()) {
7201 // Finalize the clauses that need pre-built expressions for CodeGen.
7202 for (auto C : Clauses) {
7203 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7204 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7205 B.NumIterations, *this, CurScope,
7206 DSAStack))
7207 return StmtError();
7208 }
7209 }
7210
7211 getCurFunction()->setHasBranchProtectedScope();
7212 return OMPTeamsDistributeParallelForDirective::Create(
7213 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7214}
7215
Kelvin Libf594a52016-12-17 05:48:59 +00007216StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7217 Stmt *AStmt,
7218 SourceLocation StartLoc,
7219 SourceLocation EndLoc) {
7220 if (!AStmt)
7221 return StmtError();
7222
7223 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7224 // 1.2.2 OpenMP Language Terminology
7225 // Structured block - An executable statement with a single entry at the
7226 // top and a single exit at the bottom.
7227 // The point of exit cannot be a branch out of the structured block.
7228 // longjmp() and throw() must not violate the entry/exit criteria.
7229 CS->getCapturedDecl()->setNothrow();
7230
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00007231 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7232 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7233 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7234 // 1.2.2 OpenMP Language Terminology
7235 // Structured block - An executable statement with a single entry at the
7236 // top and a single exit at the bottom.
7237 // The point of exit cannot be a branch out of the structured block.
7238 // longjmp() and throw() must not violate the entry/exit criteria.
7239 CS->getCapturedDecl()->setNothrow();
7240 }
Kelvin Libf594a52016-12-17 05:48:59 +00007241 getCurFunction()->setHasBranchProtectedScope();
7242
7243 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7244 AStmt);
7245}
7246
Kelvin Li83c451e2016-12-25 04:52:54 +00007247StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7248 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7249 SourceLocation EndLoc,
7250 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7251 if (!AStmt)
7252 return StmtError();
7253
7254 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7255 // 1.2.2 OpenMP Language Terminology
7256 // Structured block - An executable statement with a single entry at the
7257 // top and a single exit at the bottom.
7258 // The point of exit cannot be a branch out of the structured block.
7259 // longjmp() and throw() must not violate the entry/exit criteria.
7260 CS->getCapturedDecl()->setNothrow();
7261
7262 OMPLoopDirective::HelperExprs B;
7263 // In presence of clause 'collapse' with number of loops, it will
7264 // define the nested loops number.
7265 auto NestedLoopCount = CheckOpenMPLoop(
7266 OMPD_target_teams_distribute,
7267 getCollapseNumberExpr(Clauses),
7268 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7269 VarsWithImplicitDSA, B);
7270 if (NestedLoopCount == 0)
7271 return StmtError();
7272
7273 assert((CurContext->isDependentContext() || B.builtAll()) &&
7274 "omp target teams distribute loop exprs were not built");
7275
7276 getCurFunction()->setHasBranchProtectedScope();
7277 return OMPTargetTeamsDistributeDirective::Create(
7278 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7279}
7280
Kelvin Li80e8f562016-12-29 22:16:30 +00007281StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7282 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7283 SourceLocation EndLoc,
7284 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7285 if (!AStmt)
7286 return StmtError();
7287
7288 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7289 // 1.2.2 OpenMP Language Terminology
7290 // Structured block - An executable statement with a single entry at the
7291 // top and a single exit at the bottom.
7292 // The point of exit cannot be a branch out of the structured block.
7293 // longjmp() and throw() must not violate the entry/exit criteria.
7294 CS->getCapturedDecl()->setNothrow();
7295
7296 OMPLoopDirective::HelperExprs B;
7297 // In presence of clause 'collapse' with number of loops, it will
7298 // define the nested loops number.
7299 auto NestedLoopCount = CheckOpenMPLoop(
7300 OMPD_target_teams_distribute_parallel_for,
7301 getCollapseNumberExpr(Clauses),
7302 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7303 VarsWithImplicitDSA, B);
7304 if (NestedLoopCount == 0)
7305 return StmtError();
7306
7307 assert((CurContext->isDependentContext() || B.builtAll()) &&
7308 "omp target teams distribute parallel for loop exprs were not built");
7309
7310 if (!CurContext->isDependentContext()) {
7311 // Finalize the clauses that need pre-built expressions for CodeGen.
7312 for (auto C : Clauses) {
7313 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7314 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7315 B.NumIterations, *this, CurScope,
7316 DSAStack))
7317 return StmtError();
7318 }
7319 }
7320
7321 getCurFunction()->setHasBranchProtectedScope();
7322 return OMPTargetTeamsDistributeParallelForDirective::Create(
7323 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7324}
7325
Kelvin Li1851df52017-01-03 05:23:48 +00007326StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7327 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7328 SourceLocation EndLoc,
7329 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7330 if (!AStmt)
7331 return StmtError();
7332
7333 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7334 // 1.2.2 OpenMP Language Terminology
7335 // Structured block - An executable statement with a single entry at the
7336 // top and a single exit at the bottom.
7337 // The point of exit cannot be a branch out of the structured block.
7338 // longjmp() and throw() must not violate the entry/exit criteria.
7339 CS->getCapturedDecl()->setNothrow();
7340
7341 OMPLoopDirective::HelperExprs B;
7342 // In presence of clause 'collapse' with number of loops, it will
7343 // define the nested loops number.
7344 auto NestedLoopCount = CheckOpenMPLoop(
7345 OMPD_target_teams_distribute_parallel_for_simd,
7346 getCollapseNumberExpr(Clauses),
7347 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7348 VarsWithImplicitDSA, B);
7349 if (NestedLoopCount == 0)
7350 return StmtError();
7351
7352 assert((CurContext->isDependentContext() || B.builtAll()) &&
7353 "omp target teams distribute parallel for simd loop exprs were not "
7354 "built");
7355
7356 if (!CurContext->isDependentContext()) {
7357 // Finalize the clauses that need pre-built expressions for CodeGen.
7358 for (auto C : Clauses) {
7359 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7360 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7361 B.NumIterations, *this, CurScope,
7362 DSAStack))
7363 return StmtError();
7364 }
7365 }
7366
Alexey Bataev438388c2017-11-22 18:34:02 +00007367 if (checkSimdlenSafelenSpecified(*this, Clauses))
7368 return StmtError();
7369
Kelvin Li1851df52017-01-03 05:23:48 +00007370 getCurFunction()->setHasBranchProtectedScope();
7371 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7372 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7373}
7374
Kelvin Lida681182017-01-10 18:08:18 +00007375StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7376 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7377 SourceLocation EndLoc,
7378 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7379 if (!AStmt)
7380 return StmtError();
7381
7382 auto *CS = cast<CapturedStmt>(AStmt);
7383 // 1.2.2 OpenMP Language Terminology
7384 // Structured block - An executable statement with a single entry at the
7385 // top and a single exit at the bottom.
7386 // The point of exit cannot be a branch out of the structured block.
7387 // longjmp() and throw() must not violate the entry/exit criteria.
7388 CS->getCapturedDecl()->setNothrow();
7389
7390 OMPLoopDirective::HelperExprs B;
7391 // In presence of clause 'collapse' with number of loops, it will
7392 // define the nested loops number.
7393 auto NestedLoopCount = CheckOpenMPLoop(
7394 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7395 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7396 VarsWithImplicitDSA, B);
7397 if (NestedLoopCount == 0)
7398 return StmtError();
7399
7400 assert((CurContext->isDependentContext() || B.builtAll()) &&
7401 "omp target teams distribute simd loop exprs were not built");
7402
Alexey Bataev438388c2017-11-22 18:34:02 +00007403 if (!CurContext->isDependentContext()) {
7404 // Finalize the clauses that need pre-built expressions for CodeGen.
7405 for (auto C : Clauses) {
7406 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7407 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7408 B.NumIterations, *this, CurScope,
7409 DSAStack))
7410 return StmtError();
7411 }
7412 }
7413
7414 if (checkSimdlenSafelenSpecified(*this, Clauses))
7415 return StmtError();
7416
Kelvin Lida681182017-01-10 18:08:18 +00007417 getCurFunction()->setHasBranchProtectedScope();
7418 return OMPTargetTeamsDistributeSimdDirective::Create(
7419 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7420}
7421
Alexey Bataeved09d242014-05-28 05:53:51 +00007422OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007423 SourceLocation StartLoc,
7424 SourceLocation LParenLoc,
7425 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007426 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007427 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00007428 case OMPC_final:
7429 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7430 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00007431 case OMPC_num_threads:
7432 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7433 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007434 case OMPC_safelen:
7435 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7436 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00007437 case OMPC_simdlen:
7438 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7439 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00007440 case OMPC_collapse:
7441 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7442 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007443 case OMPC_ordered:
7444 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7445 break;
Michael Wonge710d542015-08-07 16:16:36 +00007446 case OMPC_device:
7447 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7448 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007449 case OMPC_num_teams:
7450 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7451 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007452 case OMPC_thread_limit:
7453 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7454 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00007455 case OMPC_priority:
7456 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7457 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007458 case OMPC_grainsize:
7459 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7460 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00007461 case OMPC_num_tasks:
7462 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7463 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00007464 case OMPC_hint:
7465 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7466 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007467 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007468 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007469 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007470 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007471 case OMPC_private:
7472 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007473 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007474 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007475 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007476 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007477 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007478 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007479 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007480 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007481 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00007482 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007483 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007484 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007485 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007486 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007487 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007488 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007489 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007490 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007491 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007492 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00007493 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007494 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007495 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00007496 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007497 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007498 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007499 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007500 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007501 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007502 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007503 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007504 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007505 llvm_unreachable("Clause is not allowed.");
7506 }
7507 return Res;
7508}
7509
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007510// An OpenMP directive such as 'target parallel' has two captured regions:
7511// for the 'target' and 'parallel' respectively. This function returns
7512// the region in which to capture expressions associated with a clause.
7513// A return value of OMPD_unknown signifies that the expression should not
7514// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007515static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7516 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7517 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007518 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7519
7520 switch (CKind) {
7521 case OMPC_if:
7522 switch (DKind) {
7523 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007524 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007525 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007526 // If this clause applies to the nested 'parallel' region, capture within
7527 // the 'target' region, otherwise do not capture.
7528 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7529 CaptureRegion = OMPD_target;
7530 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007531 case OMPD_teams_distribute_parallel_for:
7532 CaptureRegion = OMPD_teams;
7533 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007534 case OMPD_cancel:
7535 case OMPD_parallel:
7536 case OMPD_parallel_sections:
7537 case OMPD_parallel_for:
7538 case OMPD_parallel_for_simd:
7539 case OMPD_target:
7540 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007541 case OMPD_target_teams:
7542 case OMPD_target_teams_distribute:
7543 case OMPD_target_teams_distribute_simd:
7544 case OMPD_target_teams_distribute_parallel_for:
7545 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007546 case OMPD_teams_distribute_parallel_for_simd:
7547 case OMPD_distribute_parallel_for:
7548 case OMPD_distribute_parallel_for_simd:
7549 case OMPD_task:
7550 case OMPD_taskloop:
7551 case OMPD_taskloop_simd:
7552 case OMPD_target_data:
7553 case OMPD_target_enter_data:
7554 case OMPD_target_exit_data:
7555 case OMPD_target_update:
7556 // Do not capture if-clause expressions.
7557 break;
7558 case OMPD_threadprivate:
7559 case OMPD_taskyield:
7560 case OMPD_barrier:
7561 case OMPD_taskwait:
7562 case OMPD_cancellation_point:
7563 case OMPD_flush:
7564 case OMPD_declare_reduction:
7565 case OMPD_declare_simd:
7566 case OMPD_declare_target:
7567 case OMPD_end_declare_target:
7568 case OMPD_teams:
7569 case OMPD_simd:
7570 case OMPD_for:
7571 case OMPD_for_simd:
7572 case OMPD_sections:
7573 case OMPD_section:
7574 case OMPD_single:
7575 case OMPD_master:
7576 case OMPD_critical:
7577 case OMPD_taskgroup:
7578 case OMPD_distribute:
7579 case OMPD_ordered:
7580 case OMPD_atomic:
7581 case OMPD_distribute_simd:
7582 case OMPD_teams_distribute:
7583 case OMPD_teams_distribute_simd:
7584 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7585 case OMPD_unknown:
7586 llvm_unreachable("Unknown OpenMP directive");
7587 }
7588 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007589 case OMPC_num_threads:
7590 switch (DKind) {
7591 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007592 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007593 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007594 CaptureRegion = OMPD_target;
7595 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007596 case OMPD_teams_distribute_parallel_for:
7597 CaptureRegion = OMPD_teams;
7598 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007599 case OMPD_cancel:
7600 case OMPD_parallel:
7601 case OMPD_parallel_sections:
7602 case OMPD_parallel_for:
7603 case OMPD_parallel_for_simd:
7604 case OMPD_target:
7605 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007606 case OMPD_target_teams:
7607 case OMPD_target_teams_distribute:
7608 case OMPD_target_teams_distribute_simd:
7609 case OMPD_target_teams_distribute_parallel_for:
7610 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007611 case OMPD_teams_distribute_parallel_for_simd:
7612 case OMPD_distribute_parallel_for:
7613 case OMPD_distribute_parallel_for_simd:
7614 case OMPD_task:
7615 case OMPD_taskloop:
7616 case OMPD_taskloop_simd:
7617 case OMPD_target_data:
7618 case OMPD_target_enter_data:
7619 case OMPD_target_exit_data:
7620 case OMPD_target_update:
7621 // Do not capture num_threads-clause expressions.
7622 break;
7623 case OMPD_threadprivate:
7624 case OMPD_taskyield:
7625 case OMPD_barrier:
7626 case OMPD_taskwait:
7627 case OMPD_cancellation_point:
7628 case OMPD_flush:
7629 case OMPD_declare_reduction:
7630 case OMPD_declare_simd:
7631 case OMPD_declare_target:
7632 case OMPD_end_declare_target:
7633 case OMPD_teams:
7634 case OMPD_simd:
7635 case OMPD_for:
7636 case OMPD_for_simd:
7637 case OMPD_sections:
7638 case OMPD_section:
7639 case OMPD_single:
7640 case OMPD_master:
7641 case OMPD_critical:
7642 case OMPD_taskgroup:
7643 case OMPD_distribute:
7644 case OMPD_ordered:
7645 case OMPD_atomic:
7646 case OMPD_distribute_simd:
7647 case OMPD_teams_distribute:
7648 case OMPD_teams_distribute_simd:
7649 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7650 case OMPD_unknown:
7651 llvm_unreachable("Unknown OpenMP directive");
7652 }
7653 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007654 case OMPC_num_teams:
7655 switch (DKind) {
7656 case OMPD_target_teams:
7657 CaptureRegion = OMPD_target;
7658 break;
7659 case OMPD_cancel:
7660 case OMPD_parallel:
7661 case OMPD_parallel_sections:
7662 case OMPD_parallel_for:
7663 case OMPD_parallel_for_simd:
7664 case OMPD_target:
7665 case OMPD_target_simd:
7666 case OMPD_target_parallel:
7667 case OMPD_target_parallel_for:
7668 case OMPD_target_parallel_for_simd:
7669 case OMPD_target_teams_distribute:
7670 case OMPD_target_teams_distribute_simd:
7671 case OMPD_target_teams_distribute_parallel_for:
7672 case OMPD_target_teams_distribute_parallel_for_simd:
7673 case OMPD_teams_distribute_parallel_for:
7674 case OMPD_teams_distribute_parallel_for_simd:
7675 case OMPD_distribute_parallel_for:
7676 case OMPD_distribute_parallel_for_simd:
7677 case OMPD_task:
7678 case OMPD_taskloop:
7679 case OMPD_taskloop_simd:
7680 case OMPD_target_data:
7681 case OMPD_target_enter_data:
7682 case OMPD_target_exit_data:
7683 case OMPD_target_update:
7684 case OMPD_teams:
7685 case OMPD_teams_distribute:
7686 case OMPD_teams_distribute_simd:
7687 // Do not capture num_teams-clause expressions.
7688 break;
7689 case OMPD_threadprivate:
7690 case OMPD_taskyield:
7691 case OMPD_barrier:
7692 case OMPD_taskwait:
7693 case OMPD_cancellation_point:
7694 case OMPD_flush:
7695 case OMPD_declare_reduction:
7696 case OMPD_declare_simd:
7697 case OMPD_declare_target:
7698 case OMPD_end_declare_target:
7699 case OMPD_simd:
7700 case OMPD_for:
7701 case OMPD_for_simd:
7702 case OMPD_sections:
7703 case OMPD_section:
7704 case OMPD_single:
7705 case OMPD_master:
7706 case OMPD_critical:
7707 case OMPD_taskgroup:
7708 case OMPD_distribute:
7709 case OMPD_ordered:
7710 case OMPD_atomic:
7711 case OMPD_distribute_simd:
7712 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7713 case OMPD_unknown:
7714 llvm_unreachable("Unknown OpenMP directive");
7715 }
7716 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007717 case OMPC_thread_limit:
7718 switch (DKind) {
7719 case OMPD_target_teams:
7720 CaptureRegion = OMPD_target;
7721 break;
7722 case OMPD_cancel:
7723 case OMPD_parallel:
7724 case OMPD_parallel_sections:
7725 case OMPD_parallel_for:
7726 case OMPD_parallel_for_simd:
7727 case OMPD_target:
7728 case OMPD_target_simd:
7729 case OMPD_target_parallel:
7730 case OMPD_target_parallel_for:
7731 case OMPD_target_parallel_for_simd:
7732 case OMPD_target_teams_distribute:
7733 case OMPD_target_teams_distribute_simd:
7734 case OMPD_target_teams_distribute_parallel_for:
7735 case OMPD_target_teams_distribute_parallel_for_simd:
7736 case OMPD_teams_distribute_parallel_for:
7737 case OMPD_teams_distribute_parallel_for_simd:
7738 case OMPD_distribute_parallel_for:
7739 case OMPD_distribute_parallel_for_simd:
7740 case OMPD_task:
7741 case OMPD_taskloop:
7742 case OMPD_taskloop_simd:
7743 case OMPD_target_data:
7744 case OMPD_target_enter_data:
7745 case OMPD_target_exit_data:
7746 case OMPD_target_update:
7747 case OMPD_teams:
7748 case OMPD_teams_distribute:
7749 case OMPD_teams_distribute_simd:
7750 // Do not capture thread_limit-clause expressions.
7751 break;
7752 case OMPD_threadprivate:
7753 case OMPD_taskyield:
7754 case OMPD_barrier:
7755 case OMPD_taskwait:
7756 case OMPD_cancellation_point:
7757 case OMPD_flush:
7758 case OMPD_declare_reduction:
7759 case OMPD_declare_simd:
7760 case OMPD_declare_target:
7761 case OMPD_end_declare_target:
7762 case OMPD_simd:
7763 case OMPD_for:
7764 case OMPD_for_simd:
7765 case OMPD_sections:
7766 case OMPD_section:
7767 case OMPD_single:
7768 case OMPD_master:
7769 case OMPD_critical:
7770 case OMPD_taskgroup:
7771 case OMPD_distribute:
7772 case OMPD_ordered:
7773 case OMPD_atomic:
7774 case OMPD_distribute_simd:
7775 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7776 case OMPD_unknown:
7777 llvm_unreachable("Unknown OpenMP directive");
7778 }
7779 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007780 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007781 switch (DKind) {
7782 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007783 case OMPD_target_parallel_for_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007784 CaptureRegion = OMPD_target;
7785 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007786 case OMPD_teams_distribute_parallel_for:
7787 CaptureRegion = OMPD_teams;
7788 break;
Alexey Bataev7f96c372017-11-22 17:19:31 +00007789 case OMPD_distribute_parallel_for:
7790 CaptureRegion = OMPD_parallel;
7791 break;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007792 case OMPD_parallel_for:
7793 case OMPD_parallel_for_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007794 case OMPD_target_teams_distribute_parallel_for:
7795 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007796 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007797 case OMPD_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00007798 // Do not capture schedule clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007799 break;
7800 case OMPD_task:
7801 case OMPD_taskloop:
7802 case OMPD_taskloop_simd:
7803 case OMPD_target_data:
7804 case OMPD_target_enter_data:
7805 case OMPD_target_exit_data:
7806 case OMPD_target_update:
7807 case OMPD_teams:
7808 case OMPD_teams_distribute:
7809 case OMPD_teams_distribute_simd:
7810 case OMPD_target_teams_distribute:
7811 case OMPD_target_teams_distribute_simd:
7812 case OMPD_target:
7813 case OMPD_target_simd:
7814 case OMPD_target_parallel:
7815 case OMPD_cancel:
7816 case OMPD_parallel:
7817 case OMPD_parallel_sections:
7818 case OMPD_threadprivate:
7819 case OMPD_taskyield:
7820 case OMPD_barrier:
7821 case OMPD_taskwait:
7822 case OMPD_cancellation_point:
7823 case OMPD_flush:
7824 case OMPD_declare_reduction:
7825 case OMPD_declare_simd:
7826 case OMPD_declare_target:
7827 case OMPD_end_declare_target:
7828 case OMPD_simd:
7829 case OMPD_for:
7830 case OMPD_for_simd:
7831 case OMPD_sections:
7832 case OMPD_section:
7833 case OMPD_single:
7834 case OMPD_master:
7835 case OMPD_critical:
7836 case OMPD_taskgroup:
7837 case OMPD_distribute:
7838 case OMPD_ordered:
7839 case OMPD_atomic:
7840 case OMPD_distribute_simd:
7841 case OMPD_target_teams:
7842 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
7843 case OMPD_unknown:
7844 llvm_unreachable("Unknown OpenMP directive");
7845 }
7846 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007847 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007848 switch (DKind) {
7849 case OMPD_teams_distribute_parallel_for:
7850 CaptureRegion = OMPD_teams;
7851 break;
7852 case OMPD_target_teams_distribute_parallel_for:
7853 case OMPD_target_teams_distribute_parallel_for_simd:
7854 case OMPD_teams_distribute_parallel_for_simd:
7855 case OMPD_distribute_parallel_for:
7856 case OMPD_distribute_parallel_for_simd:
7857 case OMPD_teams_distribute:
7858 case OMPD_teams_distribute_simd:
7859 case OMPD_target_teams_distribute:
7860 case OMPD_target_teams_distribute_simd:
7861 case OMPD_distribute_simd:
7862 // Do not capture thread_limit-clause expressions.
7863 break;
7864 case OMPD_parallel_for:
7865 case OMPD_parallel_for_simd:
7866 case OMPD_target_parallel_for_simd:
7867 case OMPD_target_parallel_for:
7868 case OMPD_task:
7869 case OMPD_taskloop:
7870 case OMPD_taskloop_simd:
7871 case OMPD_target_data:
7872 case OMPD_target_enter_data:
7873 case OMPD_target_exit_data:
7874 case OMPD_target_update:
7875 case OMPD_teams:
7876 case OMPD_target:
7877 case OMPD_target_simd:
7878 case OMPD_target_parallel:
7879 case OMPD_cancel:
7880 case OMPD_parallel:
7881 case OMPD_parallel_sections:
7882 case OMPD_threadprivate:
7883 case OMPD_taskyield:
7884 case OMPD_barrier:
7885 case OMPD_taskwait:
7886 case OMPD_cancellation_point:
7887 case OMPD_flush:
7888 case OMPD_declare_reduction:
7889 case OMPD_declare_simd:
7890 case OMPD_declare_target:
7891 case OMPD_end_declare_target:
7892 case OMPD_simd:
7893 case OMPD_for:
7894 case OMPD_for_simd:
7895 case OMPD_sections:
7896 case OMPD_section:
7897 case OMPD_single:
7898 case OMPD_master:
7899 case OMPD_critical:
7900 case OMPD_taskgroup:
7901 case OMPD_distribute:
7902 case OMPD_ordered:
7903 case OMPD_atomic:
7904 case OMPD_target_teams:
7905 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
7906 case OMPD_unknown:
7907 llvm_unreachable("Unknown OpenMP directive");
7908 }
7909 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007910 case OMPC_firstprivate:
7911 case OMPC_lastprivate:
7912 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007913 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007914 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007915 case OMPC_linear:
7916 case OMPC_default:
7917 case OMPC_proc_bind:
7918 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007919 case OMPC_safelen:
7920 case OMPC_simdlen:
7921 case OMPC_collapse:
7922 case OMPC_private:
7923 case OMPC_shared:
7924 case OMPC_aligned:
7925 case OMPC_copyin:
7926 case OMPC_copyprivate:
7927 case OMPC_ordered:
7928 case OMPC_nowait:
7929 case OMPC_untied:
7930 case OMPC_mergeable:
7931 case OMPC_threadprivate:
7932 case OMPC_flush:
7933 case OMPC_read:
7934 case OMPC_write:
7935 case OMPC_update:
7936 case OMPC_capture:
7937 case OMPC_seq_cst:
7938 case OMPC_depend:
7939 case OMPC_device:
7940 case OMPC_threads:
7941 case OMPC_simd:
7942 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007943 case OMPC_priority:
7944 case OMPC_grainsize:
7945 case OMPC_nogroup:
7946 case OMPC_num_tasks:
7947 case OMPC_hint:
7948 case OMPC_defaultmap:
7949 case OMPC_unknown:
7950 case OMPC_uniform:
7951 case OMPC_to:
7952 case OMPC_from:
7953 case OMPC_use_device_ptr:
7954 case OMPC_is_device_ptr:
7955 llvm_unreachable("Unexpected OpenMP clause.");
7956 }
7957 return CaptureRegion;
7958}
7959
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007960OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7961 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007962 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007963 SourceLocation NameModifierLoc,
7964 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007965 SourceLocation EndLoc) {
7966 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007967 Stmt *HelperValStmt = nullptr;
7968 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007969 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7970 !Condition->isInstantiationDependent() &&
7971 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007972 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007973 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007974 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007975
Richard Smith03a4aa32016-06-23 19:02:52 +00007976 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007977
7978 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7979 CaptureRegion =
7980 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7981 if (CaptureRegion != OMPD_unknown) {
7982 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7983 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7984 HelperValStmt = buildPreInits(Context, Captures);
7985 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007986 }
7987
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007988 return new (Context)
7989 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7990 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007991}
7992
Alexey Bataev3778b602014-07-17 07:32:53 +00007993OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7994 SourceLocation StartLoc,
7995 SourceLocation LParenLoc,
7996 SourceLocation EndLoc) {
7997 Expr *ValExpr = Condition;
7998 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7999 !Condition->isInstantiationDependent() &&
8000 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008001 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00008002 if (Val.isInvalid())
8003 return nullptr;
8004
Richard Smith03a4aa32016-06-23 19:02:52 +00008005 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00008006 }
8007
8008 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8009}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008010ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8011 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00008012 if (!Op)
8013 return ExprError();
8014
8015 class IntConvertDiagnoser : public ICEConvertDiagnoser {
8016 public:
8017 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00008018 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00008019 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8020 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008021 return S.Diag(Loc, diag::err_omp_not_integral) << T;
8022 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008023 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8024 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008025 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8026 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008027 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8028 QualType T,
8029 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008030 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8031 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008032 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8033 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008034 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008035 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008036 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008037 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8038 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008039 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8040 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008041 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8042 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008043 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008044 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008045 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008046 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8047 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008048 llvm_unreachable("conversion functions are permitted");
8049 }
8050 } ConvertDiagnoser;
8051 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8052}
8053
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008054static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00008055 OpenMPClauseKind CKind,
8056 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008057 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8058 !ValExpr->isInstantiationDependent()) {
8059 SourceLocation Loc = ValExpr->getExprLoc();
8060 ExprResult Value =
8061 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8062 if (Value.isInvalid())
8063 return false;
8064
8065 ValExpr = Value.get();
8066 // The expression must evaluate to a non-negative integer value.
8067 llvm::APSInt Result;
8068 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00008069 Result.isSigned() &&
8070 !((!StrictlyPositive && Result.isNonNegative()) ||
8071 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008072 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008073 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8074 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008075 return false;
8076 }
8077 }
8078 return true;
8079}
8080
Alexey Bataev568a8332014-03-06 06:15:19 +00008081OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8082 SourceLocation StartLoc,
8083 SourceLocation LParenLoc,
8084 SourceLocation EndLoc) {
8085 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008086 Stmt *HelperValStmt = nullptr;
8087 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00008088
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008089 // OpenMP [2.5, Restrictions]
8090 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00008091 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
8092 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008093 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008094
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008095 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8096 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8097 if (CaptureRegion != OMPD_unknown) {
8098 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8099 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8100 HelperValStmt = buildPreInits(Context, Captures);
8101 }
8102
8103 return new (Context) OMPNumThreadsClause(
8104 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00008105}
8106
Alexey Bataev62c87d22014-03-21 04:51:18 +00008107ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008108 OpenMPClauseKind CKind,
8109 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008110 if (!E)
8111 return ExprError();
8112 if (E->isValueDependent() || E->isTypeDependent() ||
8113 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008114 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008115 llvm::APSInt Result;
8116 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8117 if (ICE.isInvalid())
8118 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008119 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8120 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008121 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008122 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8123 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00008124 return ExprError();
8125 }
Alexander Musman09184fe2014-09-30 05:29:28 +00008126 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8127 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8128 << E->getSourceRange();
8129 return ExprError();
8130 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008131 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8132 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00008133 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008134 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00008135 return ICE;
8136}
8137
8138OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8139 SourceLocation LParenLoc,
8140 SourceLocation EndLoc) {
8141 // OpenMP [2.8.1, simd construct, Description]
8142 // The parameter of the safelen clause must be a constant
8143 // positive integer expression.
8144 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8145 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008146 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008147 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008148 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00008149}
8150
Alexey Bataev66b15b52015-08-21 11:14:16 +00008151OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8152 SourceLocation LParenLoc,
8153 SourceLocation EndLoc) {
8154 // OpenMP [2.8.1, simd construct, Description]
8155 // The parameter of the simdlen clause must be a constant
8156 // positive integer expression.
8157 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8158 if (Simdlen.isInvalid())
8159 return nullptr;
8160 return new (Context)
8161 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8162}
8163
Alexander Musman64d33f12014-06-04 07:53:32 +00008164OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8165 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00008166 SourceLocation LParenLoc,
8167 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00008168 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008169 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00008170 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008171 // The parameter of the collapse clause must be a constant
8172 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00008173 ExprResult NumForLoopsResult =
8174 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8175 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00008176 return nullptr;
8177 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00008178 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00008179}
8180
Alexey Bataev10e775f2015-07-30 11:36:16 +00008181OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8182 SourceLocation EndLoc,
8183 SourceLocation LParenLoc,
8184 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00008185 // OpenMP [2.7.1, loop construct, Description]
8186 // OpenMP [2.8.1, simd construct, Description]
8187 // OpenMP [2.9.6, distribute construct, Description]
8188 // The parameter of the ordered clause must be a constant
8189 // positive integer expression if any.
8190 if (NumForLoops && LParenLoc.isValid()) {
8191 ExprResult NumForLoopsResult =
8192 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8193 if (NumForLoopsResult.isInvalid())
8194 return nullptr;
8195 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00008196 } else
8197 NumForLoops = nullptr;
8198 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00008199 return new (Context)
8200 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
8201}
8202
Alexey Bataeved09d242014-05-28 05:53:51 +00008203OMPClause *Sema::ActOnOpenMPSimpleClause(
8204 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8205 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008206 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008207 switch (Kind) {
8208 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008209 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00008210 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
8211 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008212 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008213 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00008214 Res = ActOnOpenMPProcBindClause(
8215 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
8216 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008217 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008218 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008219 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008220 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008221 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008222 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008223 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008224 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008225 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008226 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008227 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008228 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008229 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008230 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008231 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008232 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008233 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008234 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008235 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008236 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008237 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008238 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008239 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008240 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008241 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008242 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008243 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008244 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008245 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008246 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008247 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008248 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008249 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008250 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008251 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008252 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008253 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008254 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008255 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008256 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008257 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008258 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008259 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008260 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008261 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008262 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008263 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008264 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008265 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008266 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008267 llvm_unreachable("Clause is not allowed.");
8268 }
8269 return Res;
8270}
8271
Alexey Bataev6402bca2015-12-28 07:25:51 +00008272static std::string
8273getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
8274 ArrayRef<unsigned> Exclude = llvm::None) {
8275 std::string Values;
8276 unsigned Bound = Last >= 2 ? Last - 2 : 0;
8277 unsigned Skipped = Exclude.size();
8278 auto S = Exclude.begin(), E = Exclude.end();
8279 for (unsigned i = First; i < Last; ++i) {
8280 if (std::find(S, E, i) != E) {
8281 --Skipped;
8282 continue;
8283 }
8284 Values += "'";
8285 Values += getOpenMPSimpleClauseTypeName(K, i);
8286 Values += "'";
8287 if (i == Bound - Skipped)
8288 Values += " or ";
8289 else if (i != Bound + 1 - Skipped)
8290 Values += ", ";
8291 }
8292 return Values;
8293}
8294
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008295OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8296 SourceLocation KindKwLoc,
8297 SourceLocation StartLoc,
8298 SourceLocation LParenLoc,
8299 SourceLocation EndLoc) {
8300 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00008301 static_assert(OMPC_DEFAULT_unknown > 0,
8302 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008303 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008304 << getListOfPossibleValues(OMPC_default, /*First=*/0,
8305 /*Last=*/OMPC_DEFAULT_unknown)
8306 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008307 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008308 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00008309 switch (Kind) {
8310 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008311 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008312 break;
8313 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008314 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008315 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008316 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008317 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00008318 break;
8319 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008320 return new (Context)
8321 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008322}
8323
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008324OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8325 SourceLocation KindKwLoc,
8326 SourceLocation StartLoc,
8327 SourceLocation LParenLoc,
8328 SourceLocation EndLoc) {
8329 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008330 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008331 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
8332 /*Last=*/OMPC_PROC_BIND_unknown)
8333 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008334 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008335 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008336 return new (Context)
8337 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008338}
8339
Alexey Bataev56dafe82014-06-20 07:16:17 +00008340OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008341 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008342 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008343 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008344 SourceLocation EndLoc) {
8345 OMPClause *Res = nullptr;
8346 switch (Kind) {
8347 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008348 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
8349 assert(Argument.size() == NumberOfElements &&
8350 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008351 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008352 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
8353 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
8354 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
8355 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
8356 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008357 break;
8358 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008359 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
8360 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
8361 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
8362 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008363 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00008364 case OMPC_dist_schedule:
8365 Res = ActOnOpenMPDistScheduleClause(
8366 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
8367 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
8368 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008369 case OMPC_defaultmap:
8370 enum { Modifier, DefaultmapKind };
8371 Res = ActOnOpenMPDefaultmapClause(
8372 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8373 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00008374 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8375 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008376 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00008377 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008378 case OMPC_num_threads:
8379 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008380 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008381 case OMPC_collapse:
8382 case OMPC_default:
8383 case OMPC_proc_bind:
8384 case OMPC_private:
8385 case OMPC_firstprivate:
8386 case OMPC_lastprivate:
8387 case OMPC_shared:
8388 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008389 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008390 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008391 case OMPC_linear:
8392 case OMPC_aligned:
8393 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008394 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008395 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008396 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008397 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008398 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008399 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008400 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008401 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008402 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008403 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008404 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008405 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008406 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008407 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008408 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008409 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008410 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008411 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008412 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008413 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008414 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008415 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008416 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008417 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008418 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008419 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008420 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008421 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008422 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008423 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008424 llvm_unreachable("Clause is not allowed.");
8425 }
8426 return Res;
8427}
8428
Alexey Bataev6402bca2015-12-28 07:25:51 +00008429static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8430 OpenMPScheduleClauseModifier M2,
8431 SourceLocation M1Loc, SourceLocation M2Loc) {
8432 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8433 SmallVector<unsigned, 2> Excluded;
8434 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8435 Excluded.push_back(M2);
8436 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8437 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8438 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8439 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8440 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8441 << getListOfPossibleValues(OMPC_schedule,
8442 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8443 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8444 Excluded)
8445 << getOpenMPClauseName(OMPC_schedule);
8446 return true;
8447 }
8448 return false;
8449}
8450
Alexey Bataev56dafe82014-06-20 07:16:17 +00008451OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008452 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008453 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008454 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8455 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8456 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8457 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8458 return nullptr;
8459 // OpenMP, 2.7.1, Loop Construct, Restrictions
8460 // Either the monotonic modifier or the nonmonotonic modifier can be specified
8461 // but not both.
8462 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8463 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8464 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8465 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8466 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8467 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8468 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8469 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8470 return nullptr;
8471 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008472 if (Kind == OMPC_SCHEDULE_unknown) {
8473 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00008474 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8475 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8476 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8477 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8478 Exclude);
8479 } else {
8480 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8481 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008482 }
8483 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8484 << Values << getOpenMPClauseName(OMPC_schedule);
8485 return nullptr;
8486 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00008487 // OpenMP, 2.7.1, Loop Construct, Restrictions
8488 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8489 // schedule(guided).
8490 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8491 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8492 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8493 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8494 diag::err_omp_schedule_nonmonotonic_static);
8495 return nullptr;
8496 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008497 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00008498 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00008499 if (ChunkSize) {
8500 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8501 !ChunkSize->isInstantiationDependent() &&
8502 !ChunkSize->containsUnexpandedParameterPack()) {
8503 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8504 ExprResult Val =
8505 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8506 if (Val.isInvalid())
8507 return nullptr;
8508
8509 ValExpr = Val.get();
8510
8511 // OpenMP [2.7.1, Restrictions]
8512 // chunk_size must be a loop invariant integer expression with a positive
8513 // value.
8514 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00008515 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8516 if (Result.isSigned() && !Result.isStrictlyPositive()) {
8517 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008518 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00008519 return nullptr;
8520 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00008521 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
8522 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00008523 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8524 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8525 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008526 }
8527 }
8528 }
8529
Alexey Bataev6402bca2015-12-28 07:25:51 +00008530 return new (Context)
8531 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00008532 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008533}
8534
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008535OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8536 SourceLocation StartLoc,
8537 SourceLocation EndLoc) {
8538 OMPClause *Res = nullptr;
8539 switch (Kind) {
8540 case OMPC_ordered:
8541 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8542 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00008543 case OMPC_nowait:
8544 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8545 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008546 case OMPC_untied:
8547 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8548 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008549 case OMPC_mergeable:
8550 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8551 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008552 case OMPC_read:
8553 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8554 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00008555 case OMPC_write:
8556 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8557 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008558 case OMPC_update:
8559 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8560 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00008561 case OMPC_capture:
8562 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8563 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008564 case OMPC_seq_cst:
8565 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8566 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00008567 case OMPC_threads:
8568 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8569 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008570 case OMPC_simd:
8571 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8572 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00008573 case OMPC_nogroup:
8574 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8575 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008576 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008577 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008578 case OMPC_num_threads:
8579 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008580 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008581 case OMPC_collapse:
8582 case OMPC_schedule:
8583 case OMPC_private:
8584 case OMPC_firstprivate:
8585 case OMPC_lastprivate:
8586 case OMPC_shared:
8587 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008588 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008589 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008590 case OMPC_linear:
8591 case OMPC_aligned:
8592 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008593 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008594 case OMPC_default:
8595 case OMPC_proc_bind:
8596 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008597 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008598 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008599 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008600 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008601 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008602 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008603 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008604 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00008605 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008606 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008607 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008608 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008609 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008610 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008611 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008612 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008613 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008614 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008615 llvm_unreachable("Clause is not allowed.");
8616 }
8617 return Res;
8618}
8619
Alexey Bataev236070f2014-06-20 11:19:47 +00008620OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8621 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008622 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00008623 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8624}
8625
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008626OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8627 SourceLocation EndLoc) {
8628 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8629}
8630
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008631OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8632 SourceLocation EndLoc) {
8633 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
8634}
8635
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008636OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
8637 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008638 return new (Context) OMPReadClause(StartLoc, EndLoc);
8639}
8640
Alexey Bataevdea47612014-07-23 07:46:59 +00008641OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
8642 SourceLocation EndLoc) {
8643 return new (Context) OMPWriteClause(StartLoc, EndLoc);
8644}
8645
Alexey Bataev67a4f222014-07-23 10:25:33 +00008646OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8647 SourceLocation EndLoc) {
8648 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
8649}
8650
Alexey Bataev459dec02014-07-24 06:46:57 +00008651OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8652 SourceLocation EndLoc) {
8653 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
8654}
8655
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008656OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8657 SourceLocation EndLoc) {
8658 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
8659}
8660
Alexey Bataev346265e2015-09-25 10:37:12 +00008661OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8662 SourceLocation EndLoc) {
8663 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
8664}
8665
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008666OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8667 SourceLocation EndLoc) {
8668 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
8669}
8670
Alexey Bataevb825de12015-12-07 10:51:44 +00008671OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8672 SourceLocation EndLoc) {
8673 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
8674}
8675
Alexey Bataevc5e02582014-06-16 07:08:35 +00008676OMPClause *Sema::ActOnOpenMPVarListClause(
8677 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
8678 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
8679 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008680 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00008681 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8682 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8683 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008684 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008685 switch (Kind) {
8686 case OMPC_private:
8687 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8688 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008689 case OMPC_firstprivate:
8690 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8691 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008692 case OMPC_lastprivate:
8693 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8694 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008695 case OMPC_shared:
8696 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
8697 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008698 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00008699 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8700 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008701 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00008702 case OMPC_task_reduction:
8703 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8704 EndLoc, ReductionIdScopeSpec,
8705 ReductionId);
8706 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00008707 case OMPC_in_reduction:
8708 Res =
8709 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8710 EndLoc, ReductionIdScopeSpec, ReductionId);
8711 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00008712 case OMPC_linear:
8713 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008714 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00008715 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008716 case OMPC_aligned:
8717 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
8718 ColonLoc, EndLoc);
8719 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008720 case OMPC_copyin:
8721 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
8722 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008723 case OMPC_copyprivate:
8724 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8725 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00008726 case OMPC_flush:
8727 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
8728 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008729 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00008730 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008731 StartLoc, LParenLoc, EndLoc);
8732 break;
8733 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00008734 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
8735 DepLinMapLoc, ColonLoc, VarList, StartLoc,
8736 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008737 break;
Samuel Antao661c0902016-05-26 17:39:58 +00008738 case OMPC_to:
8739 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
8740 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00008741 case OMPC_from:
8742 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
8743 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00008744 case OMPC_use_device_ptr:
8745 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8746 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00008747 case OMPC_is_device_ptr:
8748 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8749 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008750 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008751 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008752 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008753 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008754 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008755 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008756 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008757 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008758 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008759 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008760 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008761 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008762 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008763 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008764 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008765 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008766 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008767 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008768 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00008769 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008770 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008771 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008772 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008773 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008774 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008775 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008776 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008777 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008778 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008779 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008780 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008781 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008782 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008783 llvm_unreachable("Clause is not allowed.");
8784 }
8785 return Res;
8786}
8787
Alexey Bataev90c228f2016-02-08 09:29:13 +00008788ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00008789 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00008790 ExprResult Res = BuildDeclRefExpr(
8791 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
8792 if (!Res.isUsable())
8793 return ExprError();
8794 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
8795 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
8796 if (!Res.isUsable())
8797 return ExprError();
8798 }
8799 if (VK != VK_LValue && Res.get()->isGLValue()) {
8800 Res = DefaultLvalueConversion(Res.get());
8801 if (!Res.isUsable())
8802 return ExprError();
8803 }
8804 return Res;
8805}
8806
Alexey Bataev60da77e2016-02-29 05:54:20 +00008807static std::pair<ValueDecl *, bool>
8808getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
8809 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008810 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
8811 RefExpr->containsUnexpandedParameterPack())
8812 return std::make_pair(nullptr, true);
8813
Alexey Bataevd985eda2016-02-10 11:29:16 +00008814 // OpenMP [3.1, C/C++]
8815 // A list item is a variable name.
8816 // OpenMP [2.9.3.3, Restrictions, p.1]
8817 // A variable that is part of another variable (as an array or
8818 // structure element) cannot appear in a private clause.
8819 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008820 enum {
8821 NoArrayExpr = -1,
8822 ArraySubscript = 0,
8823 OMPArraySection = 1
8824 } IsArrayExpr = NoArrayExpr;
8825 if (AllowArraySection) {
8826 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
8827 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
8828 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8829 Base = TempASE->getBase()->IgnoreParenImpCasts();
8830 RefExpr = Base;
8831 IsArrayExpr = ArraySubscript;
8832 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8833 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8834 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8835 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8836 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8837 Base = TempASE->getBase()->IgnoreParenImpCasts();
8838 RefExpr = Base;
8839 IsArrayExpr = OMPArraySection;
8840 }
8841 }
8842 ELoc = RefExpr->getExprLoc();
8843 ERange = RefExpr->getSourceRange();
8844 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008845 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8846 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8847 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8848 (S.getCurrentThisType().isNull() || !ME ||
8849 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8850 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008851 if (IsArrayExpr != NoArrayExpr)
8852 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8853 << ERange;
8854 else {
8855 S.Diag(ELoc,
8856 AllowArraySection
8857 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8858 : diag::err_omp_expected_var_name_member_expr)
8859 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8860 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008861 return std::make_pair(nullptr, false);
8862 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00008863 return std::make_pair(
8864 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008865}
8866
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008867OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8868 SourceLocation StartLoc,
8869 SourceLocation LParenLoc,
8870 SourceLocation EndLoc) {
8871 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00008872 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00008873 for (auto &RefExpr : VarList) {
8874 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008875 SourceLocation ELoc;
8876 SourceRange ERange;
8877 Expr *SimpleRefExpr = RefExpr;
8878 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008879 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008880 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008881 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008882 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008883 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008884 ValueDecl *D = Res.first;
8885 if (!D)
8886 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008887
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008888 QualType Type = D->getType();
8889 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008890
8891 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8892 // A variable that appears in a private clause must not have an incomplete
8893 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008894 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008895 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008896 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008897
Alexey Bataev758e55e2013-09-06 18:03:48 +00008898 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8899 // in a Construct]
8900 // Variables with the predetermined data-sharing attributes may not be
8901 // listed in data-sharing attributes clauses, except for the cases
8902 // listed below. For these exceptions only, listing a predetermined
8903 // variable in a data-sharing attribute clause is allowed and overrides
8904 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008905 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008906 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00008907 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8908 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008909 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008910 continue;
8911 }
8912
Kelvin Libf594a52016-12-17 05:48:59 +00008913 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008914 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008915 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00008916 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008917 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8918 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00008919 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008920 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008921 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008922 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008923 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008924 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008925 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008926 continue;
8927 }
8928
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008929 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8930 // A list item cannot appear in both a map clause and a data-sharing
8931 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008932 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008933 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008934 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008935 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008936 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008937 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008938 CurrDir == OMPD_target_parallel_for_simd ||
8939 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008940 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008941 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008942 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008943 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8944 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8945 ConflictKind = WhereFoundClauseKind;
8946 return true;
8947 })) {
8948 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008949 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00008950 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00008951 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008952 ReportOriginalDSA(*this, DSAStack, D, DVar);
8953 continue;
8954 }
8955 }
8956
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008957 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
8958 // A variable of class type (or array thereof) that appears in a private
8959 // clause requires an accessible, unambiguous default constructor for the
8960 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00008961 // Generate helper private variable and initialize it with the default
8962 // value. The address of the original variable is replaced by the address of
8963 // the new private variable in CodeGen. This new variable is not added to
8964 // IdResolver, so the code in the OpenMP region uses original variable for
8965 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008966 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008967 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8968 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00008969 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008970 if (VDPrivate->isInvalidDecl())
8971 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008972 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008973 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008974
Alexey Bataev90c228f2016-02-08 09:29:13 +00008975 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008976 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008977 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00008978 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008979 Vars.push_back((VD || CurContext->isDependentContext())
8980 ? RefExpr->IgnoreParens()
8981 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008982 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008983 }
8984
Alexey Bataeved09d242014-05-28 05:53:51 +00008985 if (Vars.empty())
8986 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008987
Alexey Bataev03b340a2014-10-21 03:16:40 +00008988 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8989 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008990}
8991
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008992namespace {
8993class DiagsUninitializedSeveretyRAII {
8994private:
8995 DiagnosticsEngine &Diags;
8996 SourceLocation SavedLoc;
8997 bool IsIgnored;
8998
8999public:
9000 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9001 bool IsIgnored)
9002 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9003 if (!IsIgnored) {
9004 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9005 /*Map*/ diag::Severity::Ignored, Loc);
9006 }
9007 }
9008 ~DiagsUninitializedSeveretyRAII() {
9009 if (!IsIgnored)
9010 Diags.popMappings(SavedLoc);
9011 }
9012};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009013}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009014
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009015OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9016 SourceLocation StartLoc,
9017 SourceLocation LParenLoc,
9018 SourceLocation EndLoc) {
9019 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009020 SmallVector<Expr *, 8> PrivateCopies;
9021 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00009022 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009023 bool IsImplicitClause =
9024 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
9025 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
9026
Alexey Bataeved09d242014-05-28 05:53:51 +00009027 for (auto &RefExpr : VarList) {
9028 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009029 SourceLocation ELoc;
9030 SourceRange ERange;
9031 Expr *SimpleRefExpr = RefExpr;
9032 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009033 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009034 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009035 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009036 PrivateCopies.push_back(nullptr);
9037 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009038 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009039 ValueDecl *D = Res.first;
9040 if (!D)
9041 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009042
Alexey Bataev60da77e2016-02-29 05:54:20 +00009043 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009044 QualType Type = D->getType();
9045 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009046
9047 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9048 // A variable that appears in a private clause must not have an incomplete
9049 // type or a reference type.
9050 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00009051 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009052 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009053 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009054
9055 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
9056 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00009057 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009058 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009059 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009060
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009061 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00009062 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009063 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009064 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009065 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009066 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009067 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009068 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9069 // A list item that specifies a given variable may not appear in more
9070 // than one clause on the same directive, except that a variable may be
9071 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009072 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9073 // A list item may appear in a firstprivate or lastprivate clause but not
9074 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009075 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009076 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) &&
9077 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009078 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009079 << getOpenMPClauseName(DVar.CKind)
9080 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009081 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009082 continue;
9083 }
9084
9085 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9086 // in a Construct]
9087 // Variables with the predetermined data-sharing attributes may not be
9088 // listed in data-sharing attributes clauses, except for the cases
9089 // listed below. For these exceptions only, listing a predetermined
9090 // variable in a data-sharing attribute clause is allowed and overrides
9091 // the variable's predetermined data-sharing attributes.
9092 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9093 // in a Construct, C/C++, p.2]
9094 // Variables with const-qualified type having no mutable member may be
9095 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00009096 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009097 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9098 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009099 << getOpenMPClauseName(DVar.CKind)
9100 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009101 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009102 continue;
9103 }
9104
9105 // OpenMP [2.9.3.4, Restrictions, p.2]
9106 // A list item that is private within a parallel region must not appear
9107 // in a firstprivate clause on a worksharing construct if any of the
9108 // worksharing regions arising from the worksharing construct ever bind
9109 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009110 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9111 // A list item that is private within a teams region must not appear in a
9112 // firstprivate clause on a distribute construct if any of the distribute
9113 // regions arising from the distribute construct ever bind to any of the
9114 // teams regions arising from the teams construct.
9115 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9116 // A list item that appears in a reduction clause of a teams construct
9117 // must not appear in a firstprivate clause on a distribute construct if
9118 // any of the distribute regions arising from the distribute construct
9119 // ever bind to any of the teams regions arising from the teams construct.
9120 if ((isOpenMPWorksharingDirective(CurrDir) ||
9121 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009122 !isOpenMPParallelDirective(CurrDir) &&
9123 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009124 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009125 if (DVar.CKind != OMPC_shared &&
9126 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009127 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009128 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00009129 Diag(ELoc, diag::err_omp_required_access)
9130 << getOpenMPClauseName(OMPC_firstprivate)
9131 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009132 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009133 continue;
9134 }
9135 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009136 // OpenMP [2.9.3.4, Restrictions, p.3]
9137 // A list item that appears in a reduction clause of a parallel construct
9138 // must not appear in a firstprivate clause on a worksharing or task
9139 // construct if any of the worksharing or task regions arising from the
9140 // worksharing or task construct ever bind to any of the parallel regions
9141 // arising from the parallel construct.
9142 // OpenMP [2.9.3.4, Restrictions, p.4]
9143 // A list item that appears in a reduction clause in worksharing
9144 // construct must not appear in a firstprivate clause in a task construct
9145 // encountered during execution of any of the worksharing regions arising
9146 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00009147 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009148 DVar = DSAStack->hasInnermostDSA(
9149 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
9150 [](OpenMPDirectiveKind K) -> bool {
9151 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009152 isOpenMPWorksharingDirective(K) ||
9153 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009154 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009155 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009156 if (DVar.CKind == OMPC_reduction &&
9157 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009158 isOpenMPWorksharingDirective(DVar.DKind) ||
9159 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009160 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
9161 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009162 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009163 continue;
9164 }
9165 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009166
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009167 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9168 // A list item cannot appear in both a map clause and a data-sharing
9169 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00009170 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00009171 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00009172 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00009173 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00009174 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00009175 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00009176 CurrDir == OMPD_target_parallel_for_simd ||
9177 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00009178 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009179 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009180 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009181 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9182 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9183 ConflictKind = WhereFoundClauseKind;
9184 return true;
9185 })) {
9186 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009187 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00009188 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009189 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9190 ReportOriginalDSA(*this, DSAStack, D, DVar);
9191 continue;
9192 }
9193 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009194 }
9195
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009196 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009197 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00009198 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009199 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9200 << getOpenMPClauseName(OMPC_firstprivate) << Type
9201 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9202 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009203 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009204 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009205 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009206 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00009207 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009208 continue;
9209 }
9210
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009211 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009212 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9213 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009214 // Generate helper private variable and initialize it with the value of the
9215 // original variable. The address of the original variable is replaced by
9216 // the address of the new private variable in the CodeGen. This new variable
9217 // is not added to IdResolver, so the code in the OpenMP region uses
9218 // original variable for proper diagnostics and variable capturing.
9219 Expr *VDInitRefExpr = nullptr;
9220 // For arrays generate initializer for single element and replace it by the
9221 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009222 if (Type->isArrayType()) {
9223 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009224 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009225 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009226 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009227 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009228 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009229 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00009230 InitializedEntity Entity =
9231 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009232 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
9233
9234 InitializationSequence InitSeq(*this, Entity, Kind, Init);
9235 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
9236 if (Result.isInvalid())
9237 VDPrivate->setInvalidDecl();
9238 else
9239 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009240 // Remove temp variable declaration.
9241 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009242 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009243 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
9244 ".firstprivate.temp");
9245 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
9246 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00009247 AddInitializerToDecl(VDPrivate,
9248 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009249 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009250 }
9251 if (VDPrivate->isInvalidDecl()) {
9252 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009253 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009254 diag::note_omp_task_predetermined_firstprivate_here);
9255 }
9256 continue;
9257 }
9258 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009259 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00009260 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
9261 RefExpr->getExprLoc());
9262 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009263 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009264 if (TopDVar.CKind == OMPC_lastprivate)
9265 Ref = TopDVar.PrivateCopy;
9266 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009267 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00009268 if (!IsOpenMPCapturedDecl(D))
9269 ExprCaptures.push_back(Ref->getDecl());
9270 }
Alexey Bataev417089f2016-02-17 13:19:37 +00009271 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009272 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009273 Vars.push_back((VD || CurContext->isDependentContext())
9274 ? RefExpr->IgnoreParens()
9275 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009276 PrivateCopies.push_back(VDPrivateRefExpr);
9277 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009278 }
9279
Alexey Bataeved09d242014-05-28 05:53:51 +00009280 if (Vars.empty())
9281 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009282
9283 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009284 Vars, PrivateCopies, Inits,
9285 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009286}
9287
Alexander Musman1bb328c2014-06-04 13:06:39 +00009288OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9289 SourceLocation StartLoc,
9290 SourceLocation LParenLoc,
9291 SourceLocation EndLoc) {
9292 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00009293 SmallVector<Expr *, 8> SrcExprs;
9294 SmallVector<Expr *, 8> DstExprs;
9295 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00009296 SmallVector<Decl *, 4> ExprCaptures;
9297 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009298 for (auto &RefExpr : VarList) {
9299 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009300 SourceLocation ELoc;
9301 SourceRange ERange;
9302 Expr *SimpleRefExpr = RefExpr;
9303 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009304 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00009305 // It will be analyzed later.
9306 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00009307 SrcExprs.push_back(nullptr);
9308 DstExprs.push_back(nullptr);
9309 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009310 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009311 ValueDecl *D = Res.first;
9312 if (!D)
9313 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009314
Alexey Bataev74caaf22016-02-20 04:09:36 +00009315 QualType Type = D->getType();
9316 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009317
9318 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
9319 // A variable that appears in a lastprivate clause must not have an
9320 // incomplete type or a reference type.
9321 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00009322 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00009323 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009324 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009325
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009326 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009327 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9328 // in a Construct]
9329 // Variables with the predetermined data-sharing attributes may not be
9330 // listed in data-sharing attributes clauses, except for the cases
9331 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009332 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9333 // A list item may appear in a firstprivate or lastprivate clause but not
9334 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009335 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009336 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009337 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00009338 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
9339 Diag(ELoc, diag::err_omp_wrong_dsa)
9340 << getOpenMPClauseName(DVar.CKind)
9341 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009342 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009343 continue;
9344 }
9345
Alexey Bataevf29276e2014-06-18 04:14:57 +00009346 // OpenMP [2.14.3.5, Restrictions, p.2]
9347 // A list item that is private within a parallel region, or that appears in
9348 // the reduction clause of a parallel construct, must not appear in a
9349 // lastprivate clause on a worksharing construct if any of the corresponding
9350 // worksharing regions ever binds to any of the corresponding parallel
9351 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00009352 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00009353 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009354 !isOpenMPParallelDirective(CurrDir) &&
9355 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00009356 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009357 if (DVar.CKind != OMPC_shared) {
9358 Diag(ELoc, diag::err_omp_required_access)
9359 << getOpenMPClauseName(OMPC_lastprivate)
9360 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009361 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009362 continue;
9363 }
9364 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009365
Alexander Musman1bb328c2014-06-04 13:06:39 +00009366 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00009367 // A variable of class type (or array thereof) that appears in a
9368 // lastprivate clause requires an accessible, unambiguous default
9369 // constructor for the class type, unless the list item is also specified
9370 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00009371 // A variable of class type (or array thereof) that appears in a
9372 // lastprivate clause requires an accessible, unambiguous copy assignment
9373 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00009374 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009375 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009376 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009377 D->hasAttrs() ? &D->getAttrs() : nullptr);
9378 auto *PseudoSrcExpr =
9379 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009380 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009381 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009382 D->hasAttrs() ? &D->getAttrs() : nullptr);
9383 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009384 // For arrays generate assignment operation for single element and replace
9385 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009386 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00009387 PseudoDstExpr, PseudoSrcExpr);
9388 if (AssignmentOp.isInvalid())
9389 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00009390 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00009391 /*DiscardedValue=*/true);
9392 if (AssignmentOp.isInvalid())
9393 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009394
Alexey Bataev74caaf22016-02-20 04:09:36 +00009395 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009396 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009397 if (TopDVar.CKind == OMPC_firstprivate)
9398 Ref = TopDVar.PrivateCopy;
9399 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009400 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009401 if (!IsOpenMPCapturedDecl(D))
9402 ExprCaptures.push_back(Ref->getDecl());
9403 }
9404 if (TopDVar.CKind == OMPC_firstprivate ||
9405 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009406 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009407 ExprResult RefRes = DefaultLvalueConversion(Ref);
9408 if (!RefRes.isUsable())
9409 continue;
9410 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009411 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9412 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009413 if (!PostUpdateRes.isUsable())
9414 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009415 ExprPostUpdates.push_back(
9416 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009417 }
9418 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009419 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009420 Vars.push_back((VD || CurContext->isDependentContext())
9421 ? RefExpr->IgnoreParens()
9422 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00009423 SrcExprs.push_back(PseudoSrcExpr);
9424 DstExprs.push_back(PseudoDstExpr);
9425 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00009426 }
9427
9428 if (Vars.empty())
9429 return nullptr;
9430
9431 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00009432 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009433 buildPreInits(Context, ExprCaptures),
9434 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00009435}
9436
Alexey Bataev758e55e2013-09-06 18:03:48 +00009437OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9438 SourceLocation StartLoc,
9439 SourceLocation LParenLoc,
9440 SourceLocation EndLoc) {
9441 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00009442 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009443 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009444 SourceLocation ELoc;
9445 SourceRange ERange;
9446 Expr *SimpleRefExpr = RefExpr;
9447 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009448 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00009449 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009450 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009451 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009452 ValueDecl *D = Res.first;
9453 if (!D)
9454 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009455
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009456 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009457 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9458 // in a Construct]
9459 // Variables with the predetermined data-sharing attributes may not be
9460 // listed in data-sharing attributes clauses, except for the cases
9461 // listed below. For these exceptions only, listing a predetermined
9462 // variable in a data-sharing attribute clause is allowed and overrides
9463 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009464 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00009465 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9466 DVar.RefExpr) {
9467 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9468 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009469 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009470 continue;
9471 }
9472
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009473 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009474 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009475 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009476 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009477 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9478 ? RefExpr->IgnoreParens()
9479 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009480 }
9481
Alexey Bataeved09d242014-05-28 05:53:51 +00009482 if (Vars.empty())
9483 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009484
9485 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9486}
9487
Alexey Bataevc5e02582014-06-16 07:08:35 +00009488namespace {
9489class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9490 DSAStackTy *Stack;
9491
9492public:
9493 bool VisitDeclRefExpr(DeclRefExpr *E) {
9494 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009495 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009496 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9497 return false;
9498 if (DVar.CKind != OMPC_unknown)
9499 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009500 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9501 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009502 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009503 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009504 return true;
9505 return false;
9506 }
9507 return false;
9508 }
9509 bool VisitStmt(Stmt *S) {
9510 for (auto Child : S->children()) {
9511 if (Child && Visit(Child))
9512 return true;
9513 }
9514 return false;
9515 }
Alexey Bataev23b69422014-06-18 07:08:49 +00009516 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009517};
Alexey Bataev23b69422014-06-18 07:08:49 +00009518} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00009519
Alexey Bataev60da77e2016-02-29 05:54:20 +00009520namespace {
9521// Transform MemberExpression for specified FieldDecl of current class to
9522// DeclRefExpr to specified OMPCapturedExprDecl.
9523class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9524 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9525 ValueDecl *Field;
9526 DeclRefExpr *CapturedExpr;
9527
9528public:
9529 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9530 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9531
9532 ExprResult TransformMemberExpr(MemberExpr *E) {
9533 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9534 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00009535 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009536 return CapturedExpr;
9537 }
9538 return BaseTransform::TransformMemberExpr(E);
9539 }
9540 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9541};
9542} // namespace
9543
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009544template <typename T>
9545static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9546 const llvm::function_ref<T(ValueDecl *)> &Gen) {
9547 for (auto &Set : Lookups) {
9548 for (auto *D : Set) {
9549 if (auto Res = Gen(cast<ValueDecl>(D)))
9550 return Res;
9551 }
9552 }
9553 return T();
9554}
9555
9556static ExprResult
9557buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9558 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9559 const DeclarationNameInfo &ReductionId, QualType Ty,
9560 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9561 if (ReductionIdScopeSpec.isInvalid())
9562 return ExprError();
9563 SmallVector<UnresolvedSet<8>, 4> Lookups;
9564 if (S) {
9565 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9566 Lookup.suppressDiagnostics();
9567 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9568 auto *D = Lookup.getRepresentativeDecl();
9569 do {
9570 S = S->getParent();
9571 } while (S && !S->isDeclScope(D));
9572 if (S)
9573 S = S->getParent();
9574 Lookups.push_back(UnresolvedSet<8>());
9575 Lookups.back().append(Lookup.begin(), Lookup.end());
9576 Lookup.clear();
9577 }
9578 } else if (auto *ULE =
9579 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9580 Lookups.push_back(UnresolvedSet<8>());
9581 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00009582 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009583 if (D == PrevD)
9584 Lookups.push_back(UnresolvedSet<8>());
9585 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9586 Lookups.back().addDecl(DRD);
9587 PrevD = D;
9588 }
9589 }
Alexey Bataevfdc20352017-08-25 15:43:55 +00009590 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9591 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009592 Ty->containsUnexpandedParameterPack() ||
9593 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9594 return !D->isInvalidDecl() &&
9595 (D->getType()->isDependentType() ||
9596 D->getType()->isInstantiationDependentType() ||
9597 D->getType()->containsUnexpandedParameterPack());
9598 })) {
9599 UnresolvedSet<8> ResSet;
9600 for (auto &Set : Lookups) {
9601 ResSet.append(Set.begin(), Set.end());
9602 // The last item marks the end of all declarations at the specified scope.
9603 ResSet.addDecl(Set[Set.size() - 1]);
9604 }
9605 return UnresolvedLookupExpr::Create(
9606 SemaRef.Context, /*NamingClass=*/nullptr,
9607 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9608 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9609 }
9610 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9611 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9612 if (!D->isInvalidDecl() &&
9613 SemaRef.Context.hasSameType(D->getType(), Ty))
9614 return D;
9615 return nullptr;
9616 }))
9617 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9618 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9619 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9620 if (!D->isInvalidDecl() &&
9621 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9622 !Ty.isMoreQualifiedThan(D->getType()))
9623 return D;
9624 return nullptr;
9625 })) {
9626 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9627 /*DetectVirtual=*/false);
9628 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9629 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9630 VD->getType().getUnqualifiedType()))) {
9631 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
9632 /*DiagID=*/0) !=
9633 Sema::AR_inaccessible) {
9634 SemaRef.BuildBasePathArray(Paths, BasePath);
9635 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9636 }
9637 }
9638 }
9639 }
9640 if (ReductionIdScopeSpec.isSet()) {
9641 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
9642 return ExprError();
9643 }
9644 return ExprEmpty();
9645}
9646
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009647namespace {
9648/// Data for the reduction-based clauses.
9649struct ReductionData {
9650 /// List of original reduction items.
9651 SmallVector<Expr *, 8> Vars;
9652 /// List of private copies of the reduction items.
9653 SmallVector<Expr *, 8> Privates;
9654 /// LHS expressions for the reduction_op expressions.
9655 SmallVector<Expr *, 8> LHSs;
9656 /// RHS expressions for the reduction_op expressions.
9657 SmallVector<Expr *, 8> RHSs;
9658 /// Reduction operation expression.
9659 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +00009660 /// Taskgroup descriptors for the corresponding reduction items in
9661 /// in_reduction clauses.
9662 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009663 /// List of captures for clause.
9664 SmallVector<Decl *, 4> ExprCaptures;
9665 /// List of postupdate expressions.
9666 SmallVector<Expr *, 4> ExprPostUpdates;
9667 ReductionData() = delete;
9668 /// Reserves required memory for the reduction data.
9669 ReductionData(unsigned Size) {
9670 Vars.reserve(Size);
9671 Privates.reserve(Size);
9672 LHSs.reserve(Size);
9673 RHSs.reserve(Size);
9674 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +00009675 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009676 ExprCaptures.reserve(Size);
9677 ExprPostUpdates.reserve(Size);
9678 }
9679 /// Stores reduction item and reduction operation only (required for dependent
9680 /// reduction item).
9681 void push(Expr *Item, Expr *ReductionOp) {
9682 Vars.emplace_back(Item);
9683 Privates.emplace_back(nullptr);
9684 LHSs.emplace_back(nullptr);
9685 RHSs.emplace_back(nullptr);
9686 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009687 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009688 }
9689 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +00009690 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
9691 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009692 Vars.emplace_back(Item);
9693 Privates.emplace_back(Private);
9694 LHSs.emplace_back(LHS);
9695 RHSs.emplace_back(RHS);
9696 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009697 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009698 }
9699};
9700} // namespace
9701
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00009702static bool CheckOMPArraySectionConstantForReduction(
9703 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
9704 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
9705 const Expr *Length = OASE->getLength();
9706 if (Length == nullptr) {
9707 // For array sections of the form [1:] or [:], we would need to analyze
9708 // the lower bound...
9709 if (OASE->getColonLoc().isValid())
9710 return false;
9711
9712 // This is an array subscript which has implicit length 1!
9713 SingleElement = true;
9714 ArraySizes.push_back(llvm::APSInt::get(1));
9715 } else {
9716 llvm::APSInt ConstantLengthValue;
9717 if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
9718 return false;
9719
9720 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
9721 ArraySizes.push_back(ConstantLengthValue);
9722 }
9723
9724 // Get the base of this array section and walk up from there.
9725 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
9726
9727 // We require length = 1 for all array sections except the right-most to
9728 // guarantee that the memory region is contiguous and has no holes in it.
9729 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
9730 Length = TempOASE->getLength();
9731 if (Length == nullptr) {
9732 // For array sections of the form [1:] or [:], we would need to analyze
9733 // the lower bound...
9734 if (OASE->getColonLoc().isValid())
9735 return false;
9736
9737 // This is an array subscript which has implicit length 1!
9738 ArraySizes.push_back(llvm::APSInt::get(1));
9739 } else {
9740 llvm::APSInt ConstantLengthValue;
9741 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
9742 ConstantLengthValue.getSExtValue() != 1)
9743 return false;
9744
9745 ArraySizes.push_back(ConstantLengthValue);
9746 }
9747 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9748 }
9749
9750 // If we have a single element, we don't need to add the implicit lengths.
9751 if (!SingleElement) {
9752 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
9753 // Has implicit length 1!
9754 ArraySizes.push_back(llvm::APSInt::get(1));
9755 Base = TempASE->getBase()->IgnoreParenImpCasts();
9756 }
9757 }
9758
9759 // This array section can be privatized as a single value or as a constant
9760 // sized array.
9761 return true;
9762}
9763
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009764static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +00009765 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
9766 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9767 SourceLocation ColonLoc, SourceLocation EndLoc,
9768 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009769 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009770 auto DN = ReductionId.getName();
9771 auto OOK = DN.getCXXOverloadedOperator();
9772 BinaryOperatorKind BOK = BO_Comma;
9773
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009774 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009775 // OpenMP [2.14.3.6, reduction clause]
9776 // C
9777 // reduction-identifier is either an identifier or one of the following
9778 // operators: +, -, *, &, |, ^, && and ||
9779 // C++
9780 // reduction-identifier is either an id-expression or one of the following
9781 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +00009782 switch (OOK) {
9783 case OO_Plus:
9784 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009785 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009786 break;
9787 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009788 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009789 break;
9790 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009791 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009792 break;
9793 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009794 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009795 break;
9796 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009797 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009798 break;
9799 case OO_AmpAmp:
9800 BOK = BO_LAnd;
9801 break;
9802 case OO_PipePipe:
9803 BOK = BO_LOr;
9804 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009805 case OO_New:
9806 case OO_Delete:
9807 case OO_Array_New:
9808 case OO_Array_Delete:
9809 case OO_Slash:
9810 case OO_Percent:
9811 case OO_Tilde:
9812 case OO_Exclaim:
9813 case OO_Equal:
9814 case OO_Less:
9815 case OO_Greater:
9816 case OO_LessEqual:
9817 case OO_GreaterEqual:
9818 case OO_PlusEqual:
9819 case OO_MinusEqual:
9820 case OO_StarEqual:
9821 case OO_SlashEqual:
9822 case OO_PercentEqual:
9823 case OO_CaretEqual:
9824 case OO_AmpEqual:
9825 case OO_PipeEqual:
9826 case OO_LessLess:
9827 case OO_GreaterGreater:
9828 case OO_LessLessEqual:
9829 case OO_GreaterGreaterEqual:
9830 case OO_EqualEqual:
9831 case OO_ExclaimEqual:
9832 case OO_PlusPlus:
9833 case OO_MinusMinus:
9834 case OO_Comma:
9835 case OO_ArrowStar:
9836 case OO_Arrow:
9837 case OO_Call:
9838 case OO_Subscript:
9839 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00009840 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009841 case NUM_OVERLOADED_OPERATORS:
9842 llvm_unreachable("Unexpected reduction identifier");
9843 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009844 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009845 if (II->isStr("max"))
9846 BOK = BO_GT;
9847 else if (II->isStr("min"))
9848 BOK = BO_LT;
9849 }
9850 break;
9851 }
9852 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009853 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00009854 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009855 else
9856 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009857 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009858
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009859 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
9860 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009861 for (auto RefExpr : VarList) {
9862 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00009863 // OpenMP [2.1, C/C++]
9864 // A list item is a variable or array section, subject to the restrictions
9865 // specified in Section 2.4 on page 42 and in each of the sections
9866 // describing clauses and directives for which a list appears.
9867 // OpenMP [2.14.3.3, Restrictions, p.1]
9868 // A variable that is part of another variable (as an array or
9869 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009870 if (!FirstIter && IR != ER)
9871 ++IR;
9872 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009873 SourceLocation ELoc;
9874 SourceRange ERange;
9875 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009876 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +00009877 /*AllowArraySection=*/true);
9878 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009879 // Try to find 'declare reduction' corresponding construct before using
9880 // builtin/overloaded operators.
9881 QualType Type = Context.DependentTy;
9882 CXXCastPath BasePath;
9883 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009884 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009885 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009886 Expr *ReductionOp = nullptr;
9887 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009888 (DeclareReductionRef.isUnset() ||
9889 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009890 ReductionOp = DeclareReductionRef.get();
9891 // It will be analyzed later.
9892 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009893 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009894 ValueDecl *D = Res.first;
9895 if (!D)
9896 continue;
9897
Alexey Bataev88202be2017-07-27 13:20:36 +00009898 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +00009899 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009900 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
9901 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
9902 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00009903 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009904 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009905 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
9906 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
9907 Type = ATy->getElementType();
9908 else
9909 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00009910 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009911 } else
9912 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9913 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00009914
Alexey Bataevc5e02582014-06-16 07:08:35 +00009915 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9916 // A variable that appears in a private clause must not have an incomplete
9917 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009918 if (S.RequireCompleteType(ELoc, Type,
9919 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +00009920 continue;
9921 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00009922 // A list item that appears in a reduction clause must not be
9923 // const-qualified.
9924 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009925 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009926 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009927 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9928 VarDecl::DeclarationOnly;
9929 S.Diag(D->getLocation(),
9930 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009931 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00009932 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009933 continue;
9934 }
9935 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
9936 // If a list-item is a reference type then it must bind to the same object
9937 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009938 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009939 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00009940 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009941 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +00009942 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009943 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
9944 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009945 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +00009946 continue;
9947 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009948 }
9949 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009950
Alexey Bataevc5e02582014-06-16 07:08:35 +00009951 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9952 // in a Construct]
9953 // Variables with the predetermined data-sharing attributes may not be
9954 // listed in data-sharing attributes clauses, except for the cases
9955 // listed below. For these exceptions only, listing a predetermined
9956 // variable in a data-sharing attribute clause is allowed and overrides
9957 // the variable's predetermined data-sharing attributes.
9958 // OpenMP [2.14.3.6, Restrictions, p.3]
9959 // Any number of reduction clauses can be specified on the directive,
9960 // but a list item can appear only once in the reduction clauses for that
9961 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00009962 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009963 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009964 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009965 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009966 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009967 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009968 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009969 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009970 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009971 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009972 << getOpenMPClauseName(DVar.CKind)
9973 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009974 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009975 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009976 }
9977
9978 // OpenMP [2.14.3.6, Restrictions, p.1]
9979 // A list item that appears in a reduction clause of a worksharing
9980 // construct must be shared in the parallel regions to which any of the
9981 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009982 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009983 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009984 !isOpenMPParallelDirective(CurrDir) &&
9985 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009986 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009987 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009988 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009989 << getOpenMPClauseName(OMPC_reduction)
9990 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009991 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009992 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00009993 }
9994 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009995
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009996 // Try to find 'declare reduction' corresponding construct before using
9997 // builtin/overloaded operators.
9998 CXXCastPath BasePath;
9999 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010000 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010001 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10002 if (DeclareReductionRef.isInvalid())
10003 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010004 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010005 (DeclareReductionRef.isUnset() ||
10006 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010007 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010008 continue;
10009 }
10010 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
10011 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010012 S.Diag(ReductionId.getLocStart(),
10013 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010014 << Type << ReductionIdRange;
10015 continue;
10016 }
10017
10018 // OpenMP [2.14.3.6, reduction clause, Restrictions]
10019 // The type of a list item that appears in a reduction clause must be valid
10020 // for the reduction-identifier. For a max or min reduction in C, the type
10021 // of the list item must be an allowed arithmetic data type: char, int,
10022 // float, double, or _Bool, possibly modified with long, short, signed, or
10023 // unsigned. For a max or min reduction in C++, the type of the list item
10024 // must be an allowed arithmetic data type: char, wchar_t, int, float,
10025 // double, or bool, possibly modified with long, short, signed, or unsigned.
10026 if (DeclareReductionRef.isUnset()) {
10027 if ((BOK == BO_GT || BOK == BO_LT) &&
10028 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010029 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
10030 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010031 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010032 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010033 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10034 VarDecl::DeclarationOnly;
10035 S.Diag(D->getLocation(),
10036 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010037 << D;
10038 }
10039 continue;
10040 }
10041 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010042 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010043 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
10044 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010045 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010046 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10047 VarDecl::DeclarationOnly;
10048 S.Diag(D->getLocation(),
10049 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010050 << D;
10051 }
10052 continue;
10053 }
10054 }
10055
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010056 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010057 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +000010058 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010059 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010060 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010061 auto PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010062
10063 // Try if we can determine constant lengths for all array sections and avoid
10064 // the VLA.
10065 bool ConstantLengthOASE = false;
10066 if (OASE) {
10067 bool SingleElement;
10068 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
10069 ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
10070 Context, OASE, SingleElement, ArraySizes);
10071
10072 // If we don't have a single element, we must emit a constant array type.
10073 if (ConstantLengthOASE && !SingleElement) {
10074 for (auto &Size : ArraySizes) {
10075 PrivateTy = Context.getConstantArrayType(
10076 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
10077 }
10078 }
10079 }
10080
10081 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000010082 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000010083 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000010084 if (!Context.getTargetInfo().isVLASupported() &&
10085 S.shouldDiagnoseTargetSupportFromOpenMP()) {
10086 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
10087 S.Diag(ELoc, diag::note_vla_unsupported);
10088 continue;
10089 }
David Majnemer9d168222016-08-05 17:44:54 +000010090 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010091 // Create pseudo array type for private copy. The size for this array will
10092 // be generated during codegen.
10093 // For array subscripts or single variables Private Ty is the same as Type
10094 // (type of the variable or single array element).
10095 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010096 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000010097 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010098 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000010099 } else if (!ASE && !OASE &&
10100 Context.getAsArrayType(D->getType().getNonReferenceType()))
10101 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010102 // Private copy.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010103 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010104 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010105 // Add initializer for private variable.
10106 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010107 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
10108 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010109 if (DeclareReductionRef.isUsable()) {
10110 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
10111 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
10112 if (DRD->getInitializer()) {
10113 Init = DRDRef;
10114 RHSVD->setInit(DRDRef);
10115 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010116 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010117 } else {
10118 switch (BOK) {
10119 case BO_Add:
10120 case BO_Xor:
10121 case BO_Or:
10122 case BO_LOr:
10123 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
10124 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010125 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010126 break;
10127 case BO_Mul:
10128 case BO_LAnd:
10129 if (Type->isScalarType() || Type->isAnyComplexType()) {
10130 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010131 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000010132 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010133 break;
10134 case BO_And: {
10135 // '&' reduction op - initializer is '~0'.
10136 QualType OrigType = Type;
10137 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
10138 Type = ComplexTy->getElementType();
10139 if (Type->isRealFloatingType()) {
10140 llvm::APFloat InitValue =
10141 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
10142 /*isIEEE=*/true);
10143 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10144 Type, ELoc);
10145 } else if (Type->isScalarType()) {
10146 auto Size = Context.getTypeSize(Type);
10147 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
10148 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
10149 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10150 }
10151 if (Init && OrigType->isAnyComplexType()) {
10152 // Init = 0xFFFF + 0xFFFFi;
10153 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010154 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010155 }
10156 Type = OrigType;
10157 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010158 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010159 case BO_LT:
10160 case BO_GT: {
10161 // 'min' reduction op - initializer is 'Largest representable number in
10162 // the reduction list item type'.
10163 // 'max' reduction op - initializer is 'Least representable number in
10164 // the reduction list item type'.
10165 if (Type->isIntegerType() || Type->isPointerType()) {
10166 bool IsSigned = Type->hasSignedIntegerRepresentation();
10167 auto Size = Context.getTypeSize(Type);
10168 QualType IntTy =
10169 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
10170 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010171 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
10172 : llvm::APInt::getMinValue(Size)
10173 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
10174 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010175 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10176 if (Type->isPointerType()) {
10177 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010178 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000010179 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010180 if (CastExpr.isInvalid())
10181 continue;
10182 Init = CastExpr.get();
10183 }
10184 } else if (Type->isRealFloatingType()) {
10185 llvm::APFloat InitValue = llvm::APFloat::getLargest(
10186 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
10187 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10188 Type, ELoc);
10189 }
10190 break;
10191 }
10192 case BO_PtrMemD:
10193 case BO_PtrMemI:
10194 case BO_MulAssign:
10195 case BO_Div:
10196 case BO_Rem:
10197 case BO_Sub:
10198 case BO_Shl:
10199 case BO_Shr:
10200 case BO_LE:
10201 case BO_GE:
10202 case BO_EQ:
10203 case BO_NE:
10204 case BO_AndAssign:
10205 case BO_XorAssign:
10206 case BO_OrAssign:
10207 case BO_Assign:
10208 case BO_AddAssign:
10209 case BO_SubAssign:
10210 case BO_DivAssign:
10211 case BO_RemAssign:
10212 case BO_ShlAssign:
10213 case BO_ShrAssign:
10214 case BO_Comma:
10215 llvm_unreachable("Unexpected reduction operation");
10216 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010217 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010218 if (Init && DeclareReductionRef.isUnset())
10219 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
10220 else if (!Init)
10221 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010222 if (RHSVD->isInvalidDecl())
10223 continue;
10224 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010225 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
10226 << Type << ReductionIdRange;
10227 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10228 VarDecl::DeclarationOnly;
10229 S.Diag(D->getLocation(),
10230 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010231 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010232 continue;
10233 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010234 // Store initializer for single element in private copy. Will be used during
10235 // codegen.
10236 PrivateVD->setInit(RHSVD->getInit());
10237 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010238 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010239 ExprResult ReductionOp;
10240 if (DeclareReductionRef.isUsable()) {
10241 QualType RedTy = DeclareReductionRef.get()->getType();
10242 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010243 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
10244 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010245 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010246 LHS = S.DefaultLvalueConversion(LHS.get());
10247 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010248 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10249 CK_UncheckedDerivedToBase, LHS.get(),
10250 &BasePath, LHS.get()->getValueKind());
10251 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10252 CK_UncheckedDerivedToBase, RHS.get(),
10253 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010254 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010255 FunctionProtoType::ExtProtoInfo EPI;
10256 QualType Params[] = {PtrRedTy, PtrRedTy};
10257 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
10258 auto *OVE = new (Context) OpaqueValueExpr(
10259 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010260 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010261 Expr *Args[] = {LHS.get(), RHS.get()};
10262 ReductionOp = new (Context)
10263 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
10264 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010265 ReductionOp = S.BuildBinOp(
10266 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010267 if (ReductionOp.isUsable()) {
10268 if (BOK != BO_LT && BOK != BO_GT) {
10269 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010270 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10271 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010272 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000010273 auto *ConditionalOp = new (Context)
10274 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
10275 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010276 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010277 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10278 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010279 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010280 if (ReductionOp.isUsable())
10281 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010282 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010283 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010284 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010285 }
10286
Alexey Bataevfa312f32017-07-21 18:48:21 +000010287 // OpenMP [2.15.4.6, Restrictions, p.2]
10288 // A list item that appears in an in_reduction clause of a task construct
10289 // must appear in a task_reduction clause of a construct associated with a
10290 // taskgroup region that includes the participating task in its taskgroup
10291 // set. The construct associated with the innermost region that meets this
10292 // condition must specify the same reduction-identifier as the in_reduction
10293 // clause.
10294 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000010295 SourceRange ParentSR;
10296 BinaryOperatorKind ParentBOK;
10297 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000010298 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000010299 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010300 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
10301 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010302 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010303 Stack->getTopMostTaskgroupReductionData(
10304 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010305 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
10306 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
10307 if (!IsParentBOK && !IsParentReductionOp) {
10308 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
10309 continue;
10310 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000010311 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
10312 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
10313 IsParentReductionOp) {
10314 bool EmitError = true;
10315 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
10316 llvm::FoldingSetNodeID RedId, ParentRedId;
10317 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
10318 DeclareReductionRef.get()->Profile(RedId, Context,
10319 /*Canonical=*/true);
10320 EmitError = RedId != ParentRedId;
10321 }
10322 if (EmitError) {
10323 S.Diag(ReductionId.getLocStart(),
10324 diag::err_omp_reduction_identifier_mismatch)
10325 << ReductionIdRange << RefExpr->getSourceRange();
10326 S.Diag(ParentSR.getBegin(),
10327 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000010328 << ParentSR
10329 << (IsParentBOK ? ParentBOKDSA.RefExpr
10330 : ParentReductionOpDSA.RefExpr)
10331 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000010332 continue;
10333 }
10334 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010335 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
10336 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000010337 }
10338
Alexey Bataev60da77e2016-02-29 05:54:20 +000010339 DeclRefExpr *Ref = nullptr;
10340 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010341 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010342 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010343 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010344 VarsExpr =
10345 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
10346 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000010347 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010348 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010349 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010350 if (!S.IsOpenMPCapturedDecl(D)) {
10351 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010352 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010353 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010354 if (!RefRes.isUsable())
10355 continue;
10356 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010357 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10358 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010359 if (!PostUpdateRes.isUsable())
10360 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010361 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
10362 Stack->getCurrentDirective() == OMPD_taskgroup) {
10363 S.Diag(RefExpr->getExprLoc(),
10364 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000010365 << RefExpr->getSourceRange();
10366 continue;
10367 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010368 RD.ExprPostUpdates.emplace_back(
10369 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000010370 }
10371 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010372 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000010373 // All reduction items are still marked as reduction (to do not increase
10374 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010375 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010376 if (CurrDir == OMPD_taskgroup) {
10377 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010378 Stack->addTaskgroupReductionData(D, ReductionIdRange,
10379 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000010380 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010381 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010382 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010383 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10384 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010385 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010386 return RD.Vars.empty();
10387}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010388
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010389OMPClause *Sema::ActOnOpenMPReductionClause(
10390 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10391 SourceLocation ColonLoc, SourceLocation EndLoc,
10392 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10393 ArrayRef<Expr *> UnresolvedReductions) {
10394 ReductionData RD(VarList.size());
10395
Alexey Bataev169d96a2017-07-18 20:17:46 +000010396 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
10397 StartLoc, LParenLoc, ColonLoc, EndLoc,
10398 ReductionIdScopeSpec, ReductionId,
10399 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010400 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000010401
Alexey Bataevc5e02582014-06-16 07:08:35 +000010402 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010403 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10404 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10405 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10406 buildPreInits(Context, RD.ExprCaptures),
10407 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000010408}
10409
Alexey Bataev169d96a2017-07-18 20:17:46 +000010410OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10411 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10412 SourceLocation ColonLoc, SourceLocation EndLoc,
10413 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10414 ArrayRef<Expr *> UnresolvedReductions) {
10415 ReductionData RD(VarList.size());
10416
10417 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
10418 VarList, StartLoc, LParenLoc, ColonLoc,
10419 EndLoc, ReductionIdScopeSpec, ReductionId,
10420 UnresolvedReductions, RD))
10421 return nullptr;
10422
10423 return OMPTaskReductionClause::Create(
10424 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10425 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10426 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10427 buildPreInits(Context, RD.ExprCaptures),
10428 buildPostUpdate(*this, RD.ExprPostUpdates));
10429}
10430
Alexey Bataevfa312f32017-07-21 18:48:21 +000010431OMPClause *Sema::ActOnOpenMPInReductionClause(
10432 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10433 SourceLocation ColonLoc, SourceLocation EndLoc,
10434 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10435 ArrayRef<Expr *> UnresolvedReductions) {
10436 ReductionData RD(VarList.size());
10437
10438 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
10439 StartLoc, LParenLoc, ColonLoc, EndLoc,
10440 ReductionIdScopeSpec, ReductionId,
10441 UnresolvedReductions, RD))
10442 return nullptr;
10443
10444 return OMPInReductionClause::Create(
10445 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10446 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000010447 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000010448 buildPreInits(Context, RD.ExprCaptures),
10449 buildPostUpdate(*this, RD.ExprPostUpdates));
10450}
10451
Alexey Bataevecba70f2016-04-12 11:02:11 +000010452bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10453 SourceLocation LinLoc) {
10454 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10455 LinKind == OMPC_LINEAR_unknown) {
10456 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10457 return true;
10458 }
10459 return false;
10460}
10461
10462bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
10463 OpenMPLinearClauseKind LinKind,
10464 QualType Type) {
10465 auto *VD = dyn_cast_or_null<VarDecl>(D);
10466 // A variable must not have an incomplete type or a reference type.
10467 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10468 return true;
10469 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10470 !Type->isReferenceType()) {
10471 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10472 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10473 return true;
10474 }
10475 Type = Type.getNonReferenceType();
10476
10477 // A list item must not be const-qualified.
10478 if (Type.isConstant(Context)) {
10479 Diag(ELoc, diag::err_omp_const_variable)
10480 << getOpenMPClauseName(OMPC_linear);
10481 if (D) {
10482 bool IsDecl =
10483 !VD ||
10484 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10485 Diag(D->getLocation(),
10486 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10487 << D;
10488 }
10489 return true;
10490 }
10491
10492 // A list item must be of integral or pointer type.
10493 Type = Type.getUnqualifiedType().getCanonicalType();
10494 const auto *Ty = Type.getTypePtrOrNull();
10495 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10496 !Ty->isPointerType())) {
10497 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10498 if (D) {
10499 bool IsDecl =
10500 !VD ||
10501 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10502 Diag(D->getLocation(),
10503 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10504 << D;
10505 }
10506 return true;
10507 }
10508 return false;
10509}
10510
Alexey Bataev182227b2015-08-20 10:54:39 +000010511OMPClause *Sema::ActOnOpenMPLinearClause(
10512 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10513 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10514 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010515 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010516 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000010517 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010518 SmallVector<Decl *, 4> ExprCaptures;
10519 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010520 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000010521 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +000010522 for (auto &RefExpr : VarList) {
10523 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010524 SourceLocation ELoc;
10525 SourceRange ERange;
10526 Expr *SimpleRefExpr = RefExpr;
10527 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10528 /*AllowArraySection=*/false);
10529 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010530 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010531 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010532 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000010533 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000010534 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010535 ValueDecl *D = Res.first;
10536 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000010537 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000010538
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010539 QualType Type = D->getType();
10540 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000010541
10542 // OpenMP [2.14.3.7, linear clause]
10543 // A list-item cannot appear in more than one linear clause.
10544 // A list-item that appears in a linear clause cannot appear in any
10545 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010546 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +000010547 if (DVar.RefExpr) {
10548 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10549 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010550 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000010551 continue;
10552 }
10553
Alexey Bataevecba70f2016-04-12 11:02:11 +000010554 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000010555 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010556 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000010557
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010558 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010559 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
10560 D->hasAttrs() ? &D->getAttrs() : nullptr);
10561 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010562 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010563 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010564 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010565 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010566 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000010567 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10568 if (!IsOpenMPCapturedDecl(D)) {
10569 ExprCaptures.push_back(Ref->getDecl());
10570 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10571 ExprResult RefRes = DefaultLvalueConversion(Ref);
10572 if (!RefRes.isUsable())
10573 continue;
10574 ExprResult PostUpdateRes =
10575 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10576 SimpleRefExpr, RefRes.get());
10577 if (!PostUpdateRes.isUsable())
10578 continue;
10579 ExprPostUpdates.push_back(
10580 IgnoredValueConversions(PostUpdateRes.get()).get());
10581 }
10582 }
10583 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010584 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010585 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010586 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010587 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010588 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010589 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010590 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
10591
10592 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010593 Vars.push_back((VD || CurContext->isDependentContext())
10594 ? RefExpr->IgnoreParens()
10595 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010596 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000010597 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000010598 }
10599
10600 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010601 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010602
10603 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000010604 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010605 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
10606 !Step->isInstantiationDependent() &&
10607 !Step->containsUnexpandedParameterPack()) {
10608 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000010609 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000010610 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010611 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010612 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000010613
Alexander Musman3276a272015-03-21 10:12:56 +000010614 // Build var to save the step value.
10615 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010616 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000010617 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010618 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010619 ExprResult CalcStep =
10620 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010621 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +000010622
Alexander Musman8dba6642014-04-22 13:09:42 +000010623 // Warn about zero linear step (it would be probably better specified as
10624 // making corresponding variables 'const').
10625 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000010626 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
10627 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000010628 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
10629 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000010630 if (!IsConstant && CalcStep.isUsable()) {
10631 // Calculate the step beforehand instead of doing this on each iteration.
10632 // (This is not used if the number of iterations may be kfold-ed).
10633 CalcStepExpr = CalcStep.get();
10634 }
Alexander Musman8dba6642014-04-22 13:09:42 +000010635 }
10636
Alexey Bataev182227b2015-08-20 10:54:39 +000010637 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
10638 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010639 StepExpr, CalcStepExpr,
10640 buildPreInits(Context, ExprCaptures),
10641 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000010642}
10643
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010644static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
10645 Expr *NumIterations, Sema &SemaRef,
10646 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000010647 // Walk the vars and build update/final expressions for the CodeGen.
10648 SmallVector<Expr *, 8> Updates;
10649 SmallVector<Expr *, 8> Finals;
10650 Expr *Step = Clause.getStep();
10651 Expr *CalcStep = Clause.getCalcStep();
10652 // OpenMP [2.14.3.7, linear clause]
10653 // If linear-step is not specified it is assumed to be 1.
10654 if (Step == nullptr)
10655 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010656 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +000010657 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010658 }
Alexander Musman3276a272015-03-21 10:12:56 +000010659 bool HasErrors = false;
10660 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010661 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010662 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +000010663 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010664 SourceLocation ELoc;
10665 SourceRange ERange;
10666 Expr *SimpleRefExpr = RefExpr;
10667 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
10668 /*AllowArraySection=*/false);
10669 ValueDecl *D = Res.first;
10670 if (Res.second || !D) {
10671 Updates.push_back(nullptr);
10672 Finals.push_back(nullptr);
10673 HasErrors = true;
10674 continue;
10675 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010676 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +000010677 Expr *InitExpr = *CurInit;
10678
10679 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000010680 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010681 Expr *CapturedRef;
10682 if (LinKind == OMPC_LINEAR_uval)
10683 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
10684 else
10685 CapturedRef =
10686 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
10687 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
10688 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010689
10690 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010691 ExprResult Update;
10692 if (!Info.first) {
10693 Update =
10694 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
10695 InitExpr, IV, Step, /* Subtract */ false);
10696 } else
10697 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010698 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
10699 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010700
10701 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010702 ExprResult Final;
10703 if (!Info.first) {
10704 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
10705 InitExpr, NumIterations, Step,
10706 /* Subtract */ false);
10707 } else
10708 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010709 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
10710 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010711
Alexander Musman3276a272015-03-21 10:12:56 +000010712 if (!Update.isUsable() || !Final.isUsable()) {
10713 Updates.push_back(nullptr);
10714 Finals.push_back(nullptr);
10715 HasErrors = true;
10716 } else {
10717 Updates.push_back(Update.get());
10718 Finals.push_back(Final.get());
10719 }
Richard Trieucc3949d2016-02-18 22:34:54 +000010720 ++CurInit;
10721 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000010722 }
10723 Clause.setUpdates(Updates);
10724 Clause.setFinals(Finals);
10725 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000010726}
10727
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010728OMPClause *Sema::ActOnOpenMPAlignedClause(
10729 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
10730 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
10731
10732 SmallVector<Expr *, 8> Vars;
10733 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000010734 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10735 SourceLocation ELoc;
10736 SourceRange ERange;
10737 Expr *SimpleRefExpr = RefExpr;
10738 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10739 /*AllowArraySection=*/false);
10740 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010741 // It will be analyzed later.
10742 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010743 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000010744 ValueDecl *D = Res.first;
10745 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010746 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010747
Alexey Bataev1efd1662016-03-29 10:59:56 +000010748 QualType QType = D->getType();
10749 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010750
10751 // OpenMP [2.8.1, simd construct, Restrictions]
10752 // The type of list items appearing in the aligned clause must be
10753 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010754 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010755 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000010756 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010757 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010758 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010759 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000010760 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010761 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000010762 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010763 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010764 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010765 continue;
10766 }
10767
10768 // OpenMP [2.8.1, simd construct, Restrictions]
10769 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000010770 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000010771 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010772 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
10773 << getOpenMPClauseName(OMPC_aligned);
10774 continue;
10775 }
10776
Alexey Bataev1efd1662016-03-29 10:59:56 +000010777 DeclRefExpr *Ref = nullptr;
10778 if (!VD && IsOpenMPCapturedDecl(D))
10779 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10780 Vars.push_back(DefaultFunctionArrayConversion(
10781 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
10782 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010783 }
10784
10785 // OpenMP [2.8.1, simd construct, Description]
10786 // The parameter of the aligned clause, alignment, must be a constant
10787 // positive integer expression.
10788 // If no optional parameter is specified, implementation-defined default
10789 // alignments for SIMD instructions on the target platforms are assumed.
10790 if (Alignment != nullptr) {
10791 ExprResult AlignResult =
10792 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
10793 if (AlignResult.isInvalid())
10794 return nullptr;
10795 Alignment = AlignResult.get();
10796 }
10797 if (Vars.empty())
10798 return nullptr;
10799
10800 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
10801 EndLoc, Vars, Alignment);
10802}
10803
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010804OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10805 SourceLocation StartLoc,
10806 SourceLocation LParenLoc,
10807 SourceLocation EndLoc) {
10808 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010809 SmallVector<Expr *, 8> SrcExprs;
10810 SmallVector<Expr *, 8> DstExprs;
10811 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000010812 for (auto &RefExpr : VarList) {
10813 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
10814 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010815 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010816 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010817 SrcExprs.push_back(nullptr);
10818 DstExprs.push_back(nullptr);
10819 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010820 continue;
10821 }
10822
Alexey Bataeved09d242014-05-28 05:53:51 +000010823 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010824 // OpenMP [2.1, C/C++]
10825 // A list item is a variable name.
10826 // OpenMP [2.14.4.1, Restrictions, p.1]
10827 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000010828 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010829 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010830 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
10831 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010832 continue;
10833 }
10834
10835 Decl *D = DE->getDecl();
10836 VarDecl *VD = cast<VarDecl>(D);
10837
10838 QualType Type = VD->getType();
10839 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
10840 // It will be analyzed later.
10841 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010842 SrcExprs.push_back(nullptr);
10843 DstExprs.push_back(nullptr);
10844 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010845 continue;
10846 }
10847
10848 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
10849 // A list item that appears in a copyin clause must be threadprivate.
10850 if (!DSAStack->isThreadPrivate(VD)) {
10851 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000010852 << getOpenMPClauseName(OMPC_copyin)
10853 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010854 continue;
10855 }
10856
10857 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10858 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000010859 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010860 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010861 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010862 auto *SrcVD =
10863 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
10864 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000010865 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010866 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
10867 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010868 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
10869 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010870 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010871 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010872 // For arrays generate assignment operation for single element and replace
10873 // it by the original array element in CodeGen.
10874 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
10875 PseudoDstExpr, PseudoSrcExpr);
10876 if (AssignmentOp.isInvalid())
10877 continue;
10878 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
10879 /*DiscardedValue=*/true);
10880 if (AssignmentOp.isInvalid())
10881 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010882
10883 DSAStack->addDSA(VD, DE, OMPC_copyin);
10884 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010885 SrcExprs.push_back(PseudoSrcExpr);
10886 DstExprs.push_back(PseudoDstExpr);
10887 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010888 }
10889
Alexey Bataeved09d242014-05-28 05:53:51 +000010890 if (Vars.empty())
10891 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010892
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010893 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10894 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010895}
10896
Alexey Bataevbae9a792014-06-27 10:37:06 +000010897OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10898 SourceLocation StartLoc,
10899 SourceLocation LParenLoc,
10900 SourceLocation EndLoc) {
10901 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000010902 SmallVector<Expr *, 8> SrcExprs;
10903 SmallVector<Expr *, 8> DstExprs;
10904 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010905 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010906 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10907 SourceLocation ELoc;
10908 SourceRange ERange;
10909 Expr *SimpleRefExpr = RefExpr;
10910 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10911 /*AllowArraySection=*/false);
10912 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010913 // It will be analyzed later.
10914 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010915 SrcExprs.push_back(nullptr);
10916 DstExprs.push_back(nullptr);
10917 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010918 }
Alexey Bataeve122da12016-03-17 10:50:17 +000010919 ValueDecl *D = Res.first;
10920 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000010921 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010922
Alexey Bataeve122da12016-03-17 10:50:17 +000010923 QualType Type = D->getType();
10924 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010925
10926 // OpenMP [2.14.4.2, Restrictions, p.2]
10927 // A list item that appears in a copyprivate clause may not appear in a
10928 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000010929 if (!VD || !DSAStack->isThreadPrivate(VD)) {
10930 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010931 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
10932 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010933 Diag(ELoc, diag::err_omp_wrong_dsa)
10934 << getOpenMPClauseName(DVar.CKind)
10935 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000010936 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010937 continue;
10938 }
10939
10940 // OpenMP [2.11.4.2, Restrictions, p.1]
10941 // All list items that appear in a copyprivate clause must be either
10942 // threadprivate or private in the enclosing context.
10943 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010944 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010945 if (DVar.CKind == OMPC_shared) {
10946 Diag(ELoc, diag::err_omp_required_access)
10947 << getOpenMPClauseName(OMPC_copyprivate)
10948 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000010949 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010950 continue;
10951 }
10952 }
10953 }
10954
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010955 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010956 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010957 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010958 << getOpenMPClauseName(OMPC_copyprivate) << Type
10959 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010960 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000010961 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010962 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000010963 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010964 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000010965 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010966 continue;
10967 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010968
Alexey Bataevbae9a792014-06-27 10:37:06 +000010969 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10970 // A variable of class type (or array thereof) that appears in a
10971 // copyin clause requires an accessible, unambiguous copy assignment
10972 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010973 Type = Context.getBaseElementType(Type.getNonReferenceType())
10974 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000010975 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010976 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
10977 D->hasAttrs() ? &D->getAttrs() : nullptr);
10978 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000010979 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010980 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
10981 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000010982 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000010983 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010984 PseudoDstExpr, PseudoSrcExpr);
10985 if (AssignmentOp.isInvalid())
10986 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000010987 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010988 /*DiscardedValue=*/true);
10989 if (AssignmentOp.isInvalid())
10990 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010991
10992 // No need to mark vars as copyprivate, they are already threadprivate or
10993 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000010994 assert(VD || IsOpenMPCapturedDecl(D));
10995 Vars.push_back(
10996 VD ? RefExpr->IgnoreParens()
10997 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000010998 SrcExprs.push_back(PseudoSrcExpr);
10999 DstExprs.push_back(PseudoDstExpr);
11000 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000011001 }
11002
11003 if (Vars.empty())
11004 return nullptr;
11005
Alexey Bataeva63048e2015-03-23 06:18:07 +000011006 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11007 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011008}
11009
Alexey Bataev6125da92014-07-21 11:26:11 +000011010OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11011 SourceLocation StartLoc,
11012 SourceLocation LParenLoc,
11013 SourceLocation EndLoc) {
11014 if (VarList.empty())
11015 return nullptr;
11016
11017 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
11018}
Alexey Bataevdea47612014-07-23 07:46:59 +000011019
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011020OMPClause *
11021Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
11022 SourceLocation DepLoc, SourceLocation ColonLoc,
11023 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11024 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011025 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011026 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011027 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011028 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000011029 return nullptr;
11030 }
11031 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011032 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
11033 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011034 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011035 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011036 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
11037 /*Last=*/OMPC_DEPEND_unknown, Except)
11038 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011039 return nullptr;
11040 }
11041 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000011042 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011043 llvm::APSInt DepCounter(/*BitWidth=*/32);
11044 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
11045 if (DepKind == OMPC_DEPEND_sink) {
11046 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
11047 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
11048 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011049 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011050 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011051 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
11052 DSAStack->getParentOrderedRegionParam()) {
11053 for (auto &RefExpr : VarList) {
11054 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000011055 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011056 // It will be analyzed later.
11057 Vars.push_back(RefExpr);
11058 continue;
11059 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011060
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011061 SourceLocation ELoc = RefExpr->getExprLoc();
11062 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
11063 if (DepKind == OMPC_DEPEND_sink) {
11064 if (DepCounter >= TotalDepCount) {
11065 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
11066 continue;
11067 }
11068 ++DepCounter;
11069 // OpenMP [2.13.9, Summary]
11070 // depend(dependence-type : vec), where dependence-type is:
11071 // 'sink' and where vec is the iteration vector, which has the form:
11072 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
11073 // where n is the value specified by the ordered clause in the loop
11074 // directive, xi denotes the loop iteration variable of the i-th nested
11075 // loop associated with the loop directive, and di is a constant
11076 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000011077 if (CurContext->isDependentContext()) {
11078 // It will be analyzed later.
11079 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011080 continue;
11081 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011082 SimpleExpr = SimpleExpr->IgnoreImplicit();
11083 OverloadedOperatorKind OOK = OO_None;
11084 SourceLocation OOLoc;
11085 Expr *LHS = SimpleExpr;
11086 Expr *RHS = nullptr;
11087 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
11088 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
11089 OOLoc = BO->getOperatorLoc();
11090 LHS = BO->getLHS()->IgnoreParenImpCasts();
11091 RHS = BO->getRHS()->IgnoreParenImpCasts();
11092 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
11093 OOK = OCE->getOperator();
11094 OOLoc = OCE->getOperatorLoc();
11095 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11096 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
11097 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
11098 OOK = MCE->getMethodDecl()
11099 ->getNameInfo()
11100 .getName()
11101 .getCXXOverloadedOperator();
11102 OOLoc = MCE->getCallee()->getExprLoc();
11103 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
11104 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11105 }
11106 SourceLocation ELoc;
11107 SourceRange ERange;
11108 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
11109 /*AllowArraySection=*/false);
11110 if (Res.second) {
11111 // It will be analyzed later.
11112 Vars.push_back(RefExpr);
11113 }
11114 ValueDecl *D = Res.first;
11115 if (!D)
11116 continue;
11117
11118 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
11119 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
11120 continue;
11121 }
11122 if (RHS) {
11123 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
11124 RHS, OMPC_depend, /*StrictlyPositive=*/false);
11125 if (RHSRes.isInvalid())
11126 continue;
11127 }
11128 if (!CurContext->isDependentContext() &&
11129 DSAStack->getParentOrderedRegionParam() &&
11130 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Rachel Craik1cf49e42017-09-19 21:04:23 +000011131 ValueDecl* VD = DSAStack->getParentLoopControlVariable(
11132 DepCounter.getZExtValue());
11133 if (VD) {
11134 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
11135 << 1 << VD;
11136 } else {
11137 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
11138 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011139 continue;
11140 }
11141 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011142 } else {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011143 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011144 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000011145 (ASE &&
11146 !ASE->getBase()
11147 ->getType()
11148 .getNonReferenceType()
11149 ->isPointerType() &&
11150 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev463a9fe2017-07-27 19:15:30 +000011151 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11152 << RefExpr->getSourceRange();
11153 continue;
11154 }
11155 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
11156 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevd070a582017-10-25 15:54:04 +000011157 ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
Alexey Bataev463a9fe2017-07-27 19:15:30 +000011158 RefExpr->IgnoreParenImpCasts());
11159 getDiagnostics().setSuppressAllDiagnostics(Suppress);
11160 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
11161 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11162 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011163 continue;
11164 }
11165 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011166 Vars.push_back(RefExpr->IgnoreParenImpCasts());
11167 }
11168
11169 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
11170 TotalDepCount > VarList.size() &&
Rachel Craik1cf49e42017-09-19 21:04:23 +000011171 DSAStack->getParentOrderedRegionParam() &&
11172 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
11173 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011174 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
11175 }
11176 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
11177 Vars.empty())
11178 return nullptr;
11179 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011180 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11181 DepKind, DepLoc, ColonLoc, Vars);
11182 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
11183 DSAStack->addDoacrossDependClause(C, OpsOffs);
11184 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011185}
Michael Wonge710d542015-08-07 16:16:36 +000011186
11187OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
11188 SourceLocation LParenLoc,
11189 SourceLocation EndLoc) {
11190 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000011191 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000011192
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011193 // OpenMP [2.9.1, Restrictions]
11194 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011195 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
11196 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011197 return nullptr;
11198
Alexey Bataev931e19b2017-10-02 16:32:39 +000011199 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11200 if (isOpenMPTargetExecutionDirective(DKind) &&
11201 !CurContext->isDependentContext()) {
11202 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11203 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11204 HelperValStmt = buildPreInits(Context, Captures);
11205 }
11206
11207 return new (Context)
11208 OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000011209}
Kelvin Li0bff7af2015-11-23 05:32:03 +000011210
Kelvin Li0bff7af2015-11-23 05:32:03 +000011211static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
11212 DSAStackTy *Stack, QualType QTy) {
11213 NamedDecl *ND;
11214 if (QTy->isIncompleteType(&ND)) {
11215 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
11216 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011217 }
11218 return true;
11219}
11220
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011221/// \brief Return true if it can be proven that the provided array expression
11222/// (array section or array subscript) does NOT specify the whole size of the
11223/// array whose base type is \a BaseQTy.
11224static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
11225 const Expr *E,
11226 QualType BaseQTy) {
11227 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11228
11229 // If this is an array subscript, it refers to the whole size if the size of
11230 // the dimension is constant and equals 1. Also, an array section assumes the
11231 // format of an array subscript if no colon is used.
11232 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
11233 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11234 return ATy->getSize().getSExtValue() != 1;
11235 // Size can't be evaluated statically.
11236 return false;
11237 }
11238
11239 assert(OASE && "Expecting array section if not an array subscript.");
11240 auto *LowerBound = OASE->getLowerBound();
11241 auto *Length = OASE->getLength();
11242
11243 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000011244 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011245 if (LowerBound) {
11246 llvm::APSInt ConstLowerBound;
11247 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
11248 return false; // Can't get the integer value as a constant.
11249 if (ConstLowerBound.getSExtValue())
11250 return true;
11251 }
11252
11253 // If we don't have a length we covering the whole dimension.
11254 if (!Length)
11255 return false;
11256
11257 // If the base is a pointer, we don't have a way to get the size of the
11258 // pointee.
11259 if (BaseQTy->isPointerType())
11260 return false;
11261
11262 // We can only check if the length is the same as the size of the dimension
11263 // if we have a constant array.
11264 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
11265 if (!CATy)
11266 return false;
11267
11268 llvm::APSInt ConstLength;
11269 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11270 return false; // Can't get the integer value as a constant.
11271
11272 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
11273}
11274
11275// Return true if it can be proven that the provided array expression (array
11276// section or array subscript) does NOT specify a single element of the array
11277// whose base type is \a BaseQTy.
11278static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000011279 const Expr *E,
11280 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011281 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11282
11283 // An array subscript always refer to a single element. Also, an array section
11284 // assumes the format of an array subscript if no colon is used.
11285 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
11286 return false;
11287
11288 assert(OASE && "Expecting array section if not an array subscript.");
11289 auto *Length = OASE->getLength();
11290
11291 // If we don't have a length we have to check if the array has unitary size
11292 // for this dimension. Also, we should always expect a length if the base type
11293 // is pointer.
11294 if (!Length) {
11295 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11296 return ATy->getSize().getSExtValue() != 1;
11297 // We cannot assume anything.
11298 return false;
11299 }
11300
11301 // Check if the length evaluates to 1.
11302 llvm::APSInt ConstLength;
11303 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11304 return false; // Can't get the integer value as a constant.
11305
11306 return ConstLength.getSExtValue() != 1;
11307}
11308
Samuel Antao661c0902016-05-26 17:39:58 +000011309// Return the expression of the base of the mappable expression or null if it
11310// cannot be determined and do all the necessary checks to see if the expression
11311// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000011312// components of the expression.
11313static Expr *CheckMapClauseExpressionBase(
11314 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000011315 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
11316 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011317 SourceLocation ELoc = E->getExprLoc();
11318 SourceRange ERange = E->getSourceRange();
11319
11320 // The base of elements of list in a map clause have to be either:
11321 // - a reference to variable or field.
11322 // - a member expression.
11323 // - an array expression.
11324 //
11325 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
11326 // reference to 'r'.
11327 //
11328 // If we have:
11329 //
11330 // struct SS {
11331 // Bla S;
11332 // foo() {
11333 // #pragma omp target map (S.Arr[:12]);
11334 // }
11335 // }
11336 //
11337 // We want to retrieve the member expression 'this->S';
11338
11339 Expr *RelevantExpr = nullptr;
11340
Samuel Antao5de996e2016-01-22 20:21:36 +000011341 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
11342 // If a list item is an array section, it must specify contiguous storage.
11343 //
11344 // For this restriction it is sufficient that we make sure only references
11345 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011346 // exist except in the rightmost expression (unless they cover the whole
11347 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000011348 //
11349 // r.ArrS[3:5].Arr[6:7]
11350 //
11351 // r.ArrS[3:5].x
11352 //
11353 // but these would be valid:
11354 // r.ArrS[3].Arr[6:7]
11355 //
11356 // r.ArrS[3].x
11357
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011358 bool AllowUnitySizeArraySection = true;
11359 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000011360
Dmitry Polukhin644a9252016-03-11 07:58:34 +000011361 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011362 E = E->IgnoreParenImpCasts();
11363
11364 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
11365 if (!isa<VarDecl>(CurE->getDecl()))
11366 break;
11367
11368 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011369
11370 // If we got a reference to a declaration, we should not expect any array
11371 // section before that.
11372 AllowUnitySizeArraySection = false;
11373 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011374
11375 // Record the component.
11376 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
11377 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000011378 continue;
11379 }
11380
11381 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
11382 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
11383
11384 if (isa<CXXThisExpr>(BaseE))
11385 // We found a base expression: this->Val.
11386 RelevantExpr = CurE;
11387 else
11388 E = BaseE;
11389
11390 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
11391 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11392 << CurE->getSourceRange();
11393 break;
11394 }
11395
11396 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11397
11398 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11399 // A bit-field cannot appear in a map clause.
11400 //
11401 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011402 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11403 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011404 break;
11405 }
11406
11407 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11408 // If the type of a list item is a reference to a type T then the type
11409 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011410 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011411
11412 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11413 // A list item cannot be a variable that is a member of a structure with
11414 // a union type.
11415 //
11416 if (auto *RT = CurType->getAs<RecordType>())
11417 if (RT->isUnionType()) {
11418 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11419 << CurE->getSourceRange();
11420 break;
11421 }
11422
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011423 // If we got a member expression, we should not expect any array section
11424 // before that:
11425 //
11426 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11427 // If a list item is an element of a structure, only the rightmost symbol
11428 // of the variable reference can be an array section.
11429 //
11430 AllowUnitySizeArraySection = false;
11431 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011432
11433 // Record the component.
11434 CurComponents.push_back(
11435 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000011436 continue;
11437 }
11438
11439 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
11440 E = CurE->getBase()->IgnoreParenImpCasts();
11441
11442 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
11443 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11444 << 0 << CurE->getSourceRange();
11445 break;
11446 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011447
11448 // If we got an array subscript that express the whole dimension we
11449 // can have any array expressions before. If it only expressing part of
11450 // the dimension, we can only have unitary-size array expressions.
11451 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
11452 E->getType()))
11453 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011454
11455 // Record the component - we don't have any declaration associated.
11456 CurComponents.push_back(
11457 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000011458 continue;
11459 }
11460
11461 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011462 E = CurE->getBase()->IgnoreParenImpCasts();
11463
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011464 auto CurType =
11465 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11466
Samuel Antao5de996e2016-01-22 20:21:36 +000011467 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11468 // If the type of a list item is a reference to a type T then the type
11469 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000011470 if (CurType->isReferenceType())
11471 CurType = CurType->getPointeeType();
11472
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011473 bool IsPointer = CurType->isAnyPointerType();
11474
11475 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011476 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11477 << 0 << CurE->getSourceRange();
11478 break;
11479 }
11480
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011481 bool NotWhole =
11482 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11483 bool NotUnity =
11484 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11485
Samuel Antaodab51bb2016-07-18 23:22:11 +000011486 if (AllowWholeSizeArraySection) {
11487 // Any array section is currently allowed. Allowing a whole size array
11488 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011489 //
11490 // If this array section refers to the whole dimension we can still
11491 // accept other array sections before this one, except if the base is a
11492 // pointer. Otherwise, only unitary sections are accepted.
11493 if (NotWhole || IsPointer)
11494 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000011495 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011496 // A unity or whole array section is not allowed and that is not
11497 // compatible with the properties of the current array section.
11498 SemaRef.Diag(
11499 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11500 << CurE->getSourceRange();
11501 break;
11502 }
Samuel Antao90927002016-04-26 14:54:23 +000011503
11504 // Record the component - we don't have any declaration associated.
11505 CurComponents.push_back(
11506 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000011507 continue;
11508 }
11509
11510 // If nothing else worked, this is not a valid map clause expression.
11511 SemaRef.Diag(ELoc,
11512 diag::err_omp_expected_named_var_member_or_array_expression)
11513 << ERange;
11514 break;
11515 }
11516
11517 return RelevantExpr;
11518}
11519
11520// Return true if expression E associated with value VD has conflicts with other
11521// map information.
Samuel Antao90927002016-04-26 14:54:23 +000011522static bool CheckMapConflicts(
11523 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
11524 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000011525 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11526 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011527 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000011528 SourceLocation ELoc = E->getExprLoc();
11529 SourceRange ERange = E->getSourceRange();
11530
11531 // In order to easily check the conflicts we need to match each component of
11532 // the expression under test with the components of the expressions that are
11533 // already in the stack.
11534
Samuel Antao5de996e2016-01-22 20:21:36 +000011535 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011536 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011537 "Map clause expression with unexpected base!");
11538
11539 // Variables to help detecting enclosing problems in data environment nests.
11540 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000011541 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011542
Samuel Antao90927002016-04-26 14:54:23 +000011543 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11544 VD, CurrentRegionOnly,
11545 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000011546 StackComponents,
11547 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000011548
Samuel Antao5de996e2016-01-22 20:21:36 +000011549 assert(!StackComponents.empty() &&
11550 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011551 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011552 "Map clause expression with unexpected base!");
11553
Samuel Antao90927002016-04-26 14:54:23 +000011554 // The whole expression in the stack.
11555 auto *RE = StackComponents.front().getAssociatedExpression();
11556
Samuel Antao5de996e2016-01-22 20:21:36 +000011557 // Expressions must start from the same base. Here we detect at which
11558 // point both expressions diverge from each other and see if we can
11559 // detect if the memory referred to both expressions is contiguous and
11560 // do not overlap.
11561 auto CI = CurComponents.rbegin();
11562 auto CE = CurComponents.rend();
11563 auto SI = StackComponents.rbegin();
11564 auto SE = StackComponents.rend();
11565 for (; CI != CE && SI != SE; ++CI, ++SI) {
11566
11567 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
11568 // At most one list item can be an array item derived from a given
11569 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000011570 if (CurrentRegionOnly &&
11571 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
11572 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
11573 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
11574 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
11575 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000011576 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000011577 << CI->getAssociatedExpression()->getSourceRange();
11578 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
11579 diag::note_used_here)
11580 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000011581 return true;
11582 }
11583
11584 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000011585 if (CI->getAssociatedExpression()->getStmtClass() !=
11586 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000011587 break;
11588
11589 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000011590 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000011591 break;
11592 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000011593 // Check if the extra components of the expressions in the enclosing
11594 // data environment are redundant for the current base declaration.
11595 // If they are, the maps completely overlap, which is legal.
11596 for (; SI != SE; ++SI) {
11597 QualType Type;
11598 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000011599 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011600 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000011601 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
11602 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011603 auto *E = OASE->getBase()->IgnoreParenImpCasts();
11604 Type =
11605 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11606 }
11607 if (Type.isNull() || Type->isAnyPointerType() ||
11608 CheckArrayExpressionDoesNotReferToWholeSize(
11609 SemaRef, SI->getAssociatedExpression(), Type))
11610 break;
11611 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011612
11613 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11614 // List items of map clauses in the same construct must not share
11615 // original storage.
11616 //
11617 // If the expressions are exactly the same or one is a subset of the
11618 // other, it means they are sharing storage.
11619 if (CI == CE && SI == SE) {
11620 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000011621 if (CKind == OMPC_map)
11622 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11623 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011624 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011625 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11626 << ERange;
11627 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011628 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11629 << RE->getSourceRange();
11630 return true;
11631 } else {
11632 // If we find the same expression in the enclosing data environment,
11633 // that is legal.
11634 IsEnclosedByDataEnvironmentExpr = true;
11635 return false;
11636 }
11637 }
11638
Samuel Antao90927002016-04-26 14:54:23 +000011639 QualType DerivedType =
11640 std::prev(CI)->getAssociatedDeclaration()->getType();
11641 SourceLocation DerivedLoc =
11642 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000011643
11644 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11645 // If the type of a list item is a reference to a type T then the type
11646 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011647 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011648
11649 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
11650 // A variable for which the type is pointer and an array section
11651 // derived from that variable must not appear as list items of map
11652 // clauses of the same construct.
11653 //
11654 // Also, cover one of the cases in:
11655 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11656 // If any part of the original storage of a list item has corresponding
11657 // storage in the device data environment, all of the original storage
11658 // must have corresponding storage in the device data environment.
11659 //
11660 if (DerivedType->isAnyPointerType()) {
11661 if (CI == CE || SI == SE) {
11662 SemaRef.Diag(
11663 DerivedLoc,
11664 diag::err_omp_pointer_mapped_along_with_derived_section)
11665 << DerivedLoc;
11666 } else {
11667 assert(CI != CE && SI != SE);
11668 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
11669 << DerivedLoc;
11670 }
11671 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11672 << RE->getSourceRange();
11673 return true;
11674 }
11675
11676 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11677 // List items of map clauses in the same construct must not share
11678 // original storage.
11679 //
11680 // An expression is a subset of the other.
11681 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000011682 if (CKind == OMPC_map)
11683 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11684 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011685 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011686 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11687 << ERange;
11688 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011689 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11690 << RE->getSourceRange();
11691 return true;
11692 }
11693
11694 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000011695 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000011696 if (!CurrentRegionOnly && SI != SE)
11697 EnclosingExpr = RE;
11698
11699 // The current expression is a subset of the expression in the data
11700 // environment.
11701 IsEnclosedByDataEnvironmentExpr |=
11702 (!CurrentRegionOnly && CI != CE && SI == SE);
11703
11704 return false;
11705 });
11706
11707 if (CurrentRegionOnly)
11708 return FoundError;
11709
11710 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11711 // If any part of the original storage of a list item has corresponding
11712 // storage in the device data environment, all of the original storage must
11713 // have corresponding storage in the device data environment.
11714 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
11715 // If a list item is an element of a structure, and a different element of
11716 // the structure has a corresponding list item in the device data environment
11717 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000011718 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000011719 // data environment prior to the task encountering the construct.
11720 //
11721 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
11722 SemaRef.Diag(ELoc,
11723 diag::err_omp_original_storage_is_shared_and_does_not_contain)
11724 << ERange;
11725 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
11726 << EnclosingExpr->getSourceRange();
11727 return true;
11728 }
11729
11730 return FoundError;
11731}
11732
Samuel Antao661c0902016-05-26 17:39:58 +000011733namespace {
11734// Utility struct that gathers all the related lists associated with a mappable
11735// expression.
11736struct MappableVarListInfo final {
11737 // The list of expressions.
11738 ArrayRef<Expr *> VarList;
11739 // The list of processed expressions.
11740 SmallVector<Expr *, 16> ProcessedVarList;
11741 // The mappble components for each expression.
11742 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
11743 // The base declaration of the variable.
11744 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
11745
11746 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
11747 // We have a list of components and base declarations for each entry in the
11748 // variable list.
11749 VarComponents.reserve(VarList.size());
11750 VarBaseDeclarations.reserve(VarList.size());
11751 }
11752};
11753}
11754
11755// Check the validity of the provided variable list for the provided clause kind
11756// \a CKind. In the check process the valid expressions, and mappable expression
11757// components and variables are extracted and used to fill \a Vars,
11758// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
11759// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
11760static void
11761checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
11762 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
11763 SourceLocation StartLoc,
11764 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
11765 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011766 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
11767 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000011768 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011769
Samuel Antao90927002016-04-26 14:54:23 +000011770 // Keep track of the mappable components and base declarations in this clause.
11771 // Each entry in the list is going to have a list of components associated. We
11772 // record each set of the components so that we can build the clause later on.
11773 // In the end we should have the same amount of declarations and component
11774 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000011775
Samuel Antao661c0902016-05-26 17:39:58 +000011776 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011777 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011778 SourceLocation ELoc = RE->getExprLoc();
11779
Kelvin Li0bff7af2015-11-23 05:32:03 +000011780 auto *VE = RE->IgnoreParenLValueCasts();
11781
11782 if (VE->isValueDependent() || VE->isTypeDependent() ||
11783 VE->isInstantiationDependent() ||
11784 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011785 // We can only analyze this information once the missing information is
11786 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000011787 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011788 continue;
11789 }
11790
11791 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011792
Samuel Antao5de996e2016-01-22 20:21:36 +000011793 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011794 SemaRef.Diag(ELoc,
11795 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000011796 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011797 continue;
11798 }
11799
Samuel Antao90927002016-04-26 14:54:23 +000011800 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
11801 ValueDecl *CurDeclaration = nullptr;
11802
11803 // Obtain the array or member expression bases if required. Also, fill the
11804 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000011805 auto *BE =
11806 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011807 if (!BE)
11808 continue;
11809
Samuel Antao90927002016-04-26 14:54:23 +000011810 assert(!CurComponents.empty() &&
11811 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011812
Samuel Antao90927002016-04-26 14:54:23 +000011813 // For the following checks, we rely on the base declaration which is
11814 // expected to be associated with the last component. The declaration is
11815 // expected to be a variable or a field (if 'this' is being mapped).
11816 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
11817 assert(CurDeclaration && "Null decl on map clause.");
11818 assert(
11819 CurDeclaration->isCanonicalDecl() &&
11820 "Expecting components to have associated only canonical declarations.");
11821
11822 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
11823 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000011824
11825 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000011826 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000011827
11828 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000011829 // threadprivate variables cannot appear in a map clause.
11830 // OpenMP 4.5 [2.10.5, target update Construct]
11831 // threadprivate variables cannot appear in a from clause.
11832 if (VD && DSAS->isThreadPrivate(VD)) {
11833 auto DVar = DSAS->getTopDSA(VD, false);
11834 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
11835 << getOpenMPClauseName(CKind);
11836 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011837 continue;
11838 }
11839
Samuel Antao5de996e2016-01-22 20:21:36 +000011840 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
11841 // A list item cannot appear in both a map clause and a data-sharing
11842 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000011843
Samuel Antao5de996e2016-01-22 20:21:36 +000011844 // Check conflicts with other map clause expressions. We check the conflicts
11845 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000011846 // environment, because the restrictions are different. We only have to
11847 // check conflicts across regions for the map clauses.
11848 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11849 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011850 break;
Samuel Antao661c0902016-05-26 17:39:58 +000011851 if (CKind == OMPC_map &&
11852 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11853 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011854 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011855
Samuel Antao661c0902016-05-26 17:39:58 +000011856 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000011857 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11858 // If the type of a list item is a reference to a type T then the type will
11859 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011860 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011861
Samuel Antao661c0902016-05-26 17:39:58 +000011862 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
11863 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000011864 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000011865 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000011866 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
11867 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000011868 continue;
11869
Samuel Antao661c0902016-05-26 17:39:58 +000011870 if (CKind == OMPC_map) {
11871 // target enter data
11872 // OpenMP [2.10.2, Restrictions, p. 99]
11873 // A map-type must be specified in all map clauses and must be either
11874 // to or alloc.
11875 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
11876 if (DKind == OMPD_target_enter_data &&
11877 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
11878 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11879 << (IsMapTypeImplicit ? 1 : 0)
11880 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11881 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011882 continue;
11883 }
Samuel Antao661c0902016-05-26 17:39:58 +000011884
11885 // target exit_data
11886 // OpenMP [2.10.3, Restrictions, p. 102]
11887 // A map-type must be specified in all map clauses and must be either
11888 // from, release, or delete.
11889 if (DKind == OMPD_target_exit_data &&
11890 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
11891 MapType == OMPC_MAP_delete)) {
11892 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11893 << (IsMapTypeImplicit ? 1 : 0)
11894 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11895 << getOpenMPDirectiveName(DKind);
11896 continue;
11897 }
11898
11899 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11900 // A list item cannot appear in both a map clause and a data-sharing
11901 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000011902 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000011903 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000011904 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000011905 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
11906 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000011907 auto DVar = DSAS->getTopDSA(VD, false);
11908 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000011909 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000011910 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000011911 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000011912 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
11913 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
11914 continue;
11915 }
11916 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011917 }
11918
Samuel Antao90927002016-04-26 14:54:23 +000011919 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000011920 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000011921
11922 // Store the components in the stack so that they can be used to check
11923 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000011924 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
11925 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000011926
11927 // Save the components and declaration to create the clause. For purposes of
11928 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000011929 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000011930 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11931 MVLI.VarComponents.back().append(CurComponents.begin(),
11932 CurComponents.end());
11933 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
11934 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011935 }
Samuel Antao661c0902016-05-26 17:39:58 +000011936}
11937
11938OMPClause *
11939Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
11940 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11941 SourceLocation MapLoc, SourceLocation ColonLoc,
11942 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11943 SourceLocation LParenLoc, SourceLocation EndLoc) {
11944 MappableVarListInfo MVLI(VarList);
11945 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
11946 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011947
Samuel Antao5de996e2016-01-22 20:21:36 +000011948 // We need to produce a map clause even if we don't have variables so that
11949 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000011950 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11951 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11952 MVLI.VarComponents, MapTypeModifier, MapType,
11953 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011954}
Kelvin Li099bb8c2015-11-24 20:50:12 +000011955
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011956QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
11957 TypeResult ParsedType) {
11958 assert(ParsedType.isUsable());
11959
11960 QualType ReductionType = GetTypeFromParser(ParsedType.get());
11961 if (ReductionType.isNull())
11962 return QualType();
11963
11964 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
11965 // A type name in a declare reduction directive cannot be a function type, an
11966 // array type, a reference type, or a type qualified with const, volatile or
11967 // restrict.
11968 if (ReductionType.hasQualifiers()) {
11969 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
11970 return QualType();
11971 }
11972
11973 if (ReductionType->isFunctionType()) {
11974 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
11975 return QualType();
11976 }
11977 if (ReductionType->isReferenceType()) {
11978 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
11979 return QualType();
11980 }
11981 if (ReductionType->isArrayType()) {
11982 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
11983 return QualType();
11984 }
11985 return ReductionType;
11986}
11987
11988Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
11989 Scope *S, DeclContext *DC, DeclarationName Name,
11990 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
11991 AccessSpecifier AS, Decl *PrevDeclInScope) {
11992 SmallVector<Decl *, 8> Decls;
11993 Decls.reserve(ReductionTypes.size());
11994
11995 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000011996 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011997 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
11998 // A reduction-identifier may not be re-declared in the current scope for the
11999 // same type or for a type that is compatible according to the base language
12000 // rules.
12001 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
12002 OMPDeclareReductionDecl *PrevDRD = nullptr;
12003 bool InCompoundScope = true;
12004 if (S != nullptr) {
12005 // Find previous declaration with the same name not referenced in other
12006 // declarations.
12007 FunctionScopeInfo *ParentFn = getEnclosingFunction();
12008 InCompoundScope =
12009 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
12010 LookupName(Lookup, S);
12011 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
12012 /*AllowInlineNamespace=*/false);
12013 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
12014 auto Filter = Lookup.makeFilter();
12015 while (Filter.hasNext()) {
12016 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
12017 if (InCompoundScope) {
12018 auto I = UsedAsPrevious.find(PrevDecl);
12019 if (I == UsedAsPrevious.end())
12020 UsedAsPrevious[PrevDecl] = false;
12021 if (auto *D = PrevDecl->getPrevDeclInScope())
12022 UsedAsPrevious[D] = true;
12023 }
12024 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
12025 PrevDecl->getLocation();
12026 }
12027 Filter.done();
12028 if (InCompoundScope) {
12029 for (auto &PrevData : UsedAsPrevious) {
12030 if (!PrevData.second) {
12031 PrevDRD = PrevData.first;
12032 break;
12033 }
12034 }
12035 }
12036 } else if (PrevDeclInScope != nullptr) {
12037 auto *PrevDRDInScope = PrevDRD =
12038 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
12039 do {
12040 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
12041 PrevDRDInScope->getLocation();
12042 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
12043 } while (PrevDRDInScope != nullptr);
12044 }
12045 for (auto &TyData : ReductionTypes) {
12046 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
12047 bool Invalid = false;
12048 if (I != PreviousRedeclTypes.end()) {
12049 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
12050 << TyData.first;
12051 Diag(I->second, diag::note_previous_definition);
12052 Invalid = true;
12053 }
12054 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
12055 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
12056 Name, TyData.first, PrevDRD);
12057 DC->addDecl(DRD);
12058 DRD->setAccess(AS);
12059 Decls.push_back(DRD);
12060 if (Invalid)
12061 DRD->setInvalidDecl();
12062 else
12063 PrevDRD = DRD;
12064 }
12065
12066 return DeclGroupPtrTy::make(
12067 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
12068}
12069
12070void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
12071 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12072
12073 // Enter new function scope.
12074 PushFunctionScope();
12075 getCurFunction()->setHasBranchProtectedScope();
12076 getCurFunction()->setHasOMPDeclareReductionCombiner();
12077
12078 if (S != nullptr)
12079 PushDeclContext(S, DRD);
12080 else
12081 CurContext = DRD;
12082
Faisal Valid143a0c2017-04-01 21:30:49 +000012083 PushExpressionEvaluationContext(
12084 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012085
12086 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012087 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
12088 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
12089 // uses semantics of argument handles by value, but it should be passed by
12090 // reference. C lang does not support references, so pass all parameters as
12091 // pointers.
12092 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012093 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012094 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012095 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
12096 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
12097 // uses semantics of argument handles by value, but it should be passed by
12098 // reference. C lang does not support references, so pass all parameters as
12099 // pointers.
12100 // Create 'T omp_out;' variable.
12101 auto *OmpOutParm =
12102 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
12103 if (S != nullptr) {
12104 PushOnScopeChains(OmpInParm, S);
12105 PushOnScopeChains(OmpOutParm, S);
12106 } else {
12107 DRD->addDecl(OmpInParm);
12108 DRD->addDecl(OmpOutParm);
12109 }
12110}
12111
12112void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
12113 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12114 DiscardCleanupsInEvaluationContext();
12115 PopExpressionEvaluationContext();
12116
12117 PopDeclContext();
12118 PopFunctionScopeInfo();
12119
12120 if (Combiner != nullptr)
12121 DRD->setCombiner(Combiner);
12122 else
12123 DRD->setInvalidDecl();
12124}
12125
Alexey Bataev070f43a2017-09-06 14:49:58 +000012126VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012127 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12128
12129 // Enter new function scope.
12130 PushFunctionScope();
12131 getCurFunction()->setHasBranchProtectedScope();
12132
12133 if (S != nullptr)
12134 PushDeclContext(S, DRD);
12135 else
12136 CurContext = DRD;
12137
Faisal Valid143a0c2017-04-01 21:30:49 +000012138 PushExpressionEvaluationContext(
12139 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012140
12141 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012142 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
12143 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
12144 // uses semantics of argument handles by value, but it should be passed by
12145 // reference. C lang does not support references, so pass all parameters as
12146 // pointers.
12147 // Create 'T omp_priv;' variable.
12148 auto *OmpPrivParm =
12149 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012150 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
12151 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
12152 // uses semantics of argument handles by value, but it should be passed by
12153 // reference. C lang does not support references, so pass all parameters as
12154 // pointers.
12155 // Create 'T omp_orig;' variable.
12156 auto *OmpOrigParm =
12157 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012158 if (S != nullptr) {
12159 PushOnScopeChains(OmpPrivParm, S);
12160 PushOnScopeChains(OmpOrigParm, S);
12161 } else {
12162 DRD->addDecl(OmpPrivParm);
12163 DRD->addDecl(OmpOrigParm);
12164 }
Alexey Bataev070f43a2017-09-06 14:49:58 +000012165 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012166}
12167
Alexey Bataev070f43a2017-09-06 14:49:58 +000012168void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
12169 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012170 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12171 DiscardCleanupsInEvaluationContext();
12172 PopExpressionEvaluationContext();
12173
12174 PopDeclContext();
12175 PopFunctionScopeInfo();
12176
Alexey Bataev070f43a2017-09-06 14:49:58 +000012177 if (Initializer != nullptr) {
12178 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
12179 } else if (OmpPrivParm->hasInit()) {
12180 DRD->setInitializer(OmpPrivParm->getInit(),
12181 OmpPrivParm->isDirectInit()
12182 ? OMPDeclareReductionDecl::DirectInit
12183 : OMPDeclareReductionDecl::CopyInit);
12184 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012185 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000012186 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012187}
12188
12189Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
12190 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
12191 for (auto *D : DeclReductions.get()) {
12192 if (IsValid) {
12193 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12194 if (S != nullptr)
12195 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
12196 } else
12197 D->setInvalidDecl();
12198 }
12199 return DeclReductions;
12200}
12201
David Majnemer9d168222016-08-05 17:44:54 +000012202OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000012203 SourceLocation StartLoc,
12204 SourceLocation LParenLoc,
12205 SourceLocation EndLoc) {
12206 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012207 Stmt *HelperValStmt = nullptr;
12208 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012209
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012210 // OpenMP [teams Constrcut, Restrictions]
12211 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012212 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
12213 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012214 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012215
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012216 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12217 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
12218 if (CaptureRegion != OMPD_unknown) {
12219 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12220 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12221 HelperValStmt = buildPreInits(Context, Captures);
12222 }
12223
12224 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
12225 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000012226}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012227
12228OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12229 SourceLocation StartLoc,
12230 SourceLocation LParenLoc,
12231 SourceLocation EndLoc) {
12232 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012233 Stmt *HelperValStmt = nullptr;
12234 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012235
12236 // OpenMP [teams Constrcut, Restrictions]
12237 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012238 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
12239 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012240 return nullptr;
12241
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012242 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12243 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
12244 if (CaptureRegion != OMPD_unknown) {
12245 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12246 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12247 HelperValStmt = buildPreInits(Context, Captures);
12248 }
12249
12250 return new (Context) OMPThreadLimitClause(
12251 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012252}
Alexey Bataeva0569352015-12-01 10:17:31 +000012253
12254OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
12255 SourceLocation StartLoc,
12256 SourceLocation LParenLoc,
12257 SourceLocation EndLoc) {
12258 Expr *ValExpr = Priority;
12259
12260 // OpenMP [2.9.1, task Constrcut]
12261 // The priority-value is a non-negative numerical scalar expression.
12262 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
12263 /*StrictlyPositive=*/false))
12264 return nullptr;
12265
12266 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12267}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012268
12269OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
12270 SourceLocation StartLoc,
12271 SourceLocation LParenLoc,
12272 SourceLocation EndLoc) {
12273 Expr *ValExpr = Grainsize;
12274
12275 // OpenMP [2.9.2, taskloop Constrcut]
12276 // The parameter of the grainsize clause must be a positive integer
12277 // expression.
12278 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
12279 /*StrictlyPositive=*/true))
12280 return nullptr;
12281
12282 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12283}
Alexey Bataev382967a2015-12-08 12:06:20 +000012284
12285OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
12286 SourceLocation StartLoc,
12287 SourceLocation LParenLoc,
12288 SourceLocation EndLoc) {
12289 Expr *ValExpr = NumTasks;
12290
12291 // OpenMP [2.9.2, taskloop Constrcut]
12292 // The parameter of the num_tasks clause must be a positive integer
12293 // expression.
12294 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
12295 /*StrictlyPositive=*/true))
12296 return nullptr;
12297
12298 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12299}
12300
Alexey Bataev28c75412015-12-15 08:19:24 +000012301OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
12302 SourceLocation LParenLoc,
12303 SourceLocation EndLoc) {
12304 // OpenMP [2.13.2, critical construct, Description]
12305 // ... where hint-expression is an integer constant expression that evaluates
12306 // to a valid lock hint.
12307 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
12308 if (HintExpr.isInvalid())
12309 return nullptr;
12310 return new (Context)
12311 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
12312}
12313
Carlo Bertollib4adf552016-01-15 18:50:31 +000012314OMPClause *Sema::ActOnOpenMPDistScheduleClause(
12315 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
12316 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
12317 SourceLocation EndLoc) {
12318 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
12319 std::string Values;
12320 Values += "'";
12321 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
12322 Values += "'";
12323 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12324 << Values << getOpenMPClauseName(OMPC_dist_schedule);
12325 return nullptr;
12326 }
12327 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012328 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012329 if (ChunkSize) {
12330 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12331 !ChunkSize->isInstantiationDependent() &&
12332 !ChunkSize->containsUnexpandedParameterPack()) {
12333 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
12334 ExprResult Val =
12335 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12336 if (Val.isInvalid())
12337 return nullptr;
12338
12339 ValExpr = Val.get();
12340
12341 // OpenMP [2.7.1, Restrictions]
12342 // chunk_size must be a loop invariant integer expression with a positive
12343 // value.
12344 llvm::APSInt Result;
12345 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12346 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12347 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
12348 << "dist_schedule" << ChunkSize->getSourceRange();
12349 return nullptr;
12350 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012351 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
12352 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000012353 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12354 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12355 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012356 }
12357 }
12358 }
12359
12360 return new (Context)
12361 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000012362 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012363}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012364
12365OMPClause *Sema::ActOnOpenMPDefaultmapClause(
12366 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12367 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12368 SourceLocation KindLoc, SourceLocation EndLoc) {
12369 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000012370 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012371 std::string Value;
12372 SourceLocation Loc;
12373 Value += "'";
12374 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12375 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012376 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012377 Loc = MLoc;
12378 } else {
12379 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012380 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012381 Loc = KindLoc;
12382 }
12383 Value += "'";
12384 Diag(Loc, diag::err_omp_unexpected_clause_value)
12385 << Value << getOpenMPClauseName(OMPC_defaultmap);
12386 return nullptr;
12387 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000012388 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012389
12390 return new (Context)
12391 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12392}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012393
12394bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12395 DeclContext *CurLexicalContext = getCurLexicalContext();
12396 if (!CurLexicalContext->isFileContext() &&
12397 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000012398 !CurLexicalContext->isExternCXXContext() &&
12399 !isa<CXXRecordDecl>(CurLexicalContext) &&
12400 !isa<ClassTemplateDecl>(CurLexicalContext) &&
12401 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12402 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012403 Diag(Loc, diag::err_omp_region_not_file_context);
12404 return false;
12405 }
12406 if (IsInOpenMPDeclareTargetContext) {
12407 Diag(Loc, diag::err_omp_enclosed_declare_target);
12408 return false;
12409 }
12410
12411 IsInOpenMPDeclareTargetContext = true;
12412 return true;
12413}
12414
12415void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12416 assert(IsInOpenMPDeclareTargetContext &&
12417 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
12418
12419 IsInOpenMPDeclareTargetContext = false;
12420}
12421
David Majnemer9d168222016-08-05 17:44:54 +000012422void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12423 CXXScopeSpec &ScopeSpec,
12424 const DeclarationNameInfo &Id,
12425 OMPDeclareTargetDeclAttr::MapTypeTy MT,
12426 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012427 LookupResult Lookup(*this, Id, LookupOrdinaryName);
12428 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12429
12430 if (Lookup.isAmbiguous())
12431 return;
12432 Lookup.suppressDiagnostics();
12433
12434 if (!Lookup.isSingleResult()) {
12435 if (TypoCorrection Corrected =
12436 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12437 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12438 CTK_ErrorRecovery)) {
12439 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12440 << Id.getName());
12441 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12442 return;
12443 }
12444
12445 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12446 return;
12447 }
12448
12449 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12450 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12451 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12452 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
12453
12454 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
12455 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
12456 ND->addAttr(A);
12457 if (ASTMutationListener *ML = Context.getASTMutationListener())
12458 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
12459 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
12460 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12461 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12462 << Id.getName();
12463 }
12464 } else
12465 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12466}
12467
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012468static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12469 Sema &SemaRef, Decl *D) {
12470 if (!D)
12471 return;
12472 Decl *LD = nullptr;
12473 if (isa<TagDecl>(D)) {
12474 LD = cast<TagDecl>(D)->getDefinition();
12475 } else if (isa<VarDecl>(D)) {
12476 LD = cast<VarDecl>(D)->getDefinition();
12477
12478 // If this is an implicit variable that is legal and we do not need to do
12479 // anything.
12480 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012481 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12482 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12483 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012484 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012485 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012486 return;
12487 }
12488
12489 } else if (isa<FunctionDecl>(D)) {
12490 const FunctionDecl *FD = nullptr;
12491 if (cast<FunctionDecl>(D)->hasBody(FD))
12492 LD = const_cast<FunctionDecl *>(FD);
12493
12494 // If the definition is associated with the current declaration in the
12495 // target region (it can be e.g. a lambda) that is legal and we do not need
12496 // to do anything else.
12497 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012498 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12499 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12500 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012501 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012502 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012503 return;
12504 }
12505 }
12506 if (!LD)
12507 LD = D;
12508 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12509 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
12510 // Outlined declaration is not declared target.
12511 if (LD->isOutOfLine()) {
12512 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12513 SemaRef.Diag(SL, diag::note_used_here) << SR;
12514 } else {
12515 DeclContext *DC = LD->getDeclContext();
12516 while (DC) {
12517 if (isa<FunctionDecl>(DC) &&
12518 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
12519 break;
12520 DC = DC->getParent();
12521 }
12522 if (DC)
12523 return;
12524
12525 // Is not declared in target context.
12526 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12527 SemaRef.Diag(SL, diag::note_used_here) << SR;
12528 }
12529 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012530 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12531 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12532 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012533 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012534 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012535 }
12536}
12537
12538static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12539 Sema &SemaRef, DSAStackTy *Stack,
12540 ValueDecl *VD) {
12541 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
12542 return true;
12543 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
12544 return false;
12545 return true;
12546}
12547
12548void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
12549 if (!D || D->isInvalidDecl())
12550 return;
12551 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
12552 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
12553 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
12554 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12555 if (DSAStack->isThreadPrivate(VD)) {
12556 Diag(SL, diag::err_omp_threadprivate_in_target);
12557 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
12558 return;
12559 }
12560 }
12561 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
12562 // Problem if any with var declared with incomplete type will be reported
12563 // as normal, so no need to check it here.
12564 if ((E || !VD->getType()->isIncompleteType()) &&
12565 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
12566 // Mark decl as declared target to prevent further diagnostic.
12567 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012568 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12569 Context, OMPDeclareTargetDeclAttr::MT_To);
12570 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012571 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012572 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012573 }
12574 return;
12575 }
12576 }
12577 if (!E) {
12578 // Checking declaration inside declare target region.
12579 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
12580 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012581 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12582 Context, OMPDeclareTargetDeclAttr::MT_To);
12583 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012584 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012585 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012586 }
12587 return;
12588 }
12589 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
12590}
Samuel Antao661c0902016-05-26 17:39:58 +000012591
12592OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
12593 SourceLocation StartLoc,
12594 SourceLocation LParenLoc,
12595 SourceLocation EndLoc) {
12596 MappableVarListInfo MVLI(VarList);
12597 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
12598 if (MVLI.ProcessedVarList.empty())
12599 return nullptr;
12600
12601 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12602 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12603 MVLI.VarComponents);
12604}
Samuel Antaoec172c62016-05-26 17:49:04 +000012605
12606OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
12607 SourceLocation StartLoc,
12608 SourceLocation LParenLoc,
12609 SourceLocation EndLoc) {
12610 MappableVarListInfo MVLI(VarList);
12611 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
12612 if (MVLI.ProcessedVarList.empty())
12613 return nullptr;
12614
12615 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12616 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12617 MVLI.VarComponents);
12618}
Carlo Bertolli2404b172016-07-13 15:37:16 +000012619
12620OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
12621 SourceLocation StartLoc,
12622 SourceLocation LParenLoc,
12623 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000012624 MappableVarListInfo MVLI(VarList);
12625 SmallVector<Expr *, 8> PrivateCopies;
12626 SmallVector<Expr *, 8> Inits;
12627
Carlo Bertolli2404b172016-07-13 15:37:16 +000012628 for (auto &RefExpr : VarList) {
12629 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
12630 SourceLocation ELoc;
12631 SourceRange ERange;
12632 Expr *SimpleRefExpr = RefExpr;
12633 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12634 if (Res.second) {
12635 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000012636 MVLI.ProcessedVarList.push_back(RefExpr);
12637 PrivateCopies.push_back(nullptr);
12638 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012639 }
12640 ValueDecl *D = Res.first;
12641 if (!D)
12642 continue;
12643
12644 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000012645 Type = Type.getNonReferenceType().getUnqualifiedType();
12646
12647 auto *VD = dyn_cast<VarDecl>(D);
12648
12649 // Item should be a pointer or reference to pointer.
12650 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000012651 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
12652 << 0 << RefExpr->getSourceRange();
12653 continue;
12654 }
Samuel Antaocc10b852016-07-28 14:23:26 +000012655
12656 // Build the private variable and the expression that refers to it.
12657 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
12658 D->hasAttrs() ? &D->getAttrs() : nullptr);
12659 if (VDPrivate->isInvalidDecl())
12660 continue;
12661
12662 CurContext->addDecl(VDPrivate);
12663 auto VDPrivateRefExpr = buildDeclRefExpr(
12664 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
12665
12666 // Add temporary variable to initialize the private copy of the pointer.
12667 auto *VDInit =
12668 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
12669 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12670 RefExpr->getExprLoc());
12671 AddInitializerToDecl(VDPrivate,
12672 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012673 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000012674
12675 // If required, build a capture to implement the privatization initialized
12676 // with the current list item value.
12677 DeclRefExpr *Ref = nullptr;
12678 if (!VD)
12679 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12680 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
12681 PrivateCopies.push_back(VDPrivateRefExpr);
12682 Inits.push_back(VDInitRefExpr);
12683
12684 // We need to add a data sharing attribute for this variable to make sure it
12685 // is correctly captured. A variable that shows up in a use_device_ptr has
12686 // similar properties of a first private variable.
12687 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
12688
12689 // Create a mappable component for the list item. List items in this clause
12690 // only need a component.
12691 MVLI.VarBaseDeclarations.push_back(D);
12692 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12693 MVLI.VarComponents.back().push_back(
12694 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000012695 }
12696
Samuel Antaocc10b852016-07-28 14:23:26 +000012697 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000012698 return nullptr;
12699
Samuel Antaocc10b852016-07-28 14:23:26 +000012700 return OMPUseDevicePtrClause::Create(
12701 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12702 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012703}
Carlo Bertolli70594e92016-07-13 17:16:49 +000012704
12705OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
12706 SourceLocation StartLoc,
12707 SourceLocation LParenLoc,
12708 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000012709 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012710 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000012711 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000012712 SourceLocation ELoc;
12713 SourceRange ERange;
12714 Expr *SimpleRefExpr = RefExpr;
12715 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12716 if (Res.second) {
12717 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000012718 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012719 }
12720 ValueDecl *D = Res.first;
12721 if (!D)
12722 continue;
12723
12724 QualType Type = D->getType();
12725 // item should be a pointer or array or reference to pointer or array
12726 if (!Type.getNonReferenceType()->isPointerType() &&
12727 !Type.getNonReferenceType()->isArrayType()) {
12728 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
12729 << 0 << RefExpr->getSourceRange();
12730 continue;
12731 }
Samuel Antao6890b092016-07-28 14:25:09 +000012732
12733 // Check if the declaration in the clause does not show up in any data
12734 // sharing attribute.
12735 auto DVar = DSAStack->getTopDSA(D, false);
12736 if (isOpenMPPrivate(DVar.CKind)) {
12737 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12738 << getOpenMPClauseName(DVar.CKind)
12739 << getOpenMPClauseName(OMPC_is_device_ptr)
12740 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12741 ReportOriginalDSA(*this, DSAStack, D, DVar);
12742 continue;
12743 }
12744
12745 Expr *ConflictExpr;
12746 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012747 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012748 [&ConflictExpr](
12749 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
12750 OpenMPClauseKind) -> bool {
12751 ConflictExpr = R.front().getAssociatedExpression();
12752 return true;
12753 })) {
12754 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
12755 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
12756 << ConflictExpr->getSourceRange();
12757 continue;
12758 }
12759
12760 // Store the components in the stack so that they can be used to check
12761 // against other clauses later on.
12762 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
12763 DSAStack->addMappableExpressionComponents(
12764 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
12765
12766 // Record the expression we've just processed.
12767 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
12768
12769 // Create a mappable component for the list item. List items in this clause
12770 // only need a component. We use a null declaration to signal fields in
12771 // 'this'.
12772 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
12773 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
12774 "Unexpected device pointer expression!");
12775 MVLI.VarBaseDeclarations.push_back(
12776 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
12777 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12778 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012779 }
12780
Samuel Antao6890b092016-07-28 14:25:09 +000012781 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000012782 return nullptr;
12783
Samuel Antao6890b092016-07-28 14:25:09 +000012784 return OMPIsDevicePtrClause::Create(
12785 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12786 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012787}