blob: 7e7391d2517f7a01c76566e1efb787a88f307fba [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
Alexey Bataev2ba67042017-11-28 21:11:44 +00002397 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2398 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00002399 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002400 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00002401 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002402 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002403 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002404 for (auto *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002405 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2406 Clause->getClauseKind() == OMPC_in_reduction) {
2407 // Capture taskgroup task_reduction descriptors inside the tasking regions
2408 // with the corresponding in_reduction items.
2409 auto *IRC = cast<OMPInReductionClause>(Clause);
2410 for (auto *E : IRC->taskgroup_descriptors())
2411 if (E)
2412 MarkDeclarationsReferencedInExpr(E);
2413 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002414 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002415 Clause->getClauseKind() == OMPC_copyprivate ||
2416 (getLangOpts().OpenMPUseTLS &&
2417 getASTContext().getTargetInfo().isTLSSupported() &&
2418 Clause->getClauseKind() == OMPC_copyin)) {
2419 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002420 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002421 for (auto *VarRef : Clause->children()) {
2422 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002423 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002424 }
2425 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002426 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00002427 } else if (CaptureRegions.size() > 1 ||
2428 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002429 if (auto *C = OMPClauseWithPreInit::get(Clause))
2430 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002431 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2432 if (auto *E = C->getPostUpdateExpr())
2433 MarkDeclarationsReferencedInExpr(E);
2434 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002435 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002436 if (Clause->getClauseKind() == OMPC_schedule)
2437 SC = cast<OMPScheduleClause>(Clause);
2438 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002439 OC = cast<OMPOrderedClause>(Clause);
2440 else if (Clause->getClauseKind() == OMPC_linear)
2441 LCs.push_back(cast<OMPLinearClause>(Clause));
2442 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002443 // OpenMP, 2.7.1 Loop Construct, Restrictions
2444 // The nonmonotonic modifier cannot be specified if an ordered clause is
2445 // specified.
2446 if (SC &&
2447 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2448 SC->getSecondScheduleModifier() ==
2449 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2450 OC) {
2451 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2452 ? SC->getFirstScheduleModifierLoc()
2453 : SC->getSecondScheduleModifierLoc(),
2454 diag::err_omp_schedule_nonmonotonic_ordered)
2455 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2456 ErrorFound = true;
2457 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002458 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2459 for (auto *C : LCs) {
2460 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2461 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2462 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002463 ErrorFound = true;
2464 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002465 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2466 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2467 OC->getNumForLoops()) {
2468 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2469 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2470 ErrorFound = true;
2471 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002472 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002473 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002474 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002475 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00002476 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002477 // Mark all variables in private list clauses as used in inner region.
2478 // Required for proper codegen of combined directives.
2479 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00002480 if (ThisCaptureRegion != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002481 for (auto *C : PICs) {
2482 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2483 // Find the particular capture region for the clause if the
2484 // directive is a combined one with multiple capture regions.
2485 // If the directive is not a combined one, the capture region
2486 // associated with the clause is OMPD_unknown and is generated
2487 // only once.
2488 if (CaptureRegion == ThisCaptureRegion ||
2489 CaptureRegion == OMPD_unknown) {
2490 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2491 for (auto *D : DS->decls())
2492 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2493 }
2494 }
2495 }
2496 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002497 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002498 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002499 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002500}
2501
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002502static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2503 OpenMPDirectiveKind CancelRegion,
2504 SourceLocation StartLoc) {
2505 // CancelRegion is only needed for cancel and cancellation_point.
2506 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2507 return false;
2508
2509 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2510 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2511 return false;
2512
2513 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2514 << getOpenMPDirectiveName(CancelRegion);
2515 return true;
2516}
2517
2518static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002519 OpenMPDirectiveKind CurrentRegion,
2520 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002521 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002522 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002523 if (Stack->getCurScope()) {
2524 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002525 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002526 bool NestingProhibited = false;
2527 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002528 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002529 enum {
2530 NoRecommend,
2531 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002532 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002533 ShouldBeInTargetRegion,
2534 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002535 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002536 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002537 // OpenMP [2.16, Nesting of Regions]
2538 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002539 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002540 // An ordered construct with the simd clause is the only OpenMP
2541 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002542 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002543 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2544 // message.
2545 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2546 ? diag::err_omp_prohibited_region_simd
2547 : diag::warn_omp_nesting_simd);
2548 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002549 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002550 if (ParentRegion == OMPD_atomic) {
2551 // OpenMP [2.16, Nesting of Regions]
2552 // OpenMP constructs may not be nested inside an atomic region.
2553 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2554 return true;
2555 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002556 if (CurrentRegion == OMPD_section) {
2557 // OpenMP [2.7.2, sections Construct, Restrictions]
2558 // Orphaned section directives are prohibited. That is, the section
2559 // directives must appear within the sections construct and must not be
2560 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002561 if (ParentRegion != OMPD_sections &&
2562 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002563 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2564 << (ParentRegion != OMPD_unknown)
2565 << getOpenMPDirectiveName(ParentRegion);
2566 return true;
2567 }
2568 return false;
2569 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002570 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002571 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002572 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002573 if (ParentRegion == OMPD_unknown &&
2574 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002575 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002576 if (CurrentRegion == OMPD_cancellation_point ||
2577 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002578 // OpenMP [2.16, Nesting of Regions]
2579 // A cancellation point construct for which construct-type-clause is
2580 // taskgroup must be nested inside a task construct. A cancellation
2581 // point construct for which construct-type-clause is not taskgroup must
2582 // be closely nested inside an OpenMP construct that matches the type
2583 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002584 // A cancel construct for which construct-type-clause is taskgroup must be
2585 // nested inside a task construct. A cancel construct for which
2586 // construct-type-clause is not taskgroup must be closely nested inside an
2587 // OpenMP construct that matches the type specified in
2588 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002589 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002590 !((CancelRegion == OMPD_parallel &&
2591 (ParentRegion == OMPD_parallel ||
2592 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002593 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002594 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002595 ParentRegion == OMPD_target_parallel_for ||
2596 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00002597 ParentRegion == OMPD_teams_distribute_parallel_for ||
2598 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002599 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2600 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002601 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2602 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002603 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002604 // OpenMP [2.16, Nesting of Regions]
2605 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002606 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002607 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002608 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002609 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2610 // OpenMP [2.16, Nesting of Regions]
2611 // A critical region may not be nested (closely or otherwise) inside a
2612 // critical region with the same name. Note that this restriction is not
2613 // sufficient to prevent deadlock.
2614 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002615 bool DeadLock = Stack->hasDirective(
2616 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2617 const DeclarationNameInfo &DNI,
2618 SourceLocation Loc) -> bool {
2619 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2620 PreviousCriticalLoc = Loc;
2621 return true;
2622 } else
2623 return false;
2624 },
2625 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002626 if (DeadLock) {
2627 SemaRef.Diag(StartLoc,
2628 diag::err_omp_prohibited_region_critical_same_name)
2629 << CurrentName.getName();
2630 if (PreviousCriticalLoc.isValid())
2631 SemaRef.Diag(PreviousCriticalLoc,
2632 diag::note_omp_previous_critical_region);
2633 return true;
2634 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002635 } else if (CurrentRegion == OMPD_barrier) {
2636 // OpenMP [2.16, Nesting of Regions]
2637 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002638 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002639 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2640 isOpenMPTaskingDirective(ParentRegion) ||
2641 ParentRegion == OMPD_master ||
2642 ParentRegion == OMPD_critical ||
2643 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002644 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002645 !isOpenMPParallelDirective(CurrentRegion) &&
2646 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002647 // OpenMP [2.16, Nesting of Regions]
2648 // A worksharing region may not be closely nested inside a worksharing,
2649 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002650 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2651 isOpenMPTaskingDirective(ParentRegion) ||
2652 ParentRegion == OMPD_master ||
2653 ParentRegion == OMPD_critical ||
2654 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002655 Recommend = ShouldBeInParallelRegion;
2656 } else if (CurrentRegion == OMPD_ordered) {
2657 // OpenMP [2.16, Nesting of Regions]
2658 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002659 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002660 // An ordered region must be closely nested inside a loop region (or
2661 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002662 // OpenMP [2.8.1,simd Construct, Restrictions]
2663 // An ordered construct with the simd clause is the only OpenMP construct
2664 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002665 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002666 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002667 !(isOpenMPSimdDirective(ParentRegion) ||
2668 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002669 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002670 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002671 // OpenMP [2.16, Nesting of Regions]
2672 // If specified, a teams construct must be contained within a target
2673 // construct.
2674 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002675 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002676 Recommend = ShouldBeInTargetRegion;
2677 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2678 }
Kelvin Libf594a52016-12-17 05:48:59 +00002679 if (!NestingProhibited &&
2680 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2681 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2682 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002683 // OpenMP [2.16, Nesting of Regions]
2684 // distribute, parallel, parallel sections, parallel workshare, and the
2685 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2686 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002687 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2688 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002689 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002690 }
David Majnemer9d168222016-08-05 17:44:54 +00002691 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002692 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002693 // OpenMP 4.5 [2.17 Nesting of Regions]
2694 // The region associated with the distribute construct must be strictly
2695 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002696 NestingProhibited =
2697 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002698 Recommend = ShouldBeInTeamsRegion;
2699 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002700 if (!NestingProhibited &&
2701 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2702 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2703 // OpenMP 4.5 [2.17 Nesting of Regions]
2704 // If a target, target update, target data, target enter data, or
2705 // target exit data construct is encountered during execution of a
2706 // target region, the behavior is unspecified.
2707 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002708 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2709 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002710 if (isOpenMPTargetExecutionDirective(K)) {
2711 OffendingRegion = K;
2712 return true;
2713 } else
2714 return false;
2715 },
2716 false /* don't skip top directive */);
2717 CloseNesting = false;
2718 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002719 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002720 if (OrphanSeen) {
2721 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2722 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2723 } else {
2724 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2725 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2726 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2727 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002728 return true;
2729 }
2730 }
2731 return false;
2732}
2733
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002734static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2735 ArrayRef<OMPClause *> Clauses,
2736 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2737 bool ErrorFound = false;
2738 unsigned NamedModifiersNumber = 0;
2739 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2740 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002741 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002742 for (const auto *C : Clauses) {
2743 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2744 // At most one if clause without a directive-name-modifier can appear on
2745 // the directive.
2746 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2747 if (FoundNameModifiers[CurNM]) {
2748 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2749 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2750 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2751 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002752 } else if (CurNM != OMPD_unknown) {
2753 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002754 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002755 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002756 FoundNameModifiers[CurNM] = IC;
2757 if (CurNM == OMPD_unknown)
2758 continue;
2759 // Check if the specified name modifier is allowed for the current
2760 // directive.
2761 // At most one if clause with the particular directive-name-modifier can
2762 // appear on the directive.
2763 bool MatchFound = false;
2764 for (auto NM : AllowedNameModifiers) {
2765 if (CurNM == NM) {
2766 MatchFound = true;
2767 break;
2768 }
2769 }
2770 if (!MatchFound) {
2771 S.Diag(IC->getNameModifierLoc(),
2772 diag::err_omp_wrong_if_directive_name_modifier)
2773 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2774 ErrorFound = true;
2775 }
2776 }
2777 }
2778 // If any if clause on the directive includes a directive-name-modifier then
2779 // all if clauses on the directive must include a directive-name-modifier.
2780 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2781 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2782 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2783 diag::err_omp_no_more_if_clause);
2784 } else {
2785 std::string Values;
2786 std::string Sep(", ");
2787 unsigned AllowedCnt = 0;
2788 unsigned TotalAllowedNum =
2789 AllowedNameModifiers.size() - NamedModifiersNumber;
2790 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2791 ++Cnt) {
2792 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2793 if (!FoundNameModifiers[NM]) {
2794 Values += "'";
2795 Values += getOpenMPDirectiveName(NM);
2796 Values += "'";
2797 if (AllowedCnt + 2 == TotalAllowedNum)
2798 Values += " or ";
2799 else if (AllowedCnt + 1 != TotalAllowedNum)
2800 Values += Sep;
2801 ++AllowedCnt;
2802 }
2803 }
2804 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2805 diag::err_omp_unnamed_if_clause)
2806 << (TotalAllowedNum > 1) << Values;
2807 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002808 for (auto Loc : NameModifierLoc) {
2809 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2810 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002811 ErrorFound = true;
2812 }
2813 return ErrorFound;
2814}
2815
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002816StmtResult Sema::ActOnOpenMPExecutableDirective(
2817 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2818 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2819 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002820 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002821 // First check CancelRegion which is then used in checkNestingOfRegions.
2822 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2823 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002824 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002825 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002826
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002827 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002828 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002829 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002830 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002831 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002832 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2833
2834 // Check default data sharing attributes for referenced variables.
2835 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002836 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2837 Stmt *S = AStmt;
2838 while (--ThisCaptureLevel >= 0)
2839 S = cast<CapturedStmt>(S)->getCapturedStmt();
2840 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002841 if (DSAChecker.isErrorFound())
2842 return StmtError();
2843 // Generate list of implicitly defined firstprivate variables.
2844 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002845
Alexey Bataev88202be2017-07-27 13:20:36 +00002846 SmallVector<Expr *, 4> ImplicitFirstprivates(
2847 DSAChecker.getImplicitFirstprivate().begin(),
2848 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002849 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
2850 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00002851 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
2852 for (auto *C : Clauses) {
2853 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
2854 for (auto *E : IRC->taskgroup_descriptors())
2855 if (E)
2856 ImplicitFirstprivates.emplace_back(E);
2857 }
2858 }
2859 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002860 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00002861 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
2862 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002863 ClausesWithImplicit.push_back(Implicit);
2864 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00002865 ImplicitFirstprivates.size();
Alexey Bataev68446b72014-07-18 07:47:19 +00002866 } else
2867 ErrorFound = true;
2868 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002869 if (!ImplicitMaps.empty()) {
2870 if (OMPClause *Implicit = ActOnOpenMPMapClause(
2871 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
2872 SourceLocation(), SourceLocation(), ImplicitMaps,
2873 SourceLocation(), SourceLocation(), SourceLocation())) {
2874 ClausesWithImplicit.emplace_back(Implicit);
2875 ErrorFound |=
2876 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
2877 } else
2878 ErrorFound = true;
2879 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002880 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002881
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002882 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002883 switch (Kind) {
2884 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002885 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2886 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002887 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002888 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002889 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002890 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2891 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002892 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002893 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002894 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2895 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002896 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002897 case OMPD_for_simd:
2898 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2899 EndLoc, VarsWithInheritedDSA);
2900 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002901 case OMPD_sections:
2902 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2903 EndLoc);
2904 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002905 case OMPD_section:
2906 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002907 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002908 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2909 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002910 case OMPD_single:
2911 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2912 EndLoc);
2913 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002914 case OMPD_master:
2915 assert(ClausesWithImplicit.empty() &&
2916 "No clauses are allowed for 'omp master' directive");
2917 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2918 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002919 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002920 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2921 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002922 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002923 case OMPD_parallel_for:
2924 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2925 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002926 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002927 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002928 case OMPD_parallel_for_simd:
2929 Res = ActOnOpenMPParallelForSimdDirective(
2930 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002931 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002932 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002933 case OMPD_parallel_sections:
2934 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2935 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002936 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002937 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002938 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002939 Res =
2940 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002941 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002942 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002943 case OMPD_taskyield:
2944 assert(ClausesWithImplicit.empty() &&
2945 "No clauses are allowed for 'omp taskyield' directive");
2946 assert(AStmt == nullptr &&
2947 "No associated statement allowed for 'omp taskyield' directive");
2948 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2949 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002950 case OMPD_barrier:
2951 assert(ClausesWithImplicit.empty() &&
2952 "No clauses are allowed for 'omp barrier' directive");
2953 assert(AStmt == nullptr &&
2954 "No associated statement allowed for 'omp barrier' directive");
2955 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2956 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002957 case OMPD_taskwait:
2958 assert(ClausesWithImplicit.empty() &&
2959 "No clauses are allowed for 'omp taskwait' directive");
2960 assert(AStmt == nullptr &&
2961 "No associated statement allowed for 'omp taskwait' directive");
2962 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2963 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002964 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00002965 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
2966 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002967 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002968 case OMPD_flush:
2969 assert(AStmt == nullptr &&
2970 "No associated statement allowed for 'omp flush' directive");
2971 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2972 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002973 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002974 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2975 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002976 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002977 case OMPD_atomic:
2978 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2979 EndLoc);
2980 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002981 case OMPD_teams:
2982 Res =
2983 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2984 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002985 case OMPD_target:
2986 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2987 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002988 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002989 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002990 case OMPD_target_parallel:
2991 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2992 StartLoc, EndLoc);
2993 AllowedNameModifiers.push_back(OMPD_target);
2994 AllowedNameModifiers.push_back(OMPD_parallel);
2995 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002996 case OMPD_target_parallel_for:
2997 Res = ActOnOpenMPTargetParallelForDirective(
2998 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2999 AllowedNameModifiers.push_back(OMPD_target);
3000 AllowedNameModifiers.push_back(OMPD_parallel);
3001 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003002 case OMPD_cancellation_point:
3003 assert(ClausesWithImplicit.empty() &&
3004 "No clauses are allowed for 'omp cancellation point' directive");
3005 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3006 "cancellation point' directive");
3007 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3008 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003009 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003010 assert(AStmt == nullptr &&
3011 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003012 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3013 CancelRegion);
3014 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003015 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003016 case OMPD_target_data:
3017 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3018 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003019 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003020 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003021 case OMPD_target_enter_data:
3022 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003023 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003024 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3025 break;
Samuel Antao72590762016-01-19 20:04:50 +00003026 case OMPD_target_exit_data:
3027 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003028 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003029 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3030 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003031 case OMPD_taskloop:
3032 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3033 EndLoc, VarsWithInheritedDSA);
3034 AllowedNameModifiers.push_back(OMPD_taskloop);
3035 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003036 case OMPD_taskloop_simd:
3037 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3038 EndLoc, VarsWithInheritedDSA);
3039 AllowedNameModifiers.push_back(OMPD_taskloop);
3040 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003041 case OMPD_distribute:
3042 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3043 EndLoc, VarsWithInheritedDSA);
3044 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003045 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003046 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3047 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003048 AllowedNameModifiers.push_back(OMPD_target_update);
3049 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003050 case OMPD_distribute_parallel_for:
3051 Res = ActOnOpenMPDistributeParallelForDirective(
3052 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3053 AllowedNameModifiers.push_back(OMPD_parallel);
3054 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003055 case OMPD_distribute_parallel_for_simd:
3056 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3057 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3058 AllowedNameModifiers.push_back(OMPD_parallel);
3059 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003060 case OMPD_distribute_simd:
3061 Res = ActOnOpenMPDistributeSimdDirective(
3062 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3063 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003064 case OMPD_target_parallel_for_simd:
3065 Res = ActOnOpenMPTargetParallelForSimdDirective(
3066 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3067 AllowedNameModifiers.push_back(OMPD_target);
3068 AllowedNameModifiers.push_back(OMPD_parallel);
3069 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003070 case OMPD_target_simd:
3071 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3072 EndLoc, VarsWithInheritedDSA);
3073 AllowedNameModifiers.push_back(OMPD_target);
3074 break;
Kelvin Li02532872016-08-05 14:37:37 +00003075 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003076 Res = ActOnOpenMPTeamsDistributeDirective(
3077 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003078 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003079 case OMPD_teams_distribute_simd:
3080 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3081 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3082 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003083 case OMPD_teams_distribute_parallel_for_simd:
3084 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3085 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3086 AllowedNameModifiers.push_back(OMPD_parallel);
3087 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003088 case OMPD_teams_distribute_parallel_for:
3089 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3090 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3091 AllowedNameModifiers.push_back(OMPD_parallel);
3092 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003093 case OMPD_target_teams:
3094 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3095 EndLoc);
3096 AllowedNameModifiers.push_back(OMPD_target);
3097 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003098 case OMPD_target_teams_distribute:
3099 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3100 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3101 AllowedNameModifiers.push_back(OMPD_target);
3102 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003103 case OMPD_target_teams_distribute_parallel_for:
3104 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3105 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3106 AllowedNameModifiers.push_back(OMPD_target);
3107 AllowedNameModifiers.push_back(OMPD_parallel);
3108 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003109 case OMPD_target_teams_distribute_parallel_for_simd:
3110 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3111 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3112 AllowedNameModifiers.push_back(OMPD_target);
3113 AllowedNameModifiers.push_back(OMPD_parallel);
3114 break;
Kelvin Lida681182017-01-10 18:08:18 +00003115 case OMPD_target_teams_distribute_simd:
3116 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3117 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3118 AllowedNameModifiers.push_back(OMPD_target);
3119 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003120 case OMPD_declare_target:
3121 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003122 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003123 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003124 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003125 llvm_unreachable("OpenMP Directive is not allowed");
3126 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003127 llvm_unreachable("Unknown OpenMP directive");
3128 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003129
Alexey Bataev4acb8592014-07-07 13:01:15 +00003130 for (auto P : VarsWithInheritedDSA) {
3131 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3132 << P.first << P.second->getSourceRange();
3133 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003134 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3135
3136 if (!AllowedNameModifiers.empty())
3137 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3138 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003139
Alexey Bataeved09d242014-05-28 05:53:51 +00003140 if (ErrorFound)
3141 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003142 return Res;
3143}
3144
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003145Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3146 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003147 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003148 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3149 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003150 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003151 assert(Linears.size() == LinModifiers.size());
3152 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003153 if (!DG || DG.get().isNull())
3154 return DeclGroupPtrTy();
3155
3156 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003157 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003158 return DG;
3159 }
3160 auto *ADecl = DG.get().getSingleDecl();
3161 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3162 ADecl = FTD->getTemplatedDecl();
3163
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003164 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3165 if (!FD) {
3166 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003167 return DeclGroupPtrTy();
3168 }
3169
Alexey Bataev2af33e32016-04-07 12:45:37 +00003170 // OpenMP [2.8.2, declare simd construct, Description]
3171 // The parameter of the simdlen clause must be a constant positive integer
3172 // expression.
3173 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003174 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003175 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003176 // OpenMP [2.8.2, declare simd construct, Description]
3177 // The special this pointer can be used as if was one of the arguments to the
3178 // function in any of the linear, aligned, or uniform clauses.
3179 // The uniform clause declares one or more arguments to have an invariant
3180 // value for all concurrent invocations of the function in the execution of a
3181 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00003182 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3183 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003184 for (auto *E : Uniforms) {
3185 E = E->IgnoreParenImpCasts();
3186 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3187 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3188 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3189 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003190 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3191 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003192 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003193 }
3194 if (isa<CXXThisExpr>(E)) {
3195 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003196 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003197 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003198 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3199 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003200 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003201 // OpenMP [2.8.2, declare simd construct, Description]
3202 // The aligned clause declares that the object to which each list item points
3203 // is aligned to the number of bytes expressed in the optional parameter of
3204 // the aligned clause.
3205 // The special this pointer can be used as if was one of the arguments to the
3206 // function in any of the linear, aligned, or uniform clauses.
3207 // The type of list items appearing in the aligned clause must be array,
3208 // pointer, reference to array, or reference to pointer.
3209 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3210 Expr *AlignedThis = nullptr;
3211 for (auto *E : Aligneds) {
3212 E = E->IgnoreParenImpCasts();
3213 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3214 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3215 auto *CanonPVD = PVD->getCanonicalDecl();
3216 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3217 FD->getParamDecl(PVD->getFunctionScopeIndex())
3218 ->getCanonicalDecl() == CanonPVD) {
3219 // OpenMP [2.8.1, simd construct, Restrictions]
3220 // A list-item cannot appear in more than one aligned clause.
3221 if (AlignedArgs.count(CanonPVD) > 0) {
3222 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3223 << 1 << E->getSourceRange();
3224 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3225 diag::note_omp_explicit_dsa)
3226 << getOpenMPClauseName(OMPC_aligned);
3227 continue;
3228 }
3229 AlignedArgs[CanonPVD] = E;
3230 QualType QTy = PVD->getType()
3231 .getNonReferenceType()
3232 .getUnqualifiedType()
3233 .getCanonicalType();
3234 const Type *Ty = QTy.getTypePtrOrNull();
3235 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3236 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3237 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3238 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3239 }
3240 continue;
3241 }
3242 }
3243 if (isa<CXXThisExpr>(E)) {
3244 if (AlignedThis) {
3245 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3246 << 2 << E->getSourceRange();
3247 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3248 << getOpenMPClauseName(OMPC_aligned);
3249 }
3250 AlignedThis = E;
3251 continue;
3252 }
3253 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3254 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3255 }
3256 // The optional parameter of the aligned clause, alignment, must be a constant
3257 // positive integer expression. If no optional parameter is specified,
3258 // implementation-defined default alignments for SIMD instructions on the
3259 // target platforms are assumed.
3260 SmallVector<Expr *, 4> NewAligns;
3261 for (auto *E : Alignments) {
3262 ExprResult Align;
3263 if (E)
3264 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3265 NewAligns.push_back(Align.get());
3266 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003267 // OpenMP [2.8.2, declare simd construct, Description]
3268 // The linear clause declares one or more list items to be private to a SIMD
3269 // lane and to have a linear relationship with respect to the iteration space
3270 // of a loop.
3271 // The special this pointer can be used as if was one of the arguments to the
3272 // function in any of the linear, aligned, or uniform clauses.
3273 // When a linear-step expression is specified in a linear clause it must be
3274 // either a constant integer expression or an integer-typed parameter that is
3275 // specified in a uniform clause on the directive.
3276 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3277 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3278 auto MI = LinModifiers.begin();
3279 for (auto *E : Linears) {
3280 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3281 ++MI;
3282 E = E->IgnoreParenImpCasts();
3283 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3284 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3285 auto *CanonPVD = PVD->getCanonicalDecl();
3286 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3287 FD->getParamDecl(PVD->getFunctionScopeIndex())
3288 ->getCanonicalDecl() == CanonPVD) {
3289 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3290 // A list-item cannot appear in more than one linear clause.
3291 if (LinearArgs.count(CanonPVD) > 0) {
3292 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3293 << getOpenMPClauseName(OMPC_linear)
3294 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3295 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3296 diag::note_omp_explicit_dsa)
3297 << getOpenMPClauseName(OMPC_linear);
3298 continue;
3299 }
3300 // Each argument can appear in at most one uniform or linear clause.
3301 if (UniformedArgs.count(CanonPVD) > 0) {
3302 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3303 << getOpenMPClauseName(OMPC_linear)
3304 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3305 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3306 diag::note_omp_explicit_dsa)
3307 << getOpenMPClauseName(OMPC_uniform);
3308 continue;
3309 }
3310 LinearArgs[CanonPVD] = E;
3311 if (E->isValueDependent() || E->isTypeDependent() ||
3312 E->isInstantiationDependent() ||
3313 E->containsUnexpandedParameterPack())
3314 continue;
3315 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3316 PVD->getOriginalType());
3317 continue;
3318 }
3319 }
3320 if (isa<CXXThisExpr>(E)) {
3321 if (UniformedLinearThis) {
3322 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3323 << getOpenMPClauseName(OMPC_linear)
3324 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3325 << E->getSourceRange();
3326 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3327 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3328 : OMPC_linear);
3329 continue;
3330 }
3331 UniformedLinearThis = E;
3332 if (E->isValueDependent() || E->isTypeDependent() ||
3333 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3334 continue;
3335 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3336 E->getType());
3337 continue;
3338 }
3339 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3340 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3341 }
3342 Expr *Step = nullptr;
3343 Expr *NewStep = nullptr;
3344 SmallVector<Expr *, 4> NewSteps;
3345 for (auto *E : Steps) {
3346 // Skip the same step expression, it was checked already.
3347 if (Step == E || !E) {
3348 NewSteps.push_back(E ? NewStep : nullptr);
3349 continue;
3350 }
3351 Step = E;
3352 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3353 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3354 auto *CanonPVD = PVD->getCanonicalDecl();
3355 if (UniformedArgs.count(CanonPVD) == 0) {
3356 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3357 << Step->getSourceRange();
3358 } else if (E->isValueDependent() || E->isTypeDependent() ||
3359 E->isInstantiationDependent() ||
3360 E->containsUnexpandedParameterPack() ||
3361 CanonPVD->getType()->hasIntegerRepresentation())
3362 NewSteps.push_back(Step);
3363 else {
3364 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3365 << Step->getSourceRange();
3366 }
3367 continue;
3368 }
3369 NewStep = Step;
3370 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3371 !Step->isInstantiationDependent() &&
3372 !Step->containsUnexpandedParameterPack()) {
3373 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3374 .get();
3375 if (NewStep)
3376 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3377 }
3378 NewSteps.push_back(NewStep);
3379 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003380 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3381 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003382 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003383 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3384 const_cast<Expr **>(Linears.data()), Linears.size(),
3385 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3386 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003387 ADecl->addAttr(NewAttr);
3388 return ConvertDeclToDeclGroup(ADecl);
3389}
3390
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003391StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3392 Stmt *AStmt,
3393 SourceLocation StartLoc,
3394 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003395 if (!AStmt)
3396 return StmtError();
3397
Alexey Bataev9959db52014-05-06 10:08:46 +00003398 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3399 // 1.2.2 OpenMP Language Terminology
3400 // Structured block - An executable statement with a single entry at the
3401 // top and a single exit at the bottom.
3402 // The point of exit cannot be a branch out of the structured block.
3403 // longjmp() and throw() must not violate the entry/exit criteria.
3404 CS->getCapturedDecl()->setNothrow();
3405
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003406 getCurFunction()->setHasBranchProtectedScope();
3407
Alexey Bataev25e5b442015-09-15 12:52:43 +00003408 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3409 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003410}
3411
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003412namespace {
3413/// \brief Helper class for checking canonical form of the OpenMP loops and
3414/// extracting iteration space of each loop in the loop nest, that will be used
3415/// for IR generation.
3416class OpenMPIterationSpaceChecker {
3417 /// \brief Reference to Sema.
3418 Sema &SemaRef;
3419 /// \brief A location for diagnostics (when there is no some better location).
3420 SourceLocation DefaultLoc;
3421 /// \brief A location for diagnostics (when increment is not compatible).
3422 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003423 /// \brief A source location for referring to loop init later.
3424 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003425 /// \brief A source location for referring to condition later.
3426 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003427 /// \brief A source location for referring to increment later.
3428 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003429 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003430 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003431 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003432 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003433 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003434 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003435 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003436 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003437 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003438 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003439 /// \brief This flag is true when condition is one of:
3440 /// Var < UB
3441 /// Var <= UB
3442 /// UB > Var
3443 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003444 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003445 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003446 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003447 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003448 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003449
3450public:
3451 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003452 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003453 /// \brief Check init-expr for canonical loop form and save loop counter
3454 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003455 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003456 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3457 /// for less/greater and for strict/non-strict comparison.
3458 bool CheckCond(Expr *S);
3459 /// \brief Check incr-expr for canonical loop form and return true if it
3460 /// does not conform, otherwise save loop step (#Step).
3461 bool CheckInc(Expr *S);
3462 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003463 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003464 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003465 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003466 /// \brief Source range of the loop init.
3467 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3468 /// \brief Source range of the loop condition.
3469 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3470 /// \brief Source range of the loop increment.
3471 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3472 /// \brief True if the step should be subtracted.
3473 bool ShouldSubtractStep() const { return SubtractStep; }
3474 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003475 Expr *
3476 BuildNumIterations(Scope *S, const bool LimitedType,
3477 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003478 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003479 Expr *BuildPreCond(Scope *S, Expr *Cond,
3480 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003481 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003482 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3483 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003484 /// \brief Build reference expression to the private counter be used for
3485 /// codegen.
3486 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003487 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003488 Expr *BuildCounterInit() const;
3489 /// \brief Build step of the counter be used for codegen.
3490 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003491 /// \brief Return true if any expression is dependent.
3492 bool Dependent() const;
3493
3494private:
3495 /// \brief Check the right-hand side of an assignment in the increment
3496 /// expression.
3497 bool CheckIncRHS(Expr *RHS);
3498 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003499 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003500 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003501 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003502 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003503 /// \brief Helper to set loop increment.
3504 bool SetStep(Expr *NewStep, bool Subtract);
3505};
3506
3507bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003508 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003509 assert(!LB && !UB && !Step);
3510 return false;
3511 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003512 return LCDecl->getType()->isDependentType() ||
3513 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3514 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003515}
3516
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003517bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3518 Expr *NewLCRefExpr,
3519 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003520 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003521 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003522 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003523 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003524 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003525 LCDecl = getCanonicalDecl(NewLCDecl);
3526 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003527 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3528 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003529 if ((Ctor->isCopyOrMoveConstructor() ||
3530 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3531 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003532 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003533 LB = NewLB;
3534 return false;
3535}
3536
3537bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003538 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003539 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003540 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3541 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003542 if (!NewUB)
3543 return true;
3544 UB = NewUB;
3545 TestIsLessOp = LessOp;
3546 TestIsStrictOp = StrictOp;
3547 ConditionSrcRange = SR;
3548 ConditionLoc = SL;
3549 return false;
3550}
3551
3552bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3553 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003554 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003555 if (!NewStep)
3556 return true;
3557 if (!NewStep->isValueDependent()) {
3558 // Check that the step is integer expression.
3559 SourceLocation StepLoc = NewStep->getLocStart();
Alexey Bataev5372fb82017-08-31 23:06:52 +00003560 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3561 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003562 if (Val.isInvalid())
3563 return true;
3564 NewStep = Val.get();
3565
3566 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3567 // If test-expr is of form var relational-op b and relational-op is < or
3568 // <= then incr-expr must cause var to increase on each iteration of the
3569 // loop. If test-expr is of form var relational-op b and relational-op is
3570 // > or >= then incr-expr must cause var to decrease on each iteration of
3571 // the loop.
3572 // If test-expr is of form b relational-op var and relational-op is < or
3573 // <= then incr-expr must cause var to decrease on each iteration of the
3574 // loop. If test-expr is of form b relational-op var and relational-op is
3575 // > or >= then incr-expr must cause var to increase on each iteration of
3576 // the loop.
3577 llvm::APSInt Result;
3578 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3579 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3580 bool IsConstNeg =
3581 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003582 bool IsConstPos =
3583 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003584 bool IsConstZero = IsConstant && !Result.getBoolValue();
3585 if (UB && (IsConstZero ||
3586 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003587 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003588 SemaRef.Diag(NewStep->getExprLoc(),
3589 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003590 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003591 SemaRef.Diag(ConditionLoc,
3592 diag::note_omp_loop_cond_requres_compatible_incr)
3593 << TestIsLessOp << ConditionSrcRange;
3594 return true;
3595 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003596 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003597 NewStep =
3598 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3599 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003600 Subtract = !Subtract;
3601 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003602 }
3603
3604 Step = NewStep;
3605 SubtractStep = Subtract;
3606 return false;
3607}
3608
Alexey Bataev9c821032015-04-30 04:23:23 +00003609bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003610 // Check init-expr for canonical loop form and save loop counter
3611 // variable - #Var and its initialization value - #LB.
3612 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3613 // var = lb
3614 // integer-type var = lb
3615 // random-access-iterator-type var = lb
3616 // pointer-type var = lb
3617 //
3618 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003619 if (EmitDiags) {
3620 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3621 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003622 return true;
3623 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003624 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3625 if (!ExprTemp->cleanupsHaveSideEffects())
3626 S = ExprTemp->getSubExpr();
3627
Alexander Musmana5f070a2014-10-01 06:03:56 +00003628 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003629 if (Expr *E = dyn_cast<Expr>(S))
3630 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003631 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003632 if (BO->getOpcode() == BO_Assign) {
3633 auto *LHS = BO->getLHS()->IgnoreParens();
3634 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3635 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3636 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3637 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3638 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3639 }
3640 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3641 if (ME->isArrow() &&
3642 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3643 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3644 }
3645 }
David Majnemer9d168222016-08-05 17:44:54 +00003646 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003647 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003648 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003649 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003650 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003651 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003652 SemaRef.Diag(S->getLocStart(),
3653 diag::ext_omp_loop_not_canonical_init)
3654 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003655 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003656 }
3657 }
3658 }
David Majnemer9d168222016-08-05 17:44:54 +00003659 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003660 if (CE->getOperator() == OO_Equal) {
3661 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003662 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003663 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3664 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3665 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3666 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3667 }
3668 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3669 if (ME->isArrow() &&
3670 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3671 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3672 }
3673 }
3674 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003675
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003676 if (Dependent() || SemaRef.CurContext->isDependentContext())
3677 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003678 if (EmitDiags) {
3679 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3680 << S->getSourceRange();
3681 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003682 return true;
3683}
3684
Alexey Bataev23b69422014-06-18 07:08:49 +00003685/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003686/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003687static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003688 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003689 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003690 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003691 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3692 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003693 if ((Ctor->isCopyOrMoveConstructor() ||
3694 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3695 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003696 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003697 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003698 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003699 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003700 }
3701 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3702 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3703 return getCanonicalDecl(ME->getMemberDecl());
3704 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003705}
3706
3707bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3708 // Check test-expr for canonical form, save upper-bound UB, flags for
3709 // less/greater and for strict/non-strict comparison.
3710 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3711 // var relational-op b
3712 // b relational-op var
3713 //
3714 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003715 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003716 return true;
3717 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003718 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003719 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003720 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003721 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003722 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003723 return SetUB(BO->getRHS(),
3724 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3725 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3726 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003727 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003728 return SetUB(BO->getLHS(),
3729 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3730 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3731 BO->getSourceRange(), BO->getOperatorLoc());
3732 }
David Majnemer9d168222016-08-05 17:44:54 +00003733 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003734 if (CE->getNumArgs() == 2) {
3735 auto Op = CE->getOperator();
3736 switch (Op) {
3737 case OO_Greater:
3738 case OO_GreaterEqual:
3739 case OO_Less:
3740 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003741 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003742 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3743 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3744 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003745 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003746 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3747 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3748 CE->getOperatorLoc());
3749 break;
3750 default:
3751 break;
3752 }
3753 }
3754 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003755 if (Dependent() || SemaRef.CurContext->isDependentContext())
3756 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003757 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003758 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003759 return true;
3760}
3761
3762bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3763 // RHS of canonical loop form increment can be:
3764 // var + incr
3765 // incr + var
3766 // var - incr
3767 //
3768 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003769 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003770 if (BO->isAdditiveOp()) {
3771 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003772 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003773 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003774 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003775 return SetStep(BO->getLHS(), false);
3776 }
David Majnemer9d168222016-08-05 17:44:54 +00003777 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003778 bool IsAdd = CE->getOperator() == OO_Plus;
3779 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003780 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003781 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003782 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003783 return SetStep(CE->getArg(0), false);
3784 }
3785 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003786 if (Dependent() || SemaRef.CurContext->isDependentContext())
3787 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003788 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003789 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003790 return true;
3791}
3792
3793bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3794 // Check incr-expr for canonical loop form and return true if it
3795 // does not conform.
3796 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3797 // ++var
3798 // var++
3799 // --var
3800 // var--
3801 // var += incr
3802 // var -= incr
3803 // var = var + incr
3804 // var = incr + var
3805 // var = var - incr
3806 //
3807 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003808 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003809 return true;
3810 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003811 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3812 if (!ExprTemp->cleanupsHaveSideEffects())
3813 S = ExprTemp->getSubExpr();
3814
Alexander Musmana5f070a2014-10-01 06:03:56 +00003815 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003816 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003817 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003818 if (UO->isIncrementDecrementOp() &&
3819 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003820 return SetStep(SemaRef
3821 .ActOnIntegerConstant(UO->getLocStart(),
3822 (UO->isDecrementOp() ? -1 : 1))
3823 .get(),
3824 false);
3825 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003826 switch (BO->getOpcode()) {
3827 case BO_AddAssign:
3828 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003829 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003830 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3831 break;
3832 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003833 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003834 return CheckIncRHS(BO->getRHS());
3835 break;
3836 default:
3837 break;
3838 }
David Majnemer9d168222016-08-05 17:44:54 +00003839 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003840 switch (CE->getOperator()) {
3841 case OO_PlusPlus:
3842 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003843 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003844 return SetStep(SemaRef
3845 .ActOnIntegerConstant(
3846 CE->getLocStart(),
3847 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3848 .get(),
3849 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003850 break;
3851 case OO_PlusEqual:
3852 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003853 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003854 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3855 break;
3856 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003857 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003858 return CheckIncRHS(CE->getArg(1));
3859 break;
3860 default:
3861 break;
3862 }
3863 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003864 if (Dependent() || SemaRef.CurContext->isDependentContext())
3865 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003866 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003867 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003868 return true;
3869}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003870
Alexey Bataev5a3af132016-03-29 08:58:54 +00003871static ExprResult
3872tryBuildCapture(Sema &SemaRef, Expr *Capture,
3873 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003874 if (SemaRef.CurContext->isDependentContext())
3875 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003876 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3877 return SemaRef.PerformImplicitConversion(
3878 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3879 /*AllowExplicit=*/true);
3880 auto I = Captures.find(Capture);
3881 if (I != Captures.end())
3882 return buildCapture(SemaRef, Capture, I->second);
3883 DeclRefExpr *Ref = nullptr;
3884 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3885 Captures[Capture] = Ref;
3886 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003887}
3888
Alexander Musmana5f070a2014-10-01 06:03:56 +00003889/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003890Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3891 Scope *S, const bool LimitedType,
3892 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003893 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003894 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003895 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003896 SemaRef.getLangOpts().CPlusPlus) {
3897 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003898 auto *UBExpr = TestIsLessOp ? UB : LB;
3899 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003900 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3901 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003902 if (!Upper || !Lower)
3903 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003904
3905 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3906
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003907 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003908 // BuildBinOp already emitted error, this one is to point user to upper
3909 // and lower bound, and to tell what is passed to 'operator-'.
3910 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3911 << Upper->getSourceRange() << Lower->getSourceRange();
3912 return nullptr;
3913 }
3914 }
3915
3916 if (!Diff.isUsable())
3917 return nullptr;
3918
3919 // Upper - Lower [- 1]
3920 if (TestIsStrictOp)
3921 Diff = SemaRef.BuildBinOp(
3922 S, DefaultLoc, BO_Sub, Diff.get(),
3923 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3924 if (!Diff.isUsable())
3925 return nullptr;
3926
3927 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003928 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3929 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003930 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003931 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003932 if (!Diff.isUsable())
3933 return nullptr;
3934
3935 // Parentheses (for dumping/debugging purposes only).
3936 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3937 if (!Diff.isUsable())
3938 return nullptr;
3939
3940 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003941 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003942 if (!Diff.isUsable())
3943 return nullptr;
3944
Alexander Musman174b3ca2014-10-06 11:16:29 +00003945 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003946 QualType Type = Diff.get()->getType();
3947 auto &C = SemaRef.Context;
3948 bool UseVarType = VarType->hasIntegerRepresentation() &&
3949 C.getTypeSize(Type) > C.getTypeSize(VarType);
3950 if (!Type->isIntegerType() || UseVarType) {
3951 unsigned NewSize =
3952 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3953 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3954 : Type->hasSignedIntegerRepresentation();
3955 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003956 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3957 Diff = SemaRef.PerformImplicitConversion(
3958 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3959 if (!Diff.isUsable())
3960 return nullptr;
3961 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003962 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003963 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003964 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3965 if (NewSize != C.getTypeSize(Type)) {
3966 if (NewSize < C.getTypeSize(Type)) {
3967 assert(NewSize == 64 && "incorrect loop var size");
3968 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3969 << InitSrcRange << ConditionSrcRange;
3970 }
3971 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003972 NewSize, Type->hasSignedIntegerRepresentation() ||
3973 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003974 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3975 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3976 Sema::AA_Converting, true);
3977 if (!Diff.isUsable())
3978 return nullptr;
3979 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003980 }
3981 }
3982
Alexander Musmana5f070a2014-10-01 06:03:56 +00003983 return Diff.get();
3984}
3985
Alexey Bataev5a3af132016-03-29 08:58:54 +00003986Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3987 Scope *S, Expr *Cond,
3988 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003989 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3990 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3991 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003992
Alexey Bataev5a3af132016-03-29 08:58:54 +00003993 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3994 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3995 if (!NewLB.isUsable() || !NewUB.isUsable())
3996 return nullptr;
3997
Alexey Bataev62dbb972015-04-22 11:59:37 +00003998 auto CondExpr = SemaRef.BuildBinOp(
3999 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
4000 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004001 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004002 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004003 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4004 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004005 CondExpr = SemaRef.PerformImplicitConversion(
4006 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4007 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004008 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004009 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4010 // Otherwise use original loop conditon and evaluate it in runtime.
4011 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4012}
4013
Alexander Musmana5f070a2014-10-01 06:03:56 +00004014/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004015DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004016 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004017 auto *VD = dyn_cast<VarDecl>(LCDecl);
4018 if (!VD) {
4019 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
4020 auto *Ref = buildDeclRefExpr(
4021 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004022 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4023 // If the loop control decl is explicitly marked as private, do not mark it
4024 // as captured again.
4025 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4026 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004027 return Ref;
4028 }
4029 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004030 DefaultLoc);
4031}
4032
4033Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004034 if (LCDecl && !LCDecl->isInvalidDecl()) {
4035 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00004036 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004037 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
4038 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004039 if (PrivateVar->isInvalidDecl())
4040 return nullptr;
4041 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4042 }
4043 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004044}
4045
Samuel Antao4c8035b2016-12-12 18:00:20 +00004046/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004047Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
4048
4049/// \brief Build step of the counter be used for codegen.
4050Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
4051
4052/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004053struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004054 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004055 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004056 /// \brief This expression calculates the number of iterations in the loop.
4057 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004058 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004059 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004060 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00004061 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004062 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004063 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004064 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004065 /// \brief This is step for the #CounterVar used to generate its update:
4066 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004067 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004068 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004069 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004070 /// \brief Source range of the loop init.
4071 SourceRange InitSrcRange;
4072 /// \brief Source range of the loop condition.
4073 SourceRange CondSrcRange;
4074 /// \brief Source range of the loop increment.
4075 SourceRange IncSrcRange;
4076};
4077
Alexey Bataev23b69422014-06-18 07:08:49 +00004078} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004079
Alexey Bataev9c821032015-04-30 04:23:23 +00004080void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4081 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4082 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004083 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4084 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004085 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4086 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004087 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4088 if (auto *D = ISC.GetLoopDecl()) {
4089 auto *VD = dyn_cast<VarDecl>(D);
4090 if (!VD) {
4091 if (auto *Private = IsOpenMPCapturedDecl(D))
4092 VD = Private;
4093 else {
4094 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4095 /*WithInit=*/false);
4096 VD = cast<VarDecl>(Ref->getDecl());
4097 }
4098 }
4099 DSAStack->addLoopControlVariable(D, VD);
4100 }
4101 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004102 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004103 }
4104}
4105
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004106/// \brief Called on a for stmt to check and extract its iteration space
4107/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00004108static bool CheckOpenMPIterationSpace(
4109 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4110 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004111 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004112 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004113 LoopIterationSpace &ResultIterSpace,
4114 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004115 // OpenMP [2.6, Canonical Loop Form]
4116 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004117 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004118 if (!For) {
4119 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004120 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4121 << getOpenMPDirectiveName(DKind) << NestedLoopCount
4122 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4123 if (NestedLoopCount > 1) {
4124 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4125 SemaRef.Diag(DSA.getConstructLoc(),
4126 diag::note_omp_collapse_ordered_expr)
4127 << 2 << CollapseLoopCountExpr->getSourceRange()
4128 << OrderedLoopCountExpr->getSourceRange();
4129 else if (CollapseLoopCountExpr)
4130 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4131 diag::note_omp_collapse_ordered_expr)
4132 << 0 << CollapseLoopCountExpr->getSourceRange();
4133 else
4134 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4135 diag::note_omp_collapse_ordered_expr)
4136 << 1 << OrderedLoopCountExpr->getSourceRange();
4137 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004138 return true;
4139 }
4140 assert(For->getBody());
4141
4142 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4143
4144 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00004145 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004146 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004147 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004148
4149 bool HasErrors = false;
4150
4151 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004152 if (auto *LCDecl = ISC.GetLoopDecl()) {
4153 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004154
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004155 // OpenMP [2.6, Canonical Loop Form]
4156 // Var is one of the following:
4157 // A variable of signed or unsigned integer type.
4158 // For C++, a variable of a random access iterator type.
4159 // For C, a variable of a pointer type.
4160 auto VarType = LCDecl->getType().getNonReferenceType();
4161 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4162 !VarType->isPointerType() &&
4163 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4164 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4165 << SemaRef.getLangOpts().CPlusPlus;
4166 HasErrors = true;
4167 }
4168
4169 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4170 // a Construct
4171 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4172 // parallel for construct is (are) private.
4173 // The loop iteration variable in the associated for-loop of a simd
4174 // construct with just one associated for-loop is linear with a
4175 // constant-linear-step that is the increment of the associated for-loop.
4176 // Exclude loop var from the list of variables with implicitly defined data
4177 // sharing attributes.
4178 VarsWithImplicitDSA.erase(LCDecl);
4179
4180 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4181 // in a Construct, C/C++].
4182 // The loop iteration variable in the associated for-loop of a simd
4183 // construct with just one associated for-loop may be listed in a linear
4184 // clause with a constant-linear-step that is the increment of the
4185 // associated for-loop.
4186 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4187 // parallel for construct may be listed in a private or lastprivate clause.
4188 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4189 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4190 // declared in the loop and it is predetermined as a private.
4191 auto PredeterminedCKind =
4192 isOpenMPSimdDirective(DKind)
4193 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4194 : OMPC_private;
4195 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4196 DVar.CKind != PredeterminedCKind) ||
4197 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4198 isOpenMPDistributeDirective(DKind)) &&
4199 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4200 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4201 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4202 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4203 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4204 << getOpenMPClauseName(PredeterminedCKind);
4205 if (DVar.RefExpr == nullptr)
4206 DVar.CKind = PredeterminedCKind;
4207 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4208 HasErrors = true;
4209 } else if (LoopDeclRefExpr != nullptr) {
4210 // Make the loop iteration variable private (for worksharing constructs),
4211 // linear (for simd directives with the only one associated loop) or
4212 // lastprivate (for simd directives with several collapsed or ordered
4213 // loops).
4214 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004215 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4216 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004217 /*FromParent=*/false);
4218 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4219 }
4220
4221 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4222
4223 // Check test-expr.
4224 HasErrors |= ISC.CheckCond(For->getCond());
4225
4226 // Check incr-expr.
4227 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004228 }
4229
Alexander Musmana5f070a2014-10-01 06:03:56 +00004230 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004231 return HasErrors;
4232
Alexander Musmana5f070a2014-10-01 06:03:56 +00004233 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004234 ResultIterSpace.PreCond =
4235 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00004236 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004237 DSA.getCurScope(),
4238 (isOpenMPWorksharingDirective(DKind) ||
4239 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4240 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004241 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00004242 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004243 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4244 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4245 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4246 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4247 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4248 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4249
Alexey Bataev62dbb972015-04-22 11:59:37 +00004250 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4251 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004252 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004253 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004254 ResultIterSpace.CounterInit == nullptr ||
4255 ResultIterSpace.CounterStep == nullptr);
4256
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004257 return HasErrors;
4258}
4259
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004260/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004261static ExprResult
4262BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4263 ExprResult Start,
4264 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004265 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004266 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4267 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004268 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004269 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004270 VarRef.get()->getType())) {
4271 NewStart = SemaRef.PerformImplicitConversion(
4272 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4273 /*AllowExplicit=*/true);
4274 if (!NewStart.isUsable())
4275 return ExprError();
4276 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004277
4278 auto Init =
4279 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4280 return Init;
4281}
4282
Alexander Musmana5f070a2014-10-01 06:03:56 +00004283/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004284static ExprResult
4285BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4286 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4287 ExprResult Step, bool Subtract,
4288 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004289 // Add parentheses (for debugging purposes only).
4290 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4291 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4292 !Step.isUsable())
4293 return ExprError();
4294
Alexey Bataev5a3af132016-03-29 08:58:54 +00004295 ExprResult NewStep = Step;
4296 if (Captures)
4297 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004298 if (NewStep.isInvalid())
4299 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004300 ExprResult Update =
4301 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004302 if (!Update.isUsable())
4303 return ExprError();
4304
Alexey Bataevc0214e02016-02-16 12:13:49 +00004305 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4306 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004307 ExprResult NewStart = Start;
4308 if (Captures)
4309 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004310 if (NewStart.isInvalid())
4311 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004312
Alexey Bataevc0214e02016-02-16 12:13:49 +00004313 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4314 ExprResult SavedUpdate = Update;
4315 ExprResult UpdateVal;
4316 if (VarRef.get()->getType()->isOverloadableType() ||
4317 NewStart.get()->getType()->isOverloadableType() ||
4318 Update.get()->getType()->isOverloadableType()) {
4319 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4320 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4321 Update =
4322 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4323 if (Update.isUsable()) {
4324 UpdateVal =
4325 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4326 VarRef.get(), SavedUpdate.get());
4327 if (UpdateVal.isUsable()) {
4328 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4329 UpdateVal.get());
4330 }
4331 }
4332 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4333 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004334
Alexey Bataevc0214e02016-02-16 12:13:49 +00004335 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4336 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4337 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4338 NewStart.get(), SavedUpdate.get());
4339 if (!Update.isUsable())
4340 return ExprError();
4341
Alexey Bataev11481f52016-02-17 10:29:05 +00004342 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4343 VarRef.get()->getType())) {
4344 Update = SemaRef.PerformImplicitConversion(
4345 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4346 if (!Update.isUsable())
4347 return ExprError();
4348 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004349
4350 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4351 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004352 return Update;
4353}
4354
4355/// \brief Convert integer expression \a E to make it have at least \a Bits
4356/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004357static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004358 if (E == nullptr)
4359 return ExprError();
4360 auto &C = SemaRef.Context;
4361 QualType OldType = E->getType();
4362 unsigned HasBits = C.getTypeSize(OldType);
4363 if (HasBits >= Bits)
4364 return ExprResult(E);
4365 // OK to convert to signed, because new type has more bits than old.
4366 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4367 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4368 true);
4369}
4370
4371/// \brief Check if the given expression \a E is a constant integer that fits
4372/// into \a Bits bits.
4373static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4374 if (E == nullptr)
4375 return false;
4376 llvm::APSInt Result;
4377 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4378 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4379 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004380}
4381
Alexey Bataev5a3af132016-03-29 08:58:54 +00004382/// Build preinits statement for the given declarations.
4383static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00004384 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004385 if (!PreInits.empty()) {
4386 return new (Context) DeclStmt(
4387 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4388 SourceLocation(), SourceLocation());
4389 }
4390 return nullptr;
4391}
4392
4393/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00004394static Stmt *
4395buildPreInits(ASTContext &Context,
4396 const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004397 if (!Captures.empty()) {
4398 SmallVector<Decl *, 16> PreInits;
4399 for (auto &Pair : Captures)
4400 PreInits.push_back(Pair.second->getDecl());
4401 return buildPreInits(Context, PreInits);
4402 }
4403 return nullptr;
4404}
4405
4406/// Build postupdate expression for the given list of postupdates expressions.
4407static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4408 Expr *PostUpdate = nullptr;
4409 if (!PostUpdates.empty()) {
4410 for (auto *E : PostUpdates) {
4411 Expr *ConvE = S.BuildCStyleCastExpr(
4412 E->getExprLoc(),
4413 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4414 E->getExprLoc(), E)
4415 .get();
4416 PostUpdate = PostUpdate
4417 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4418 PostUpdate, ConvE)
4419 .get()
4420 : ConvE;
4421 }
4422 }
4423 return PostUpdate;
4424}
4425
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004426/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004427/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4428/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004429static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004430CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4431 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4432 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004433 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004434 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004435 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004436 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004437 // Found 'collapse' clause - calculate collapse number.
4438 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004439 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004440 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004441 }
4442 if (OrderedLoopCountExpr) {
4443 // Found 'ordered' clause - calculate collapse number.
4444 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004445 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4446 if (Result.getLimitedValue() < NestedLoopCount) {
4447 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4448 diag::err_omp_wrong_ordered_loop_count)
4449 << OrderedLoopCountExpr->getSourceRange();
4450 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4451 diag::note_collapse_loop_count)
4452 << CollapseLoopCountExpr->getSourceRange();
4453 }
4454 NestedLoopCount = Result.getLimitedValue();
4455 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004456 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004457 // This is helper routine for loop directives (e.g., 'for', 'simd',
4458 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004459 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004460 SmallVector<LoopIterationSpace, 4> IterSpaces;
4461 IterSpaces.resize(NestedLoopCount);
4462 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004463 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004464 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004465 NestedLoopCount, CollapseLoopCountExpr,
4466 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004467 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004468 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004469 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004470 // OpenMP [2.8.1, simd construct, Restrictions]
4471 // All loops associated with the construct must be perfectly nested; that
4472 // is, there must be no intervening code nor any OpenMP directive between
4473 // any two loops.
4474 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004475 }
4476
Alexander Musmana5f070a2014-10-01 06:03:56 +00004477 Built.clear(/* size */ NestedLoopCount);
4478
4479 if (SemaRef.CurContext->isDependentContext())
4480 return NestedLoopCount;
4481
4482 // An example of what is generated for the following code:
4483 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004484 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004485 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004486 // for (k = 0; k < NK; ++k)
4487 // for (j = J0; j < NJ; j+=2) {
4488 // <loop body>
4489 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004490 //
4491 // We generate the code below.
4492 // Note: the loop body may be outlined in CodeGen.
4493 // Note: some counters may be C++ classes, operator- is used to find number of
4494 // iterations and operator+= to calculate counter value.
4495 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4496 // or i64 is currently supported).
4497 //
4498 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4499 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4500 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4501 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4502 // // similar updates for vars in clauses (e.g. 'linear')
4503 // <loop body (using local i and j)>
4504 // }
4505 // i = NI; // assign final values of counters
4506 // j = NJ;
4507 //
4508
4509 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4510 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004511 // Precondition tests if there is at least one iteration (all conditions are
4512 // true).
4513 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004514 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004515 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004516 32 /* Bits */, SemaRef
4517 .PerformImplicitConversion(
4518 N0->IgnoreImpCasts(), N0->getType(),
4519 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004520 .get(),
4521 SemaRef);
4522 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004523 64 /* Bits */, SemaRef
4524 .PerformImplicitConversion(
4525 N0->IgnoreImpCasts(), N0->getType(),
4526 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004527 .get(),
4528 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004529
4530 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4531 return NestedLoopCount;
4532
4533 auto &C = SemaRef.Context;
4534 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4535
4536 Scope *CurScope = DSA.getCurScope();
4537 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004538 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004539 PreCond =
4540 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4541 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004542 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004543 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004544 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004545 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4546 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004547 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004548 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004549 SemaRef
4550 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4551 Sema::AA_Converting,
4552 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004553 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004554 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004555 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004556 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004557 SemaRef
4558 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4559 Sema::AA_Converting,
4560 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004561 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004562 }
4563
4564 // Choose either the 32-bit or 64-bit version.
4565 ExprResult LastIteration = LastIteration64;
4566 if (LastIteration32.isUsable() &&
4567 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4568 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4569 FitsInto(
4570 32 /* Bits */,
4571 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4572 LastIteration64.get(), SemaRef)))
4573 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004574 QualType VType = LastIteration.get()->getType();
4575 QualType RealVType = VType;
4576 QualType StrideVType = VType;
4577 if (isOpenMPTaskLoopDirective(DKind)) {
4578 VType =
4579 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4580 StrideVType =
4581 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4582 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004583
4584 if (!LastIteration.isUsable())
4585 return 0;
4586
4587 // Save the number of iterations.
4588 ExprResult NumIterations = LastIteration;
4589 {
4590 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004591 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4592 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004593 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4594 if (!LastIteration.isUsable())
4595 return 0;
4596 }
4597
4598 // Calculate the last iteration number beforehand instead of doing this on
4599 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4600 llvm::APSInt Result;
4601 bool IsConstant =
4602 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4603 ExprResult CalcLastIteration;
4604 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004605 ExprResult SaveRef =
4606 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004607 LastIteration = SaveRef;
4608
4609 // Prepare SaveRef + 1.
4610 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004611 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004612 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4613 if (!NumIterations.isUsable())
4614 return 0;
4615 }
4616
4617 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4618
David Majnemer9d168222016-08-05 17:44:54 +00004619 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004620 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004621 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4622 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004623 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004624 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4625 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004626 SemaRef.AddInitializerToDecl(LBDecl,
4627 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4628 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004629
4630 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004631 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4632 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004633 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004634 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004635
4636 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4637 // This will be used to implement clause 'lastprivate'.
4638 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004639 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4640 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004641 SemaRef.AddInitializerToDecl(ILDecl,
4642 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4643 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004644
4645 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004646 VarDecl *STDecl =
4647 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4648 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004649 SemaRef.AddInitializerToDecl(STDecl,
4650 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4651 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004652
4653 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004654 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004655 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4656 UB.get(), LastIteration.get());
4657 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4658 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4659 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4660 CondOp.get());
4661 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004662
4663 // If we have a combined directive that combines 'distribute', 'for' or
4664 // 'simd' we need to be able to access the bounds of the schedule of the
4665 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4666 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4667 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004668
Carlo Bertolliffafe102017-04-20 00:39:39 +00004669 // Lower bound variable, initialized with zero.
4670 VarDecl *CombLBDecl =
4671 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4672 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4673 SemaRef.AddInitializerToDecl(
4674 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4675 /*DirectInit*/ false);
4676
4677 // Upper bound variable, initialized with last iteration number.
4678 VarDecl *CombUBDecl =
4679 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4680 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4681 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4682 /*DirectInit*/ false);
4683
4684 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4685 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4686 ExprResult CombCondOp =
4687 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4688 LastIteration.get(), CombUB.get());
4689 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4690 CombCondOp.get());
4691 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4692
4693 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004694 // We expect to have at least 2 more parameters than the 'parallel'
4695 // directive does - the lower and upper bounds of the previous schedule.
4696 assert(CD->getNumParams() >= 4 &&
4697 "Unexpected number of parameters in loop combined directive");
4698
4699 // Set the proper type for the bounds given what we learned from the
4700 // enclosed loops.
4701 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4702 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4703
4704 // Previous lower and upper bounds are obtained from the region
4705 // parameters.
4706 PrevLB =
4707 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4708 PrevUB =
4709 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4710 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004711 }
4712
4713 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004714 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004715 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004716 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004717 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4718 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004719 Expr *RHS =
4720 (isOpenMPWorksharingDirective(DKind) ||
4721 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4722 ? LB.get()
4723 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004724 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4725 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004726
4727 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4728 Expr *CombRHS =
4729 (isOpenMPWorksharingDirective(DKind) ||
4730 isOpenMPTaskLoopDirective(DKind) ||
4731 isOpenMPDistributeDirective(DKind))
4732 ? CombLB.get()
4733 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4734 CombInit =
4735 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4736 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4737 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004738 }
4739
Alexander Musmanc6388682014-12-15 07:07:06 +00004740 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004741 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004742 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004743 (isOpenMPWorksharingDirective(DKind) ||
4744 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004745 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4746 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4747 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004748 ExprResult CombCond;
4749 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4750 CombCond =
4751 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4752 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004753 // Loop increment (IV = IV + 1)
4754 SourceLocation IncLoc;
4755 ExprResult Inc =
4756 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4757 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4758 if (!Inc.isUsable())
4759 return 0;
4760 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004761 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4762 if (!Inc.isUsable())
4763 return 0;
4764
4765 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4766 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004767 // In combined construct, add combined version that use CombLB and CombUB
4768 // base variables for the update
4769 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004770 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4771 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004772 // LB + ST
4773 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4774 if (!NextLB.isUsable())
4775 return 0;
4776 // LB = LB + ST
4777 NextLB =
4778 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4779 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4780 if (!NextLB.isUsable())
4781 return 0;
4782 // UB + ST
4783 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4784 if (!NextUB.isUsable())
4785 return 0;
4786 // UB = UB + ST
4787 NextUB =
4788 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4789 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4790 if (!NextUB.isUsable())
4791 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004792 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4793 CombNextLB =
4794 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4795 if (!NextLB.isUsable())
4796 return 0;
4797 // LB = LB + ST
4798 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4799 CombNextLB.get());
4800 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4801 if (!CombNextLB.isUsable())
4802 return 0;
4803 // UB + ST
4804 CombNextUB =
4805 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4806 if (!CombNextUB.isUsable())
4807 return 0;
4808 // UB = UB + ST
4809 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4810 CombNextUB.get());
4811 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4812 if (!CombNextUB.isUsable())
4813 return 0;
4814 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004815 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004816
Carlo Bertolliffafe102017-04-20 00:39:39 +00004817 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004818 // directive with for as IV = IV + ST; ensure upper bound expression based
4819 // on PrevUB instead of NumIterations - used to implement 'for' when found
4820 // in combination with 'distribute', like in 'distribute parallel for'
4821 SourceLocation DistIncLoc;
4822 ExprResult DistCond, DistInc, PrevEUB;
4823 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4824 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4825 assert(DistCond.isUsable() && "distribute cond expr was not built");
4826
4827 DistInc =
4828 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4829 assert(DistInc.isUsable() && "distribute inc expr was not built");
4830 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4831 DistInc.get());
4832 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4833 assert(DistInc.isUsable() && "distribute inc expr was not built");
4834
4835 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4836 // construct
4837 SourceLocation DistEUBLoc;
4838 ExprResult IsUBGreater =
4839 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4840 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4841 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4842 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4843 CondOp.get());
4844 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4845 }
4846
Alexander Musmana5f070a2014-10-01 06:03:56 +00004847 // Build updates and final values of the loop counters.
4848 bool HasErrors = false;
4849 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004850 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004851 Built.Updates.resize(NestedLoopCount);
4852 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004853 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004854 {
4855 ExprResult Div;
4856 // Go from inner nested loop to outer.
4857 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4858 LoopIterationSpace &IS = IterSpaces[Cnt];
4859 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4860 // Build: Iter = (IV / Div) % IS.NumIters
4861 // where Div is product of previous iterations' IS.NumIters.
4862 ExprResult Iter;
4863 if (Div.isUsable()) {
4864 Iter =
4865 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4866 } else {
4867 Iter = IV;
4868 assert((Cnt == (int)NestedLoopCount - 1) &&
4869 "unusable div expected on first iteration only");
4870 }
4871
4872 if (Cnt != 0 && Iter.isUsable())
4873 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4874 IS.NumIterations);
4875 if (!Iter.isUsable()) {
4876 HasErrors = true;
4877 break;
4878 }
4879
Alexey Bataev39f915b82015-05-08 10:41:21 +00004880 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004881 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4882 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4883 IS.CounterVar->getExprLoc(),
4884 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004885 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004886 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004887 if (!Init.isUsable()) {
4888 HasErrors = true;
4889 break;
4890 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004891 ExprResult Update = BuildCounterUpdate(
4892 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4893 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004894 if (!Update.isUsable()) {
4895 HasErrors = true;
4896 break;
4897 }
4898
4899 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4900 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004901 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004902 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004903 if (!Final.isUsable()) {
4904 HasErrors = true;
4905 break;
4906 }
4907
4908 // Build Div for the next iteration: Div <- Div * IS.NumIters
4909 if (Cnt != 0) {
4910 if (Div.isUnset())
4911 Div = IS.NumIterations;
4912 else
4913 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4914 IS.NumIterations);
4915
4916 // Add parentheses (for debugging purposes only).
4917 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004918 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004919 if (!Div.isUsable()) {
4920 HasErrors = true;
4921 break;
4922 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004923 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004924 }
4925 if (!Update.isUsable() || !Final.isUsable()) {
4926 HasErrors = true;
4927 break;
4928 }
4929 // Save results
4930 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004931 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004932 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004933 Built.Updates[Cnt] = Update.get();
4934 Built.Finals[Cnt] = Final.get();
4935 }
4936 }
4937
4938 if (HasErrors)
4939 return 0;
4940
4941 // Save results
4942 Built.IterationVarRef = IV.get();
4943 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004944 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004945 Built.CalcLastIteration =
4946 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004947 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004948 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004949 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004950 Built.Init = Init.get();
4951 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004952 Built.LB = LB.get();
4953 Built.UB = UB.get();
4954 Built.IL = IL.get();
4955 Built.ST = ST.get();
4956 Built.EUB = EUB.get();
4957 Built.NLB = NextLB.get();
4958 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004959 Built.PrevLB = PrevLB.get();
4960 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004961 Built.DistInc = DistInc.get();
4962 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004963 Built.DistCombinedFields.LB = CombLB.get();
4964 Built.DistCombinedFields.UB = CombUB.get();
4965 Built.DistCombinedFields.EUB = CombEUB.get();
4966 Built.DistCombinedFields.Init = CombInit.get();
4967 Built.DistCombinedFields.Cond = CombCond.get();
4968 Built.DistCombinedFields.NLB = CombNextLB.get();
4969 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004970
Alexey Bataev8b427062016-05-25 12:36:08 +00004971 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4972 // Fill data for doacross depend clauses.
4973 for (auto Pair : DSA.getDoacrossDependClauses()) {
4974 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4975 Pair.first->setCounterValue(CounterVal);
4976 else {
4977 if (NestedLoopCount != Pair.second.size() ||
4978 NestedLoopCount != LoopMultipliers.size() + 1) {
4979 // Erroneous case - clause has some problems.
4980 Pair.first->setCounterValue(CounterVal);
4981 continue;
4982 }
4983 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4984 auto I = Pair.second.rbegin();
4985 auto IS = IterSpaces.rbegin();
4986 auto ILM = LoopMultipliers.rbegin();
4987 Expr *UpCounterVal = CounterVal;
4988 Expr *Multiplier = nullptr;
4989 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4990 if (I->first) {
4991 assert(IS->CounterStep);
4992 Expr *NormalizedOffset =
4993 SemaRef
4994 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4995 I->first, IS->CounterStep)
4996 .get();
4997 if (Multiplier) {
4998 NormalizedOffset =
4999 SemaRef
5000 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
5001 NormalizedOffset, Multiplier)
5002 .get();
5003 }
5004 assert(I->second == OO_Plus || I->second == OO_Minus);
5005 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00005006 UpCounterVal = SemaRef
5007 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
5008 UpCounterVal, NormalizedOffset)
5009 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00005010 }
5011 Multiplier = *ILM;
5012 ++I;
5013 ++IS;
5014 ++ILM;
5015 }
5016 Pair.first->setCounterValue(UpCounterVal);
5017 }
5018 }
5019
Alexey Bataevabfc0692014-06-25 06:52:00 +00005020 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005021}
5022
Alexey Bataev10e775f2015-07-30 11:36:16 +00005023static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005024 auto CollapseClauses =
5025 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5026 if (CollapseClauses.begin() != CollapseClauses.end())
5027 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005028 return nullptr;
5029}
5030
Alexey Bataev10e775f2015-07-30 11:36:16 +00005031static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005032 auto OrderedClauses =
5033 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5034 if (OrderedClauses.begin() != OrderedClauses.end())
5035 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005036 return nullptr;
5037}
5038
Kelvin Lic5609492016-07-15 04:39:07 +00005039static bool checkSimdlenSafelenSpecified(Sema &S,
5040 const ArrayRef<OMPClause *> Clauses) {
5041 OMPSafelenClause *Safelen = nullptr;
5042 OMPSimdlenClause *Simdlen = nullptr;
5043
5044 for (auto *Clause : Clauses) {
5045 if (Clause->getClauseKind() == OMPC_safelen)
5046 Safelen = cast<OMPSafelenClause>(Clause);
5047 else if (Clause->getClauseKind() == OMPC_simdlen)
5048 Simdlen = cast<OMPSimdlenClause>(Clause);
5049 if (Safelen && Simdlen)
5050 break;
5051 }
5052
5053 if (Simdlen && Safelen) {
5054 llvm::APSInt SimdlenRes, SafelenRes;
5055 auto SimdlenLength = Simdlen->getSimdlen();
5056 auto SafelenLength = Safelen->getSafelen();
5057 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5058 SimdlenLength->isInstantiationDependent() ||
5059 SimdlenLength->containsUnexpandedParameterPack())
5060 return false;
5061 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5062 SafelenLength->isInstantiationDependent() ||
5063 SafelenLength->containsUnexpandedParameterPack())
5064 return false;
5065 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5066 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5067 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5068 // If both simdlen and safelen clauses are specified, the value of the
5069 // simdlen parameter must be less than or equal to the value of the safelen
5070 // parameter.
5071 if (SimdlenRes > SafelenRes) {
5072 S.Diag(SimdlenLength->getExprLoc(),
5073 diag::err_omp_wrong_simdlen_safelen_values)
5074 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5075 return true;
5076 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005077 }
5078 return false;
5079}
5080
Alexey Bataev4acb8592014-07-07 13:01:15 +00005081StmtResult Sema::ActOnOpenMPSimdDirective(
5082 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5083 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005084 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005085 if (!AStmt)
5086 return StmtError();
5087
5088 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005089 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005090 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5091 // define the nested loops number.
5092 unsigned NestedLoopCount = CheckOpenMPLoop(
5093 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5094 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005095 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005096 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005097
Alexander Musmana5f070a2014-10-01 06:03:56 +00005098 assert((CurContext->isDependentContext() || B.builtAll()) &&
5099 "omp simd loop exprs were not built");
5100
Alexander Musman3276a272015-03-21 10:12:56 +00005101 if (!CurContext->isDependentContext()) {
5102 // Finalize the clauses that need pre-built expressions for CodeGen.
5103 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005104 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005105 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005106 B.NumIterations, *this, CurScope,
5107 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005108 return StmtError();
5109 }
5110 }
5111
Kelvin Lic5609492016-07-15 04:39:07 +00005112 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005113 return StmtError();
5114
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005115 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005116 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5117 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005118}
5119
Alexey Bataev4acb8592014-07-07 13:01:15 +00005120StmtResult Sema::ActOnOpenMPForDirective(
5121 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5122 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005123 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005124 if (!AStmt)
5125 return StmtError();
5126
5127 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005128 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005129 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5130 // define the nested loops number.
5131 unsigned NestedLoopCount = CheckOpenMPLoop(
5132 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5133 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005134 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005135 return StmtError();
5136
Alexander Musmana5f070a2014-10-01 06:03:56 +00005137 assert((CurContext->isDependentContext() || B.builtAll()) &&
5138 "omp for loop exprs were not built");
5139
Alexey Bataev54acd402015-08-04 11:18:19 +00005140 if (!CurContext->isDependentContext()) {
5141 // Finalize the clauses that need pre-built expressions for CodeGen.
5142 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005143 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005144 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005145 B.NumIterations, *this, CurScope,
5146 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005147 return StmtError();
5148 }
5149 }
5150
Alexey Bataevf29276e2014-06-18 04:14:57 +00005151 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005152 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005153 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005154}
5155
Alexander Musmanf82886e2014-09-18 05:12:34 +00005156StmtResult Sema::ActOnOpenMPForSimdDirective(
5157 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5158 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005159 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005160 if (!AStmt)
5161 return StmtError();
5162
5163 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005164 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005165 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5166 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005167 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005168 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5169 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5170 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005171 if (NestedLoopCount == 0)
5172 return StmtError();
5173
Alexander Musmanc6388682014-12-15 07:07:06 +00005174 assert((CurContext->isDependentContext() || B.builtAll()) &&
5175 "omp for simd loop exprs were not built");
5176
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005177 if (!CurContext->isDependentContext()) {
5178 // Finalize the clauses that need pre-built expressions for CodeGen.
5179 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005180 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005181 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005182 B.NumIterations, *this, CurScope,
5183 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005184 return StmtError();
5185 }
5186 }
5187
Kelvin Lic5609492016-07-15 04:39:07 +00005188 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005189 return StmtError();
5190
Alexander Musmanf82886e2014-09-18 05:12:34 +00005191 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005192 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5193 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005194}
5195
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005196StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5197 Stmt *AStmt,
5198 SourceLocation StartLoc,
5199 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005200 if (!AStmt)
5201 return StmtError();
5202
5203 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005204 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005205 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005206 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005207 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005208 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005209 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005210 return StmtError();
5211 // All associated statements must be '#pragma omp section' except for
5212 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005213 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005214 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5215 if (SectionStmt)
5216 Diag(SectionStmt->getLocStart(),
5217 diag::err_omp_sections_substmt_not_section);
5218 return StmtError();
5219 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005220 cast<OMPSectionDirective>(SectionStmt)
5221 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005222 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005223 } else {
5224 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5225 return StmtError();
5226 }
5227
5228 getCurFunction()->setHasBranchProtectedScope();
5229
Alexey Bataev25e5b442015-09-15 12:52:43 +00005230 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5231 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005232}
5233
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005234StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5235 SourceLocation StartLoc,
5236 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005237 if (!AStmt)
5238 return StmtError();
5239
5240 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005241
5242 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005243 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005244
Alexey Bataev25e5b442015-09-15 12:52:43 +00005245 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5246 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005247}
5248
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005249StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5250 Stmt *AStmt,
5251 SourceLocation StartLoc,
5252 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005253 if (!AStmt)
5254 return StmtError();
5255
5256 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005257
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005258 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005259
Alexey Bataev3255bf32015-01-19 05:20:46 +00005260 // OpenMP [2.7.3, single Construct, Restrictions]
5261 // The copyprivate clause must not be used with the nowait clause.
5262 OMPClause *Nowait = nullptr;
5263 OMPClause *Copyprivate = nullptr;
5264 for (auto *Clause : Clauses) {
5265 if (Clause->getClauseKind() == OMPC_nowait)
5266 Nowait = Clause;
5267 else if (Clause->getClauseKind() == OMPC_copyprivate)
5268 Copyprivate = Clause;
5269 if (Copyprivate && Nowait) {
5270 Diag(Copyprivate->getLocStart(),
5271 diag::err_omp_single_copyprivate_with_nowait);
5272 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5273 return StmtError();
5274 }
5275 }
5276
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005277 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5278}
5279
Alexander Musman80c22892014-07-17 08:54:58 +00005280StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5281 SourceLocation StartLoc,
5282 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005283 if (!AStmt)
5284 return StmtError();
5285
5286 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005287
5288 getCurFunction()->setHasBranchProtectedScope();
5289
5290 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5291}
5292
Alexey Bataev28c75412015-12-15 08:19:24 +00005293StmtResult Sema::ActOnOpenMPCriticalDirective(
5294 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5295 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005296 if (!AStmt)
5297 return StmtError();
5298
5299 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005300
Alexey Bataev28c75412015-12-15 08:19:24 +00005301 bool ErrorFound = false;
5302 llvm::APSInt Hint;
5303 SourceLocation HintLoc;
5304 bool DependentHint = false;
5305 for (auto *C : Clauses) {
5306 if (C->getClauseKind() == OMPC_hint) {
5307 if (!DirName.getName()) {
5308 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5309 ErrorFound = true;
5310 }
5311 Expr *E = cast<OMPHintClause>(C)->getHint();
5312 if (E->isTypeDependent() || E->isValueDependent() ||
5313 E->isInstantiationDependent())
5314 DependentHint = true;
5315 else {
5316 Hint = E->EvaluateKnownConstInt(Context);
5317 HintLoc = C->getLocStart();
5318 }
5319 }
5320 }
5321 if (ErrorFound)
5322 return StmtError();
5323 auto Pair = DSAStack->getCriticalWithHint(DirName);
5324 if (Pair.first && DirName.getName() && !DependentHint) {
5325 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5326 Diag(StartLoc, diag::err_omp_critical_with_hint);
5327 if (HintLoc.isValid()) {
5328 Diag(HintLoc, diag::note_omp_critical_hint_here)
5329 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5330 } else
5331 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5332 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5333 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5334 << 1
5335 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5336 /*Radix=*/10, /*Signed=*/false);
5337 } else
5338 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5339 }
5340 }
5341
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005342 getCurFunction()->setHasBranchProtectedScope();
5343
Alexey Bataev28c75412015-12-15 08:19:24 +00005344 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5345 Clauses, AStmt);
5346 if (!Pair.first && DirName.getName() && !DependentHint)
5347 DSAStack->addCriticalWithHint(Dir, Hint);
5348 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005349}
5350
Alexey Bataev4acb8592014-07-07 13:01:15 +00005351StmtResult Sema::ActOnOpenMPParallelForDirective(
5352 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5353 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005354 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005355 if (!AStmt)
5356 return StmtError();
5357
Alexey Bataev4acb8592014-07-07 13:01:15 +00005358 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5359 // 1.2.2 OpenMP Language Terminology
5360 // Structured block - An executable statement with a single entry at the
5361 // top and a single exit at the bottom.
5362 // The point of exit cannot be a branch out of the structured block.
5363 // longjmp() and throw() must not violate the entry/exit criteria.
5364 CS->getCapturedDecl()->setNothrow();
5365
Alexander Musmanc6388682014-12-15 07:07:06 +00005366 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005367 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5368 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005369 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005370 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5371 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5372 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005373 if (NestedLoopCount == 0)
5374 return StmtError();
5375
Alexander Musmana5f070a2014-10-01 06:03:56 +00005376 assert((CurContext->isDependentContext() || B.builtAll()) &&
5377 "omp parallel for loop exprs were not built");
5378
Alexey Bataev54acd402015-08-04 11:18:19 +00005379 if (!CurContext->isDependentContext()) {
5380 // Finalize the clauses that need pre-built expressions for CodeGen.
5381 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005382 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005383 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005384 B.NumIterations, *this, CurScope,
5385 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005386 return StmtError();
5387 }
5388 }
5389
Alexey Bataev4acb8592014-07-07 13:01:15 +00005390 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005391 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005392 NestedLoopCount, Clauses, AStmt, B,
5393 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005394}
5395
Alexander Musmane4e893b2014-09-23 09:33:00 +00005396StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5397 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5398 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005399 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005400 if (!AStmt)
5401 return StmtError();
5402
Alexander Musmane4e893b2014-09-23 09:33:00 +00005403 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5404 // 1.2.2 OpenMP Language Terminology
5405 // Structured block - An executable statement with a single entry at the
5406 // top and a single exit at the bottom.
5407 // The point of exit cannot be a branch out of the structured block.
5408 // longjmp() and throw() must not violate the entry/exit criteria.
5409 CS->getCapturedDecl()->setNothrow();
5410
Alexander Musmanc6388682014-12-15 07:07:06 +00005411 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005412 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5413 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005414 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005415 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5416 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5417 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005418 if (NestedLoopCount == 0)
5419 return StmtError();
5420
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005421 if (!CurContext->isDependentContext()) {
5422 // Finalize the clauses that need pre-built expressions for CodeGen.
5423 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005424 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005425 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005426 B.NumIterations, *this, CurScope,
5427 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005428 return StmtError();
5429 }
5430 }
5431
Kelvin Lic5609492016-07-15 04:39:07 +00005432 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005433 return StmtError();
5434
Alexander Musmane4e893b2014-09-23 09:33:00 +00005435 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005436 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005437 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005438}
5439
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005440StmtResult
5441Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5442 Stmt *AStmt, SourceLocation StartLoc,
5443 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005444 if (!AStmt)
5445 return StmtError();
5446
5447 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005448 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005449 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005450 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005451 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005452 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005453 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005454 return StmtError();
5455 // All associated statements must be '#pragma omp section' except for
5456 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005457 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005458 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5459 if (SectionStmt)
5460 Diag(SectionStmt->getLocStart(),
5461 diag::err_omp_parallel_sections_substmt_not_section);
5462 return StmtError();
5463 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005464 cast<OMPSectionDirective>(SectionStmt)
5465 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005466 }
5467 } else {
5468 Diag(AStmt->getLocStart(),
5469 diag::err_omp_parallel_sections_not_compound_stmt);
5470 return StmtError();
5471 }
5472
5473 getCurFunction()->setHasBranchProtectedScope();
5474
Alexey Bataev25e5b442015-09-15 12:52:43 +00005475 return OMPParallelSectionsDirective::Create(
5476 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005477}
5478
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005479StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5480 Stmt *AStmt, SourceLocation StartLoc,
5481 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005482 if (!AStmt)
5483 return StmtError();
5484
David Majnemer9d168222016-08-05 17:44:54 +00005485 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005486 // 1.2.2 OpenMP Language Terminology
5487 // Structured block - An executable statement with a single entry at the
5488 // top and a single exit at the bottom.
5489 // The point of exit cannot be a branch out of the structured block.
5490 // longjmp() and throw() must not violate the entry/exit criteria.
5491 CS->getCapturedDecl()->setNothrow();
5492
5493 getCurFunction()->setHasBranchProtectedScope();
5494
Alexey Bataev25e5b442015-09-15 12:52:43 +00005495 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5496 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005497}
5498
Alexey Bataev68446b72014-07-18 07:47:19 +00005499StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5500 SourceLocation EndLoc) {
5501 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5502}
5503
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005504StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5505 SourceLocation EndLoc) {
5506 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5507}
5508
Alexey Bataev2df347a2014-07-18 10:17:07 +00005509StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5510 SourceLocation EndLoc) {
5511 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5512}
5513
Alexey Bataev169d96a2017-07-18 20:17:46 +00005514StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5515 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005516 SourceLocation StartLoc,
5517 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005518 if (!AStmt)
5519 return StmtError();
5520
5521 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005522
5523 getCurFunction()->setHasBranchProtectedScope();
5524
Alexey Bataev169d96a2017-07-18 20:17:46 +00005525 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00005526 AStmt,
5527 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005528}
5529
Alexey Bataev6125da92014-07-21 11:26:11 +00005530StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5531 SourceLocation StartLoc,
5532 SourceLocation EndLoc) {
5533 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5534 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5535}
5536
Alexey Bataev346265e2015-09-25 10:37:12 +00005537StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5538 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005539 SourceLocation StartLoc,
5540 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005541 OMPClause *DependFound = nullptr;
5542 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005543 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005544 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005545 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005546 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005547 for (auto *C : Clauses) {
5548 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5549 DependFound = C;
5550 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5551 if (DependSourceClause) {
5552 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5553 << getOpenMPDirectiveName(OMPD_ordered)
5554 << getOpenMPClauseName(OMPC_depend) << 2;
5555 ErrorFound = true;
5556 } else
5557 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005558 if (DependSinkClause) {
5559 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5560 << 0;
5561 ErrorFound = true;
5562 }
5563 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5564 if (DependSourceClause) {
5565 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5566 << 1;
5567 ErrorFound = true;
5568 }
5569 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005570 }
5571 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005572 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005573 else if (C->getClauseKind() == OMPC_simd)
5574 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005575 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005576 if (!ErrorFound && !SC &&
5577 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005578 // OpenMP [2.8.1,simd Construct, Restrictions]
5579 // An ordered construct with the simd clause is the only OpenMP construct
5580 // that can appear in the simd region.
5581 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005582 ErrorFound = true;
5583 } else if (DependFound && (TC || SC)) {
5584 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5585 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5586 ErrorFound = true;
5587 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5588 Diag(DependFound->getLocStart(),
5589 diag::err_omp_ordered_directive_without_param);
5590 ErrorFound = true;
5591 } else if (TC || Clauses.empty()) {
5592 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5593 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5594 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5595 << (TC != nullptr);
5596 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5597 ErrorFound = true;
5598 }
5599 }
5600 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005601 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005602
5603 if (AStmt) {
5604 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5605
5606 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005607 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005608
5609 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005610}
5611
Alexey Bataev1d160b12015-03-13 12:27:31 +00005612namespace {
5613/// \brief Helper class for checking expression in 'omp atomic [update]'
5614/// construct.
5615class OpenMPAtomicUpdateChecker {
5616 /// \brief Error results for atomic update expressions.
5617 enum ExprAnalysisErrorCode {
5618 /// \brief A statement is not an expression statement.
5619 NotAnExpression,
5620 /// \brief Expression is not builtin binary or unary operation.
5621 NotABinaryOrUnaryExpression,
5622 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5623 NotAnUnaryIncDecExpression,
5624 /// \brief An expression is not of scalar type.
5625 NotAScalarType,
5626 /// \brief A binary operation is not an assignment operation.
5627 NotAnAssignmentOp,
5628 /// \brief RHS part of the binary operation is not a binary expression.
5629 NotABinaryExpression,
5630 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5631 /// expression.
5632 NotABinaryOperator,
5633 /// \brief RHS binary operation does not have reference to the updated LHS
5634 /// part.
5635 NotAnUpdateExpression,
5636 /// \brief No errors is found.
5637 NoError
5638 };
5639 /// \brief Reference to Sema.
5640 Sema &SemaRef;
5641 /// \brief A location for note diagnostics (when error is found).
5642 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005643 /// \brief 'x' lvalue part of the source atomic expression.
5644 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005645 /// \brief 'expr' rvalue part of the source atomic expression.
5646 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005647 /// \brief Helper expression of the form
5648 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5649 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5650 Expr *UpdateExpr;
5651 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5652 /// important for non-associative operations.
5653 bool IsXLHSInRHSPart;
5654 BinaryOperatorKind Op;
5655 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005656 /// \brief true if the source expression is a postfix unary operation, false
5657 /// if it is a prefix unary operation.
5658 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005659
5660public:
5661 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005662 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005663 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005664 /// \brief Check specified statement that it is suitable for 'atomic update'
5665 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005666 /// expression. If DiagId and NoteId == 0, then only check is performed
5667 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005668 /// \param DiagId Diagnostic which should be emitted if error is found.
5669 /// \param NoteId Diagnostic note for the main error message.
5670 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005671 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005672 /// \brief Return the 'x' lvalue part of the source atomic expression.
5673 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005674 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5675 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005676 /// \brief Return the update expression used in calculation of the updated
5677 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5678 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5679 Expr *getUpdateExpr() const { return UpdateExpr; }
5680 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5681 /// false otherwise.
5682 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5683
Alexey Bataevb78ca832015-04-01 03:33:17 +00005684 /// \brief true if the source expression is a postfix unary operation, false
5685 /// if it is a prefix unary operation.
5686 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5687
Alexey Bataev1d160b12015-03-13 12:27:31 +00005688private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005689 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5690 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005691};
5692} // namespace
5693
5694bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5695 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5696 ExprAnalysisErrorCode ErrorFound = NoError;
5697 SourceLocation ErrorLoc, NoteLoc;
5698 SourceRange ErrorRange, NoteRange;
5699 // Allowed constructs are:
5700 // x = x binop expr;
5701 // x = expr binop x;
5702 if (AtomicBinOp->getOpcode() == BO_Assign) {
5703 X = AtomicBinOp->getLHS();
5704 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5705 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5706 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5707 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5708 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005709 Op = AtomicInnerBinOp->getOpcode();
5710 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005711 auto *LHS = AtomicInnerBinOp->getLHS();
5712 auto *RHS = AtomicInnerBinOp->getRHS();
5713 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5714 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5715 /*Canonical=*/true);
5716 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5717 /*Canonical=*/true);
5718 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5719 /*Canonical=*/true);
5720 if (XId == LHSId) {
5721 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005722 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005723 } else if (XId == RHSId) {
5724 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005725 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005726 } else {
5727 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5728 ErrorRange = AtomicInnerBinOp->getSourceRange();
5729 NoteLoc = X->getExprLoc();
5730 NoteRange = X->getSourceRange();
5731 ErrorFound = NotAnUpdateExpression;
5732 }
5733 } else {
5734 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5735 ErrorRange = AtomicInnerBinOp->getSourceRange();
5736 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5737 NoteRange = SourceRange(NoteLoc, NoteLoc);
5738 ErrorFound = NotABinaryOperator;
5739 }
5740 } else {
5741 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5742 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5743 ErrorFound = NotABinaryExpression;
5744 }
5745 } else {
5746 ErrorLoc = AtomicBinOp->getExprLoc();
5747 ErrorRange = AtomicBinOp->getSourceRange();
5748 NoteLoc = AtomicBinOp->getOperatorLoc();
5749 NoteRange = SourceRange(NoteLoc, NoteLoc);
5750 ErrorFound = NotAnAssignmentOp;
5751 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005752 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005753 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5754 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5755 return true;
5756 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005757 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005758 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005759}
5760
5761bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5762 unsigned NoteId) {
5763 ExprAnalysisErrorCode ErrorFound = NoError;
5764 SourceLocation ErrorLoc, NoteLoc;
5765 SourceRange ErrorRange, NoteRange;
5766 // Allowed constructs are:
5767 // x++;
5768 // x--;
5769 // ++x;
5770 // --x;
5771 // x binop= expr;
5772 // x = x binop expr;
5773 // x = expr binop x;
5774 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5775 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5776 if (AtomicBody->getType()->isScalarType() ||
5777 AtomicBody->isInstantiationDependent()) {
5778 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5779 AtomicBody->IgnoreParenImpCasts())) {
5780 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005781 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005782 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005783 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005784 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005785 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005786 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005787 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5788 AtomicBody->IgnoreParenImpCasts())) {
5789 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005790 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005791 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005792 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5793 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005794 // Check for Unary Operation
5795 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005796 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005797 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5798 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005799 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005800 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5801 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005802 } else {
5803 ErrorFound = NotAnUnaryIncDecExpression;
5804 ErrorLoc = AtomicUnaryOp->getExprLoc();
5805 ErrorRange = AtomicUnaryOp->getSourceRange();
5806 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5807 NoteRange = SourceRange(NoteLoc, NoteLoc);
5808 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005809 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005810 ErrorFound = NotABinaryOrUnaryExpression;
5811 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5812 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5813 }
5814 } else {
5815 ErrorFound = NotAScalarType;
5816 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5817 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5818 }
5819 } else {
5820 ErrorFound = NotAnExpression;
5821 NoteLoc = ErrorLoc = S->getLocStart();
5822 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5823 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005824 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005825 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5826 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5827 return true;
5828 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005829 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005830 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005831 // Build an update expression of form 'OpaqueValueExpr(x) binop
5832 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5833 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5834 auto *OVEX = new (SemaRef.getASTContext())
5835 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5836 auto *OVEExpr = new (SemaRef.getASTContext())
5837 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5838 auto Update =
5839 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5840 IsXLHSInRHSPart ? OVEExpr : OVEX);
5841 if (Update.isInvalid())
5842 return true;
5843 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5844 Sema::AA_Casting);
5845 if (Update.isInvalid())
5846 return true;
5847 UpdateExpr = Update.get();
5848 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005849 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005850}
5851
Alexey Bataev0162e452014-07-22 10:10:35 +00005852StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5853 Stmt *AStmt,
5854 SourceLocation StartLoc,
5855 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005856 if (!AStmt)
5857 return StmtError();
5858
David Majnemer9d168222016-08-05 17:44:54 +00005859 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005860 // 1.2.2 OpenMP Language Terminology
5861 // Structured block - An executable statement with a single entry at the
5862 // top and a single exit at the bottom.
5863 // The point of exit cannot be a branch out of the structured block.
5864 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005865 OpenMPClauseKind AtomicKind = OMPC_unknown;
5866 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005867 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005868 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005869 C->getClauseKind() == OMPC_update ||
5870 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005871 if (AtomicKind != OMPC_unknown) {
5872 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5873 << SourceRange(C->getLocStart(), C->getLocEnd());
5874 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5875 << getOpenMPClauseName(AtomicKind);
5876 } else {
5877 AtomicKind = C->getClauseKind();
5878 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005879 }
5880 }
5881 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005882
Alexey Bataev459dec02014-07-24 06:46:57 +00005883 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005884 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5885 Body = EWC->getSubExpr();
5886
Alexey Bataev62cec442014-11-18 10:14:22 +00005887 Expr *X = nullptr;
5888 Expr *V = nullptr;
5889 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005890 Expr *UE = nullptr;
5891 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005892 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005893 // OpenMP [2.12.6, atomic Construct]
5894 // In the next expressions:
5895 // * x and v (as applicable) are both l-value expressions with scalar type.
5896 // * During the execution of an atomic region, multiple syntactic
5897 // occurrences of x must designate the same storage location.
5898 // * Neither of v and expr (as applicable) may access the storage location
5899 // designated by x.
5900 // * Neither of x and expr (as applicable) may access the storage location
5901 // designated by v.
5902 // * expr is an expression with scalar type.
5903 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5904 // * binop, binop=, ++, and -- are not overloaded operators.
5905 // * The expression x binop expr must be numerically equivalent to x binop
5906 // (expr). This requirement is satisfied if the operators in expr have
5907 // precedence greater than binop, or by using parentheses around expr or
5908 // subexpressions of expr.
5909 // * The expression expr binop x must be numerically equivalent to (expr)
5910 // binop x. This requirement is satisfied if the operators in expr have
5911 // precedence equal to or greater than binop, or by using parentheses around
5912 // expr or subexpressions of expr.
5913 // * For forms that allow multiple occurrences of x, the number of times
5914 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005915 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005916 enum {
5917 NotAnExpression,
5918 NotAnAssignmentOp,
5919 NotAScalarType,
5920 NotAnLValue,
5921 NoError
5922 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005923 SourceLocation ErrorLoc, NoteLoc;
5924 SourceRange ErrorRange, NoteRange;
5925 // If clause is read:
5926 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005927 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5928 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005929 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5930 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5931 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5932 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5933 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5934 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5935 if (!X->isLValue() || !V->isLValue()) {
5936 auto NotLValueExpr = X->isLValue() ? V : X;
5937 ErrorFound = NotAnLValue;
5938 ErrorLoc = AtomicBinOp->getExprLoc();
5939 ErrorRange = AtomicBinOp->getSourceRange();
5940 NoteLoc = NotLValueExpr->getExprLoc();
5941 NoteRange = NotLValueExpr->getSourceRange();
5942 }
5943 } else if (!X->isInstantiationDependent() ||
5944 !V->isInstantiationDependent()) {
5945 auto NotScalarExpr =
5946 (X->isInstantiationDependent() || X->getType()->isScalarType())
5947 ? V
5948 : X;
5949 ErrorFound = NotAScalarType;
5950 ErrorLoc = AtomicBinOp->getExprLoc();
5951 ErrorRange = AtomicBinOp->getSourceRange();
5952 NoteLoc = NotScalarExpr->getExprLoc();
5953 NoteRange = NotScalarExpr->getSourceRange();
5954 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005955 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005956 ErrorFound = NotAnAssignmentOp;
5957 ErrorLoc = AtomicBody->getExprLoc();
5958 ErrorRange = AtomicBody->getSourceRange();
5959 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5960 : AtomicBody->getExprLoc();
5961 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5962 : AtomicBody->getSourceRange();
5963 }
5964 } else {
5965 ErrorFound = NotAnExpression;
5966 NoteLoc = ErrorLoc = Body->getLocStart();
5967 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005968 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005969 if (ErrorFound != NoError) {
5970 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5971 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005972 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5973 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005974 return StmtError();
5975 } else if (CurContext->isDependentContext())
5976 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005977 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005978 enum {
5979 NotAnExpression,
5980 NotAnAssignmentOp,
5981 NotAScalarType,
5982 NotAnLValue,
5983 NoError
5984 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005985 SourceLocation ErrorLoc, NoteLoc;
5986 SourceRange ErrorRange, NoteRange;
5987 // If clause is write:
5988 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005989 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5990 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005991 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5992 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005993 X = AtomicBinOp->getLHS();
5994 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005995 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5996 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5997 if (!X->isLValue()) {
5998 ErrorFound = NotAnLValue;
5999 ErrorLoc = AtomicBinOp->getExprLoc();
6000 ErrorRange = AtomicBinOp->getSourceRange();
6001 NoteLoc = X->getExprLoc();
6002 NoteRange = X->getSourceRange();
6003 }
6004 } else if (!X->isInstantiationDependent() ||
6005 !E->isInstantiationDependent()) {
6006 auto NotScalarExpr =
6007 (X->isInstantiationDependent() || X->getType()->isScalarType())
6008 ? E
6009 : X;
6010 ErrorFound = NotAScalarType;
6011 ErrorLoc = AtomicBinOp->getExprLoc();
6012 ErrorRange = AtomicBinOp->getSourceRange();
6013 NoteLoc = NotScalarExpr->getExprLoc();
6014 NoteRange = NotScalarExpr->getSourceRange();
6015 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006016 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00006017 ErrorFound = NotAnAssignmentOp;
6018 ErrorLoc = AtomicBody->getExprLoc();
6019 ErrorRange = AtomicBody->getSourceRange();
6020 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6021 : AtomicBody->getExprLoc();
6022 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6023 : AtomicBody->getSourceRange();
6024 }
6025 } else {
6026 ErrorFound = NotAnExpression;
6027 NoteLoc = ErrorLoc = Body->getLocStart();
6028 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006029 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00006030 if (ErrorFound != NoError) {
6031 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6032 << ErrorRange;
6033 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6034 << NoteRange;
6035 return StmtError();
6036 } else if (CurContext->isDependentContext())
6037 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006038 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006039 // If clause is update:
6040 // x++;
6041 // x--;
6042 // ++x;
6043 // --x;
6044 // x binop= expr;
6045 // x = x binop expr;
6046 // x = expr binop x;
6047 OpenMPAtomicUpdateChecker Checker(*this);
6048 if (Checker.checkStatement(
6049 Body, (AtomicKind == OMPC_update)
6050 ? diag::err_omp_atomic_update_not_expression_statement
6051 : diag::err_omp_atomic_not_expression_statement,
6052 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006053 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006054 if (!CurContext->isDependentContext()) {
6055 E = Checker.getExpr();
6056 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006057 UE = Checker.getUpdateExpr();
6058 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006059 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006060 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006061 enum {
6062 NotAnAssignmentOp,
6063 NotACompoundStatement,
6064 NotTwoSubstatements,
6065 NotASpecificExpression,
6066 NoError
6067 } ErrorFound = NoError;
6068 SourceLocation ErrorLoc, NoteLoc;
6069 SourceRange ErrorRange, NoteRange;
6070 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6071 // If clause is a capture:
6072 // v = x++;
6073 // v = x--;
6074 // v = ++x;
6075 // v = --x;
6076 // v = x binop= expr;
6077 // v = x = x binop expr;
6078 // v = x = expr binop x;
6079 auto *AtomicBinOp =
6080 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6081 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6082 V = AtomicBinOp->getLHS();
6083 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6084 OpenMPAtomicUpdateChecker Checker(*this);
6085 if (Checker.checkStatement(
6086 Body, diag::err_omp_atomic_capture_not_expression_statement,
6087 diag::note_omp_atomic_update))
6088 return StmtError();
6089 E = Checker.getExpr();
6090 X = Checker.getX();
6091 UE = Checker.getUpdateExpr();
6092 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6093 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006094 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006095 ErrorLoc = AtomicBody->getExprLoc();
6096 ErrorRange = AtomicBody->getSourceRange();
6097 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6098 : AtomicBody->getExprLoc();
6099 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6100 : AtomicBody->getSourceRange();
6101 ErrorFound = NotAnAssignmentOp;
6102 }
6103 if (ErrorFound != NoError) {
6104 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6105 << ErrorRange;
6106 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6107 return StmtError();
6108 } else if (CurContext->isDependentContext()) {
6109 UE = V = E = X = nullptr;
6110 }
6111 } else {
6112 // If clause is a capture:
6113 // { v = x; x = expr; }
6114 // { v = x; x++; }
6115 // { v = x; x--; }
6116 // { v = x; ++x; }
6117 // { v = x; --x; }
6118 // { v = x; x binop= expr; }
6119 // { v = x; x = x binop expr; }
6120 // { v = x; x = expr binop x; }
6121 // { x++; v = x; }
6122 // { x--; v = x; }
6123 // { ++x; v = x; }
6124 // { --x; v = x; }
6125 // { x binop= expr; v = x; }
6126 // { x = x binop expr; v = x; }
6127 // { x = expr binop x; v = x; }
6128 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6129 // Check that this is { expr1; expr2; }
6130 if (CS->size() == 2) {
6131 auto *First = CS->body_front();
6132 auto *Second = CS->body_back();
6133 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6134 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6135 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6136 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6137 // Need to find what subexpression is 'v' and what is 'x'.
6138 OpenMPAtomicUpdateChecker Checker(*this);
6139 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6140 BinaryOperator *BinOp = nullptr;
6141 if (IsUpdateExprFound) {
6142 BinOp = dyn_cast<BinaryOperator>(First);
6143 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6144 }
6145 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6146 // { v = x; x++; }
6147 // { v = x; x--; }
6148 // { v = x; ++x; }
6149 // { v = x; --x; }
6150 // { v = x; x binop= expr; }
6151 // { v = x; x = x binop expr; }
6152 // { v = x; x = expr binop x; }
6153 // Check that the first expression has form v = x.
6154 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6155 llvm::FoldingSetNodeID XId, PossibleXId;
6156 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6157 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6158 IsUpdateExprFound = XId == PossibleXId;
6159 if (IsUpdateExprFound) {
6160 V = BinOp->getLHS();
6161 X = Checker.getX();
6162 E = Checker.getExpr();
6163 UE = Checker.getUpdateExpr();
6164 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006165 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006166 }
6167 }
6168 if (!IsUpdateExprFound) {
6169 IsUpdateExprFound = !Checker.checkStatement(First);
6170 BinOp = nullptr;
6171 if (IsUpdateExprFound) {
6172 BinOp = dyn_cast<BinaryOperator>(Second);
6173 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6174 }
6175 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6176 // { x++; v = x; }
6177 // { x--; v = x; }
6178 // { ++x; v = x; }
6179 // { --x; v = x; }
6180 // { x binop= expr; v = x; }
6181 // { x = x binop expr; v = x; }
6182 // { x = expr binop x; v = x; }
6183 // Check that the second expression has form v = x.
6184 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6185 llvm::FoldingSetNodeID XId, PossibleXId;
6186 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6187 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6188 IsUpdateExprFound = XId == PossibleXId;
6189 if (IsUpdateExprFound) {
6190 V = BinOp->getLHS();
6191 X = Checker.getX();
6192 E = Checker.getExpr();
6193 UE = Checker.getUpdateExpr();
6194 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006195 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006196 }
6197 }
6198 }
6199 if (!IsUpdateExprFound) {
6200 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00006201 auto *FirstExpr = dyn_cast<Expr>(First);
6202 auto *SecondExpr = dyn_cast<Expr>(Second);
6203 if (!FirstExpr || !SecondExpr ||
6204 !(FirstExpr->isInstantiationDependent() ||
6205 SecondExpr->isInstantiationDependent())) {
6206 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6207 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006208 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00006209 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6210 : First->getLocStart();
6211 NoteRange = ErrorRange = FirstBinOp
6212 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00006213 : SourceRange(ErrorLoc, ErrorLoc);
6214 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006215 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6216 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6217 ErrorFound = NotAnAssignmentOp;
6218 NoteLoc = ErrorLoc = SecondBinOp
6219 ? SecondBinOp->getOperatorLoc()
6220 : Second->getLocStart();
6221 NoteRange = ErrorRange =
6222 SecondBinOp ? SecondBinOp->getSourceRange()
6223 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006224 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006225 auto *PossibleXRHSInFirst =
6226 FirstBinOp->getRHS()->IgnoreParenImpCasts();
6227 auto *PossibleXLHSInSecond =
6228 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6229 llvm::FoldingSetNodeID X1Id, X2Id;
6230 PossibleXRHSInFirst->Profile(X1Id, Context,
6231 /*Canonical=*/true);
6232 PossibleXLHSInSecond->Profile(X2Id, Context,
6233 /*Canonical=*/true);
6234 IsUpdateExprFound = X1Id == X2Id;
6235 if (IsUpdateExprFound) {
6236 V = FirstBinOp->getLHS();
6237 X = SecondBinOp->getLHS();
6238 E = SecondBinOp->getRHS();
6239 UE = nullptr;
6240 IsXLHSInRHSPart = false;
6241 IsPostfixUpdate = true;
6242 } else {
6243 ErrorFound = NotASpecificExpression;
6244 ErrorLoc = FirstBinOp->getExprLoc();
6245 ErrorRange = FirstBinOp->getSourceRange();
6246 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6247 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6248 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006249 }
6250 }
6251 }
6252 }
6253 } else {
6254 NoteLoc = ErrorLoc = Body->getLocStart();
6255 NoteRange = ErrorRange =
6256 SourceRange(Body->getLocStart(), Body->getLocStart());
6257 ErrorFound = NotTwoSubstatements;
6258 }
6259 } else {
6260 NoteLoc = ErrorLoc = Body->getLocStart();
6261 NoteRange = ErrorRange =
6262 SourceRange(Body->getLocStart(), Body->getLocStart());
6263 ErrorFound = NotACompoundStatement;
6264 }
6265 if (ErrorFound != NoError) {
6266 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6267 << ErrorRange;
6268 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6269 return StmtError();
6270 } else if (CurContext->isDependentContext()) {
6271 UE = V = E = X = nullptr;
6272 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006273 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006274 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006275
6276 getCurFunction()->setHasBranchProtectedScope();
6277
Alexey Bataev62cec442014-11-18 10:14:22 +00006278 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006279 X, V, E, UE, IsXLHSInRHSPart,
6280 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006281}
6282
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006283StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6284 Stmt *AStmt,
6285 SourceLocation StartLoc,
6286 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006287 if (!AStmt)
6288 return StmtError();
6289
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006290 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6291 // 1.2.2 OpenMP Language Terminology
6292 // Structured block - An executable statement with a single entry at the
6293 // top and a single exit at the bottom.
6294 // The point of exit cannot be a branch out of the structured block.
6295 // longjmp() and throw() must not violate the entry/exit criteria.
6296 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006297
Alexey Bataev13314bf2014-10-09 04:18:56 +00006298 // OpenMP [2.16, Nesting of Regions]
6299 // If specified, a teams construct must be contained within a target
6300 // construct. That target construct must contain no statements or directives
6301 // outside of the teams construct.
6302 if (DSAStack->hasInnerTeamsRegion()) {
6303 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
6304 bool OMPTeamsFound = true;
6305 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6306 auto I = CS->body_begin();
6307 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00006308 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006309 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6310 OMPTeamsFound = false;
6311 break;
6312 }
6313 ++I;
6314 }
6315 assert(I != CS->body_end() && "Not found statement");
6316 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00006317 } else {
6318 auto *OED = dyn_cast<OMPExecutableDirective>(S);
6319 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00006320 }
6321 if (!OMPTeamsFound) {
6322 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6323 Diag(DSAStack->getInnerTeamsRegionLoc(),
6324 diag::note_omp_nested_teams_construct_here);
6325 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6326 << isa<OMPExecutableDirective>(S);
6327 return StmtError();
6328 }
6329 }
6330
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006331 getCurFunction()->setHasBranchProtectedScope();
6332
6333 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6334}
6335
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006336StmtResult
6337Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6338 Stmt *AStmt, SourceLocation StartLoc,
6339 SourceLocation EndLoc) {
6340 if (!AStmt)
6341 return StmtError();
6342
6343 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6344 // 1.2.2 OpenMP Language Terminology
6345 // Structured block - An executable statement with a single entry at the
6346 // top and a single exit at the bottom.
6347 // The point of exit cannot be a branch out of the structured block.
6348 // longjmp() and throw() must not violate the entry/exit criteria.
6349 CS->getCapturedDecl()->setNothrow();
6350
6351 getCurFunction()->setHasBranchProtectedScope();
6352
6353 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6354 AStmt);
6355}
6356
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006357StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6358 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6359 SourceLocation EndLoc,
6360 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6361 if (!AStmt)
6362 return StmtError();
6363
6364 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6365 // 1.2.2 OpenMP Language Terminology
6366 // Structured block - An executable statement with a single entry at the
6367 // top and a single exit at the bottom.
6368 // The point of exit cannot be a branch out of the structured block.
6369 // longjmp() and throw() must not violate the entry/exit criteria.
6370 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006371 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6372 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6373 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6374 // 1.2.2 OpenMP Language Terminology
6375 // Structured block - An executable statement with a single entry at the
6376 // top and a single exit at the bottom.
6377 // The point of exit cannot be a branch out of the structured block.
6378 // longjmp() and throw() must not violate the entry/exit criteria.
6379 CS->getCapturedDecl()->setNothrow();
6380 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006381
6382 OMPLoopDirective::HelperExprs B;
6383 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6384 // define the nested loops number.
6385 unsigned NestedLoopCount =
6386 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006387 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006388 VarsWithImplicitDSA, B);
6389 if (NestedLoopCount == 0)
6390 return StmtError();
6391
6392 assert((CurContext->isDependentContext() || B.builtAll()) &&
6393 "omp target parallel for loop exprs were not built");
6394
6395 if (!CurContext->isDependentContext()) {
6396 // Finalize the clauses that need pre-built expressions for CodeGen.
6397 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006398 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006399 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006400 B.NumIterations, *this, CurScope,
6401 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006402 return StmtError();
6403 }
6404 }
6405
6406 getCurFunction()->setHasBranchProtectedScope();
6407 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6408 NestedLoopCount, Clauses, AStmt,
6409 B, DSAStack->isCancelRegion());
6410}
6411
Alexey Bataev95b64a92017-05-30 16:00:04 +00006412/// Check for existence of a map clause in the list of clauses.
6413static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6414 const OpenMPClauseKind K) {
6415 return llvm::any_of(
6416 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6417}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006418
Alexey Bataev95b64a92017-05-30 16:00:04 +00006419template <typename... Params>
6420static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6421 const Params... ClauseTypes) {
6422 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006423}
6424
Michael Wong65f367f2015-07-21 13:44:28 +00006425StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6426 Stmt *AStmt,
6427 SourceLocation StartLoc,
6428 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006429 if (!AStmt)
6430 return StmtError();
6431
6432 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6433
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006434 // OpenMP [2.10.1, Restrictions, p. 97]
6435 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006436 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6437 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6438 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006439 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006440 return StmtError();
6441 }
6442
Michael Wong65f367f2015-07-21 13:44:28 +00006443 getCurFunction()->setHasBranchProtectedScope();
6444
6445 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6446 AStmt);
6447}
6448
Samuel Antaodf67fc42016-01-19 19:15:56 +00006449StmtResult
6450Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6451 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006452 SourceLocation EndLoc, Stmt *AStmt) {
6453 if (!AStmt)
6454 return StmtError();
6455
6456 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6457 // 1.2.2 OpenMP Language Terminology
6458 // Structured block - An executable statement with a single entry at the
6459 // top and a single exit at the bottom.
6460 // The point of exit cannot be a branch out of the structured block.
6461 // longjmp() and throw() must not violate the entry/exit criteria.
6462 CS->getCapturedDecl()->setNothrow();
6463 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
6464 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6465 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6466 // 1.2.2 OpenMP Language Terminology
6467 // Structured block - An executable statement with a single entry at the
6468 // top and a single exit at the bottom.
6469 // The point of exit cannot be a branch out of the structured block.
6470 // longjmp() and throw() must not violate the entry/exit criteria.
6471 CS->getCapturedDecl()->setNothrow();
6472 }
6473
Samuel Antaodf67fc42016-01-19 19:15:56 +00006474 // OpenMP [2.10.2, Restrictions, p. 99]
6475 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006476 if (!hasClauses(Clauses, OMPC_map)) {
6477 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6478 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006479 return StmtError();
6480 }
6481
Alexey Bataev7828b252017-11-21 17:08:48 +00006482 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6483 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006484}
6485
Samuel Antao72590762016-01-19 20:04:50 +00006486StmtResult
6487Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6488 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006489 SourceLocation EndLoc, Stmt *AStmt) {
6490 if (!AStmt)
6491 return StmtError();
6492
6493 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6494 // 1.2.2 OpenMP Language Terminology
6495 // Structured block - An executable statement with a single entry at the
6496 // top and a single exit at the bottom.
6497 // The point of exit cannot be a branch out of the structured block.
6498 // longjmp() and throw() must not violate the entry/exit criteria.
6499 CS->getCapturedDecl()->setNothrow();
6500 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
6501 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6502 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6503 // 1.2.2 OpenMP Language Terminology
6504 // Structured block - An executable statement with a single entry at the
6505 // top and a single exit at the bottom.
6506 // The point of exit cannot be a branch out of the structured block.
6507 // longjmp() and throw() must not violate the entry/exit criteria.
6508 CS->getCapturedDecl()->setNothrow();
6509 }
6510
Samuel Antao72590762016-01-19 20:04:50 +00006511 // OpenMP [2.10.3, Restrictions, p. 102]
6512 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006513 if (!hasClauses(Clauses, OMPC_map)) {
6514 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6515 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006516 return StmtError();
6517 }
6518
Alexey Bataev7828b252017-11-21 17:08:48 +00006519 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6520 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00006521}
6522
Samuel Antao686c70c2016-05-26 17:30:50 +00006523StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6524 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006525 SourceLocation EndLoc,
6526 Stmt *AStmt) {
6527 if (!AStmt)
6528 return StmtError();
6529
6530 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6531 // 1.2.2 OpenMP Language Terminology
6532 // Structured block - An executable statement with a single entry at the
6533 // top and a single exit at the bottom.
6534 // The point of exit cannot be a branch out of the structured block.
6535 // longjmp() and throw() must not violate the entry/exit criteria.
6536 CS->getCapturedDecl()->setNothrow();
6537 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
6538 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6539 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6540 // 1.2.2 OpenMP Language Terminology
6541 // Structured block - An executable statement with a single entry at the
6542 // top and a single exit at the bottom.
6543 // The point of exit cannot be a branch out of the structured block.
6544 // longjmp() and throw() must not violate the entry/exit criteria.
6545 CS->getCapturedDecl()->setNothrow();
6546 }
6547
Alexey Bataev95b64a92017-05-30 16:00:04 +00006548 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006549 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6550 return StmtError();
6551 }
Alexey Bataev7828b252017-11-21 17:08:48 +00006552 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
6553 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00006554}
6555
Alexey Bataev13314bf2014-10-09 04:18:56 +00006556StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6557 Stmt *AStmt, SourceLocation StartLoc,
6558 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006559 if (!AStmt)
6560 return StmtError();
6561
Alexey Bataev13314bf2014-10-09 04:18:56 +00006562 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6563 // 1.2.2 OpenMP Language Terminology
6564 // Structured block - An executable statement with a single entry at the
6565 // top and a single exit at the bottom.
6566 // The point of exit cannot be a branch out of the structured block.
6567 // longjmp() and throw() must not violate the entry/exit criteria.
6568 CS->getCapturedDecl()->setNothrow();
6569
6570 getCurFunction()->setHasBranchProtectedScope();
6571
6572 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6573}
6574
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006575StmtResult
6576Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6577 SourceLocation EndLoc,
6578 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006579 if (DSAStack->isParentNowaitRegion()) {
6580 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6581 return StmtError();
6582 }
6583 if (DSAStack->isParentOrderedRegion()) {
6584 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6585 return StmtError();
6586 }
6587 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6588 CancelRegion);
6589}
6590
Alexey Bataev87933c72015-09-18 08:07:34 +00006591StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6592 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006593 SourceLocation EndLoc,
6594 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006595 if (DSAStack->isParentNowaitRegion()) {
6596 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6597 return StmtError();
6598 }
6599 if (DSAStack->isParentOrderedRegion()) {
6600 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6601 return StmtError();
6602 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006603 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006604 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6605 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006606}
6607
Alexey Bataev382967a2015-12-08 12:06:20 +00006608static bool checkGrainsizeNumTasksClauses(Sema &S,
6609 ArrayRef<OMPClause *> Clauses) {
6610 OMPClause *PrevClause = nullptr;
6611 bool ErrorFound = false;
6612 for (auto *C : Clauses) {
6613 if (C->getClauseKind() == OMPC_grainsize ||
6614 C->getClauseKind() == OMPC_num_tasks) {
6615 if (!PrevClause)
6616 PrevClause = C;
6617 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6618 S.Diag(C->getLocStart(),
6619 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6620 << getOpenMPClauseName(C->getClauseKind())
6621 << getOpenMPClauseName(PrevClause->getClauseKind());
6622 S.Diag(PrevClause->getLocStart(),
6623 diag::note_omp_previous_grainsize_num_tasks)
6624 << getOpenMPClauseName(PrevClause->getClauseKind());
6625 ErrorFound = true;
6626 }
6627 }
6628 }
6629 return ErrorFound;
6630}
6631
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006632static bool checkReductionClauseWithNogroup(Sema &S,
6633 ArrayRef<OMPClause *> Clauses) {
6634 OMPClause *ReductionClause = nullptr;
6635 OMPClause *NogroupClause = nullptr;
6636 for (auto *C : Clauses) {
6637 if (C->getClauseKind() == OMPC_reduction) {
6638 ReductionClause = C;
6639 if (NogroupClause)
6640 break;
6641 continue;
6642 }
6643 if (C->getClauseKind() == OMPC_nogroup) {
6644 NogroupClause = C;
6645 if (ReductionClause)
6646 break;
6647 continue;
6648 }
6649 }
6650 if (ReductionClause && NogroupClause) {
6651 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6652 << SourceRange(NogroupClause->getLocStart(),
6653 NogroupClause->getLocEnd());
6654 return true;
6655 }
6656 return false;
6657}
6658
Alexey Bataev49f6e782015-12-01 04:18:41 +00006659StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6660 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6661 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006662 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006663 if (!AStmt)
6664 return StmtError();
6665
6666 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6667 OMPLoopDirective::HelperExprs B;
6668 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6669 // define the nested loops number.
6670 unsigned NestedLoopCount =
6671 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006672 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006673 VarsWithImplicitDSA, B);
6674 if (NestedLoopCount == 0)
6675 return StmtError();
6676
6677 assert((CurContext->isDependentContext() || B.builtAll()) &&
6678 "omp for loop exprs were not built");
6679
Alexey Bataev382967a2015-12-08 12:06:20 +00006680 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6681 // The grainsize clause and num_tasks clause are mutually exclusive and may
6682 // not appear on the same taskloop directive.
6683 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6684 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006685 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6686 // If a reduction clause is present on the taskloop directive, the nogroup
6687 // clause must not be specified.
6688 if (checkReductionClauseWithNogroup(*this, Clauses))
6689 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006690
Alexey Bataev49f6e782015-12-01 04:18:41 +00006691 getCurFunction()->setHasBranchProtectedScope();
6692 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6693 NestedLoopCount, Clauses, AStmt, B);
6694}
6695
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006696StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6697 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6698 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006699 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006700 if (!AStmt)
6701 return StmtError();
6702
6703 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6704 OMPLoopDirective::HelperExprs B;
6705 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6706 // define the nested loops number.
6707 unsigned NestedLoopCount =
6708 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6709 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6710 VarsWithImplicitDSA, B);
6711 if (NestedLoopCount == 0)
6712 return StmtError();
6713
6714 assert((CurContext->isDependentContext() || B.builtAll()) &&
6715 "omp for loop exprs were not built");
6716
Alexey Bataev5a3af132016-03-29 08:58:54 +00006717 if (!CurContext->isDependentContext()) {
6718 // Finalize the clauses that need pre-built expressions for CodeGen.
6719 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006720 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006721 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006722 B.NumIterations, *this, CurScope,
6723 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006724 return StmtError();
6725 }
6726 }
6727
Alexey Bataev382967a2015-12-08 12:06:20 +00006728 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6729 // The grainsize clause and num_tasks clause are mutually exclusive and may
6730 // not appear on the same taskloop directive.
6731 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6732 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006733 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6734 // If a reduction clause is present on the taskloop directive, the nogroup
6735 // clause must not be specified.
6736 if (checkReductionClauseWithNogroup(*this, Clauses))
6737 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00006738 if (checkSimdlenSafelenSpecified(*this, Clauses))
6739 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006740
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006741 getCurFunction()->setHasBranchProtectedScope();
6742 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6743 NestedLoopCount, Clauses, AStmt, B);
6744}
6745
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006746StmtResult Sema::ActOnOpenMPDistributeDirective(
6747 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6748 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006749 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006750 if (!AStmt)
6751 return StmtError();
6752
6753 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6754 OMPLoopDirective::HelperExprs B;
6755 // In presence of clause 'collapse' with number of loops, it will
6756 // define the nested loops number.
6757 unsigned NestedLoopCount =
6758 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6759 nullptr /*ordered not a clause on distribute*/, AStmt,
6760 *this, *DSAStack, VarsWithImplicitDSA, B);
6761 if (NestedLoopCount == 0)
6762 return StmtError();
6763
6764 assert((CurContext->isDependentContext() || B.builtAll()) &&
6765 "omp for loop exprs were not built");
6766
6767 getCurFunction()->setHasBranchProtectedScope();
6768 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6769 NestedLoopCount, Clauses, AStmt, B);
6770}
6771
Carlo Bertolli9925f152016-06-27 14:55:37 +00006772StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6773 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6774 SourceLocation EndLoc,
6775 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6776 if (!AStmt)
6777 return StmtError();
6778
6779 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6780 // 1.2.2 OpenMP Language Terminology
6781 // Structured block - An executable statement with a single entry at the
6782 // top and a single exit at the bottom.
6783 // The point of exit cannot be a branch out of the structured block.
6784 // longjmp() and throw() must not violate the entry/exit criteria.
6785 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00006786 for (int ThisCaptureLevel =
6787 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
6788 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6789 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6790 // 1.2.2 OpenMP Language Terminology
6791 // Structured block - An executable statement with a single entry at the
6792 // top and a single exit at the bottom.
6793 // The point of exit cannot be a branch out of the structured block.
6794 // longjmp() and throw() must not violate the entry/exit criteria.
6795 CS->getCapturedDecl()->setNothrow();
6796 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00006797
6798 OMPLoopDirective::HelperExprs B;
6799 // In presence of clause 'collapse' with number of loops, it will
6800 // define the nested loops number.
6801 unsigned NestedLoopCount = CheckOpenMPLoop(
6802 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00006803 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00006804 VarsWithImplicitDSA, B);
6805 if (NestedLoopCount == 0)
6806 return StmtError();
6807
6808 assert((CurContext->isDependentContext() || B.builtAll()) &&
6809 "omp for loop exprs were not built");
6810
Alexey Bataev438388c2017-11-22 18:34:02 +00006811 if (!CurContext->isDependentContext()) {
6812 // Finalize the clauses that need pre-built expressions for CodeGen.
6813 for (auto C : Clauses) {
6814 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6815 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6816 B.NumIterations, *this, CurScope,
6817 DSAStack))
6818 return StmtError();
6819 }
6820 }
6821
Carlo Bertolli9925f152016-06-27 14:55:37 +00006822 getCurFunction()->setHasBranchProtectedScope();
6823 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00006824 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
6825 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00006826}
6827
Kelvin Li4a39add2016-07-05 05:00:15 +00006828StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6829 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6830 SourceLocation EndLoc,
6831 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6832 if (!AStmt)
6833 return StmtError();
6834
6835 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6836 // 1.2.2 OpenMP Language Terminology
6837 // Structured block - An executable statement with a single entry at the
6838 // top and a single exit at the bottom.
6839 // The point of exit cannot be a branch out of the structured block.
6840 // longjmp() and throw() must not violate the entry/exit criteria.
6841 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00006842 for (int ThisCaptureLevel =
6843 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
6844 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6845 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6846 // 1.2.2 OpenMP Language Terminology
6847 // Structured block - An executable statement with a single entry at the
6848 // top and a single exit at the bottom.
6849 // The point of exit cannot be a branch out of the structured block.
6850 // longjmp() and throw() must not violate the entry/exit criteria.
6851 CS->getCapturedDecl()->setNothrow();
6852 }
Kelvin Li4a39add2016-07-05 05:00:15 +00006853
6854 OMPLoopDirective::HelperExprs B;
6855 // In presence of clause 'collapse' with number of loops, it will
6856 // define the nested loops number.
6857 unsigned NestedLoopCount = CheckOpenMPLoop(
6858 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00006859 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00006860 VarsWithImplicitDSA, B);
6861 if (NestedLoopCount == 0)
6862 return StmtError();
6863
6864 assert((CurContext->isDependentContext() || B.builtAll()) &&
6865 "omp for loop exprs were not built");
6866
Alexey Bataev438388c2017-11-22 18:34:02 +00006867 if (!CurContext->isDependentContext()) {
6868 // Finalize the clauses that need pre-built expressions for CodeGen.
6869 for (auto C : Clauses) {
6870 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6871 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6872 B.NumIterations, *this, CurScope,
6873 DSAStack))
6874 return StmtError();
6875 }
6876 }
6877
Kelvin Lic5609492016-07-15 04:39:07 +00006878 if (checkSimdlenSafelenSpecified(*this, Clauses))
6879 return StmtError();
6880
Kelvin Li4a39add2016-07-05 05:00:15 +00006881 getCurFunction()->setHasBranchProtectedScope();
6882 return OMPDistributeParallelForSimdDirective::Create(
6883 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6884}
6885
Kelvin Li787f3fc2016-07-06 04:45:38 +00006886StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6887 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6888 SourceLocation EndLoc,
6889 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6890 if (!AStmt)
6891 return StmtError();
6892
6893 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6894 // 1.2.2 OpenMP Language Terminology
6895 // Structured block - An executable statement with a single entry at the
6896 // top and a single exit at the bottom.
6897 // The point of exit cannot be a branch out of the structured block.
6898 // longjmp() and throw() must not violate the entry/exit criteria.
6899 CS->getCapturedDecl()->setNothrow();
6900
6901 OMPLoopDirective::HelperExprs B;
6902 // In presence of clause 'collapse' with number of loops, it will
6903 // define the nested loops number.
6904 unsigned NestedLoopCount =
6905 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6906 nullptr /*ordered not a clause on distribute*/, AStmt,
6907 *this, *DSAStack, VarsWithImplicitDSA, B);
6908 if (NestedLoopCount == 0)
6909 return StmtError();
6910
6911 assert((CurContext->isDependentContext() || B.builtAll()) &&
6912 "omp for loop exprs were not built");
6913
Alexey Bataev438388c2017-11-22 18:34:02 +00006914 if (!CurContext->isDependentContext()) {
6915 // Finalize the clauses that need pre-built expressions for CodeGen.
6916 for (auto C : Clauses) {
6917 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6918 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6919 B.NumIterations, *this, CurScope,
6920 DSAStack))
6921 return StmtError();
6922 }
6923 }
6924
Kelvin Lic5609492016-07-15 04:39:07 +00006925 if (checkSimdlenSafelenSpecified(*this, Clauses))
6926 return StmtError();
6927
Kelvin Li787f3fc2016-07-06 04:45:38 +00006928 getCurFunction()->setHasBranchProtectedScope();
6929 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6930 NestedLoopCount, Clauses, AStmt, B);
6931}
6932
Kelvin Lia579b912016-07-14 02:54:56 +00006933StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6934 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6935 SourceLocation EndLoc,
6936 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6937 if (!AStmt)
6938 return StmtError();
6939
6940 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6941 // 1.2.2 OpenMP Language Terminology
6942 // Structured block - An executable statement with a single entry at the
6943 // top and a single exit at the bottom.
6944 // The point of exit cannot be a branch out of the structured block.
6945 // longjmp() and throw() must not violate the entry/exit criteria.
6946 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00006947 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6948 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6949 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6950 // 1.2.2 OpenMP Language Terminology
6951 // Structured block - An executable statement with a single entry at the
6952 // top and a single exit at the bottom.
6953 // The point of exit cannot be a branch out of the structured block.
6954 // longjmp() and throw() must not violate the entry/exit criteria.
6955 CS->getCapturedDecl()->setNothrow();
6956 }
Kelvin Lia579b912016-07-14 02:54:56 +00006957
6958 OMPLoopDirective::HelperExprs B;
6959 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6960 // define the nested loops number.
6961 unsigned NestedLoopCount = CheckOpenMPLoop(
6962 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00006963 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00006964 VarsWithImplicitDSA, B);
6965 if (NestedLoopCount == 0)
6966 return StmtError();
6967
6968 assert((CurContext->isDependentContext() || B.builtAll()) &&
6969 "omp target parallel for simd loop exprs were not built");
6970
6971 if (!CurContext->isDependentContext()) {
6972 // Finalize the clauses that need pre-built expressions for CodeGen.
6973 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006974 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006975 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6976 B.NumIterations, *this, CurScope,
6977 DSAStack))
6978 return StmtError();
6979 }
6980 }
Kelvin Lic5609492016-07-15 04:39:07 +00006981 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006982 return StmtError();
6983
6984 getCurFunction()->setHasBranchProtectedScope();
6985 return OMPTargetParallelForSimdDirective::Create(
6986 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6987}
6988
Kelvin Li986330c2016-07-20 22:57:10 +00006989StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6990 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6991 SourceLocation EndLoc,
6992 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6993 if (!AStmt)
6994 return StmtError();
6995
6996 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6997 // 1.2.2 OpenMP Language Terminology
6998 // Structured block - An executable statement with a single entry at the
6999 // top and a single exit at the bottom.
7000 // The point of exit cannot be a branch out of the structured block.
7001 // longjmp() and throw() must not violate the entry/exit criteria.
7002 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00007003 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7004 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7005 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7006 // 1.2.2 OpenMP Language Terminology
7007 // Structured block - An executable statement with a single entry at the
7008 // top and a single exit at the bottom.
7009 // The point of exit cannot be a branch out of the structured block.
7010 // longjmp() and throw() must not violate the entry/exit criteria.
7011 CS->getCapturedDecl()->setNothrow();
7012 }
7013
Kelvin Li986330c2016-07-20 22:57:10 +00007014 OMPLoopDirective::HelperExprs B;
7015 // In presence of clause 'collapse' with number of loops, it will define the
7016 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00007017 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00007018 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00007019 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00007020 VarsWithImplicitDSA, B);
7021 if (NestedLoopCount == 0)
7022 return StmtError();
7023
7024 assert((CurContext->isDependentContext() || B.builtAll()) &&
7025 "omp target simd loop exprs were not built");
7026
7027 if (!CurContext->isDependentContext()) {
7028 // Finalize the clauses that need pre-built expressions for CodeGen.
7029 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007030 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00007031 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7032 B.NumIterations, *this, CurScope,
7033 DSAStack))
7034 return StmtError();
7035 }
7036 }
7037
7038 if (checkSimdlenSafelenSpecified(*this, Clauses))
7039 return StmtError();
7040
7041 getCurFunction()->setHasBranchProtectedScope();
7042 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7043 NestedLoopCount, Clauses, AStmt, B);
7044}
7045
Kelvin Li02532872016-08-05 14:37:37 +00007046StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7047 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7048 SourceLocation EndLoc,
7049 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7050 if (!AStmt)
7051 return StmtError();
7052
7053 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7054 // 1.2.2 OpenMP Language Terminology
7055 // Structured block - An executable statement with a single entry at the
7056 // top and a single exit at the bottom.
7057 // The point of exit cannot be a branch out of the structured block.
7058 // longjmp() and throw() must not violate the entry/exit criteria.
7059 CS->getCapturedDecl()->setNothrow();
7060
7061 OMPLoopDirective::HelperExprs B;
7062 // In presence of clause 'collapse' with number of loops, it will
7063 // define the nested loops number.
7064 unsigned NestedLoopCount =
7065 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
7066 nullptr /*ordered not a clause on distribute*/, AStmt,
7067 *this, *DSAStack, VarsWithImplicitDSA, B);
7068 if (NestedLoopCount == 0)
7069 return StmtError();
7070
7071 assert((CurContext->isDependentContext() || B.builtAll()) &&
7072 "omp teams distribute loop exprs were not built");
7073
7074 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00007075 return OMPTeamsDistributeDirective::Create(
7076 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00007077}
7078
Kelvin Li4e325f72016-10-25 12:50:55 +00007079StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7080 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7081 SourceLocation EndLoc,
7082 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7083 if (!AStmt)
7084 return StmtError();
7085
7086 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7087 // 1.2.2 OpenMP Language Terminology
7088 // Structured block - An executable statement with a single entry at the
7089 // top and a single exit at the bottom.
7090 // The point of exit cannot be a branch out of the structured block.
7091 // longjmp() and throw() must not violate the entry/exit criteria.
7092 CS->getCapturedDecl()->setNothrow();
7093
7094 OMPLoopDirective::HelperExprs B;
7095 // In presence of clause 'collapse' with number of loops, it will
7096 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00007097 unsigned NestedLoopCount = CheckOpenMPLoop(
7098 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7099 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7100 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00007101
7102 if (NestedLoopCount == 0)
7103 return StmtError();
7104
7105 assert((CurContext->isDependentContext() || B.builtAll()) &&
7106 "omp teams distribute simd loop exprs were not built");
7107
7108 if (!CurContext->isDependentContext()) {
7109 // Finalize the clauses that need pre-built expressions for CodeGen.
7110 for (auto C : Clauses) {
7111 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7112 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7113 B.NumIterations, *this, CurScope,
7114 DSAStack))
7115 return StmtError();
7116 }
7117 }
7118
7119 if (checkSimdlenSafelenSpecified(*this, Clauses))
7120 return StmtError();
7121
7122 getCurFunction()->setHasBranchProtectedScope();
7123 return OMPTeamsDistributeSimdDirective::Create(
7124 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7125}
7126
Kelvin Li579e41c2016-11-30 23:51:03 +00007127StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7128 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7129 SourceLocation EndLoc,
7130 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7131 if (!AStmt)
7132 return StmtError();
7133
7134 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7135 // 1.2.2 OpenMP Language Terminology
7136 // Structured block - An executable statement with a single entry at the
7137 // top and a single exit at the bottom.
7138 // The point of exit cannot be a branch out of the structured block.
7139 // longjmp() and throw() must not violate the entry/exit criteria.
7140 CS->getCapturedDecl()->setNothrow();
7141
7142 OMPLoopDirective::HelperExprs B;
7143 // In presence of clause 'collapse' with number of loops, it will
7144 // define the nested loops number.
7145 auto NestedLoopCount = CheckOpenMPLoop(
7146 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7147 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7148 VarsWithImplicitDSA, B);
7149
7150 if (NestedLoopCount == 0)
7151 return StmtError();
7152
7153 assert((CurContext->isDependentContext() || B.builtAll()) &&
7154 "omp for loop exprs were not built");
7155
7156 if (!CurContext->isDependentContext()) {
7157 // Finalize the clauses that need pre-built expressions for CodeGen.
7158 for (auto C : Clauses) {
7159 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7160 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7161 B.NumIterations, *this, CurScope,
7162 DSAStack))
7163 return StmtError();
7164 }
7165 }
7166
7167 if (checkSimdlenSafelenSpecified(*this, Clauses))
7168 return StmtError();
7169
7170 getCurFunction()->setHasBranchProtectedScope();
7171 return OMPTeamsDistributeParallelForSimdDirective::Create(
7172 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7173}
7174
Kelvin Li7ade93f2016-12-09 03:24:30 +00007175StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7176 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7177 SourceLocation EndLoc,
7178 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7179 if (!AStmt)
7180 return StmtError();
7181
7182 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7183 // 1.2.2 OpenMP Language Terminology
7184 // Structured block - An executable statement with a single entry at the
7185 // top and a single exit at the bottom.
7186 // The point of exit cannot be a branch out of the structured block.
7187 // longjmp() and throw() must not violate the entry/exit criteria.
7188 CS->getCapturedDecl()->setNothrow();
7189
Carlo Bertolli62fae152017-11-20 20:46:39 +00007190 for (int ThisCaptureLevel =
7191 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7192 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7193 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7194 // 1.2.2 OpenMP Language Terminology
7195 // Structured block - An executable statement with a single entry at the
7196 // top and a single exit at the bottom.
7197 // The point of exit cannot be a branch out of the structured block.
7198 // longjmp() and throw() must not violate the entry/exit criteria.
7199 CS->getCapturedDecl()->setNothrow();
7200 }
7201
Kelvin Li7ade93f2016-12-09 03:24:30 +00007202 OMPLoopDirective::HelperExprs B;
7203 // In presence of clause 'collapse' with number of loops, it will
7204 // define the nested loops number.
7205 unsigned NestedLoopCount = CheckOpenMPLoop(
7206 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00007207 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00007208 VarsWithImplicitDSA, B);
7209
7210 if (NestedLoopCount == 0)
7211 return StmtError();
7212
7213 assert((CurContext->isDependentContext() || B.builtAll()) &&
7214 "omp for loop exprs were not built");
7215
7216 if (!CurContext->isDependentContext()) {
7217 // Finalize the clauses that need pre-built expressions for CodeGen.
7218 for (auto C : Clauses) {
7219 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7220 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7221 B.NumIterations, *this, CurScope,
7222 DSAStack))
7223 return StmtError();
7224 }
7225 }
7226
7227 getCurFunction()->setHasBranchProtectedScope();
7228 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007229 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7230 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00007231}
7232
Kelvin Libf594a52016-12-17 05:48:59 +00007233StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7234 Stmt *AStmt,
7235 SourceLocation StartLoc,
7236 SourceLocation EndLoc) {
7237 if (!AStmt)
7238 return StmtError();
7239
7240 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7241 // 1.2.2 OpenMP Language Terminology
7242 // Structured block - An executable statement with a single entry at the
7243 // top and a single exit at the bottom.
7244 // The point of exit cannot be a branch out of the structured block.
7245 // longjmp() and throw() must not violate the entry/exit criteria.
7246 CS->getCapturedDecl()->setNothrow();
7247
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00007248 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7249 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7250 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7251 // 1.2.2 OpenMP Language Terminology
7252 // Structured block - An executable statement with a single entry at the
7253 // top and a single exit at the bottom.
7254 // The point of exit cannot be a branch out of the structured block.
7255 // longjmp() and throw() must not violate the entry/exit criteria.
7256 CS->getCapturedDecl()->setNothrow();
7257 }
Kelvin Libf594a52016-12-17 05:48:59 +00007258 getCurFunction()->setHasBranchProtectedScope();
7259
7260 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7261 AStmt);
7262}
7263
Kelvin Li83c451e2016-12-25 04:52:54 +00007264StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7265 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7266 SourceLocation EndLoc,
7267 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7268 if (!AStmt)
7269 return StmtError();
7270
7271 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7272 // 1.2.2 OpenMP Language Terminology
7273 // Structured block - An executable statement with a single entry at the
7274 // top and a single exit at the bottom.
7275 // The point of exit cannot be a branch out of the structured block.
7276 // longjmp() and throw() must not violate the entry/exit criteria.
7277 CS->getCapturedDecl()->setNothrow();
7278
7279 OMPLoopDirective::HelperExprs B;
7280 // In presence of clause 'collapse' with number of loops, it will
7281 // define the nested loops number.
7282 auto NestedLoopCount = CheckOpenMPLoop(
7283 OMPD_target_teams_distribute,
7284 getCollapseNumberExpr(Clauses),
7285 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7286 VarsWithImplicitDSA, B);
7287 if (NestedLoopCount == 0)
7288 return StmtError();
7289
7290 assert((CurContext->isDependentContext() || B.builtAll()) &&
7291 "omp target teams distribute loop exprs were not built");
7292
7293 getCurFunction()->setHasBranchProtectedScope();
7294 return OMPTargetTeamsDistributeDirective::Create(
7295 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7296}
7297
Kelvin Li80e8f562016-12-29 22:16:30 +00007298StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7299 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7300 SourceLocation EndLoc,
7301 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7302 if (!AStmt)
7303 return StmtError();
7304
7305 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7306 // 1.2.2 OpenMP Language Terminology
7307 // Structured block - An executable statement with a single entry at the
7308 // top and a single exit at the bottom.
7309 // The point of exit cannot be a branch out of the structured block.
7310 // longjmp() and throw() must not violate the entry/exit criteria.
7311 CS->getCapturedDecl()->setNothrow();
7312
7313 OMPLoopDirective::HelperExprs B;
7314 // In presence of clause 'collapse' with number of loops, it will
7315 // define the nested loops number.
7316 auto NestedLoopCount = CheckOpenMPLoop(
7317 OMPD_target_teams_distribute_parallel_for,
7318 getCollapseNumberExpr(Clauses),
7319 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7320 VarsWithImplicitDSA, B);
7321 if (NestedLoopCount == 0)
7322 return StmtError();
7323
7324 assert((CurContext->isDependentContext() || B.builtAll()) &&
7325 "omp target teams distribute parallel for loop exprs were not built");
7326
7327 if (!CurContext->isDependentContext()) {
7328 // Finalize the clauses that need pre-built expressions for CodeGen.
7329 for (auto C : Clauses) {
7330 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7331 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7332 B.NumIterations, *this, CurScope,
7333 DSAStack))
7334 return StmtError();
7335 }
7336 }
7337
7338 getCurFunction()->setHasBranchProtectedScope();
7339 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00007340 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7341 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00007342}
7343
Kelvin Li1851df52017-01-03 05:23:48 +00007344StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7345 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7346 SourceLocation EndLoc,
7347 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7348 if (!AStmt)
7349 return StmtError();
7350
7351 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7352 // 1.2.2 OpenMP Language Terminology
7353 // Structured block - An executable statement with a single entry at the
7354 // top and a single exit at the bottom.
7355 // The point of exit cannot be a branch out of the structured block.
7356 // longjmp() and throw() must not violate the entry/exit criteria.
7357 CS->getCapturedDecl()->setNothrow();
7358
7359 OMPLoopDirective::HelperExprs B;
7360 // In presence of clause 'collapse' with number of loops, it will
7361 // define the nested loops number.
7362 auto NestedLoopCount = CheckOpenMPLoop(
7363 OMPD_target_teams_distribute_parallel_for_simd,
7364 getCollapseNumberExpr(Clauses),
7365 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7366 VarsWithImplicitDSA, B);
7367 if (NestedLoopCount == 0)
7368 return StmtError();
7369
7370 assert((CurContext->isDependentContext() || B.builtAll()) &&
7371 "omp target teams distribute parallel for simd loop exprs were not "
7372 "built");
7373
7374 if (!CurContext->isDependentContext()) {
7375 // Finalize the clauses that need pre-built expressions for CodeGen.
7376 for (auto C : Clauses) {
7377 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7378 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7379 B.NumIterations, *this, CurScope,
7380 DSAStack))
7381 return StmtError();
7382 }
7383 }
7384
Alexey Bataev438388c2017-11-22 18:34:02 +00007385 if (checkSimdlenSafelenSpecified(*this, Clauses))
7386 return StmtError();
7387
Kelvin Li1851df52017-01-03 05:23:48 +00007388 getCurFunction()->setHasBranchProtectedScope();
7389 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7390 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7391}
7392
Kelvin Lida681182017-01-10 18:08:18 +00007393StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7394 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7395 SourceLocation EndLoc,
7396 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7397 if (!AStmt)
7398 return StmtError();
7399
7400 auto *CS = cast<CapturedStmt>(AStmt);
7401 // 1.2.2 OpenMP Language Terminology
7402 // Structured block - An executable statement with a single entry at the
7403 // top and a single exit at the bottom.
7404 // The point of exit cannot be a branch out of the structured block.
7405 // longjmp() and throw() must not violate the entry/exit criteria.
7406 CS->getCapturedDecl()->setNothrow();
7407
7408 OMPLoopDirective::HelperExprs B;
7409 // In presence of clause 'collapse' with number of loops, it will
7410 // define the nested loops number.
7411 auto NestedLoopCount = CheckOpenMPLoop(
7412 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7413 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7414 VarsWithImplicitDSA, B);
7415 if (NestedLoopCount == 0)
7416 return StmtError();
7417
7418 assert((CurContext->isDependentContext() || B.builtAll()) &&
7419 "omp target teams distribute simd loop exprs were not built");
7420
Alexey Bataev438388c2017-11-22 18:34:02 +00007421 if (!CurContext->isDependentContext()) {
7422 // Finalize the clauses that need pre-built expressions for CodeGen.
7423 for (auto C : Clauses) {
7424 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7425 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7426 B.NumIterations, *this, CurScope,
7427 DSAStack))
7428 return StmtError();
7429 }
7430 }
7431
7432 if (checkSimdlenSafelenSpecified(*this, Clauses))
7433 return StmtError();
7434
Kelvin Lida681182017-01-10 18:08:18 +00007435 getCurFunction()->setHasBranchProtectedScope();
7436 return OMPTargetTeamsDistributeSimdDirective::Create(
7437 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7438}
7439
Alexey Bataeved09d242014-05-28 05:53:51 +00007440OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007441 SourceLocation StartLoc,
7442 SourceLocation LParenLoc,
7443 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007444 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007445 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00007446 case OMPC_final:
7447 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7448 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00007449 case OMPC_num_threads:
7450 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7451 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007452 case OMPC_safelen:
7453 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7454 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00007455 case OMPC_simdlen:
7456 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7457 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00007458 case OMPC_collapse:
7459 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7460 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007461 case OMPC_ordered:
7462 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7463 break;
Michael Wonge710d542015-08-07 16:16:36 +00007464 case OMPC_device:
7465 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7466 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007467 case OMPC_num_teams:
7468 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7469 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007470 case OMPC_thread_limit:
7471 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7472 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00007473 case OMPC_priority:
7474 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7475 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007476 case OMPC_grainsize:
7477 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7478 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00007479 case OMPC_num_tasks:
7480 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7481 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00007482 case OMPC_hint:
7483 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7484 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007485 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007486 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007487 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007488 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007489 case OMPC_private:
7490 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007491 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007492 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007493 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007494 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007495 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007496 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007497 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007498 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007499 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00007500 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007501 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007502 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007503 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007504 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007505 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007506 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007507 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007508 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007509 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007510 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00007511 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007512 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007513 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00007514 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007515 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007516 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007517 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007518 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007519 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007520 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007521 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007522 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007523 llvm_unreachable("Clause is not allowed.");
7524 }
7525 return Res;
7526}
7527
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007528// An OpenMP directive such as 'target parallel' has two captured regions:
7529// for the 'target' and 'parallel' respectively. This function returns
7530// the region in which to capture expressions associated with a clause.
7531// A return value of OMPD_unknown signifies that the expression should not
7532// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007533static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7534 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7535 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007536 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007537 switch (CKind) {
7538 case OMPC_if:
7539 switch (DKind) {
7540 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007541 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007542 case OMPD_target_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007543 case OMPD_target_teams_distribute_parallel_for:
7544 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007545 // If this clause applies to the nested 'parallel' region, capture within
7546 // the 'target' region, otherwise do not capture.
7547 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7548 CaptureRegion = OMPD_target;
7549 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007550 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007551 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007552 CaptureRegion = OMPD_teams;
7553 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007554 case OMPD_cancel:
7555 case OMPD_parallel:
7556 case OMPD_parallel_sections:
7557 case OMPD_parallel_for:
7558 case OMPD_parallel_for_simd:
7559 case OMPD_target:
7560 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007561 case OMPD_target_teams:
7562 case OMPD_target_teams_distribute:
7563 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007564 case OMPD_distribute_parallel_for:
7565 case OMPD_distribute_parallel_for_simd:
7566 case OMPD_task:
7567 case OMPD_taskloop:
7568 case OMPD_taskloop_simd:
7569 case OMPD_target_data:
7570 case OMPD_target_enter_data:
7571 case OMPD_target_exit_data:
7572 case OMPD_target_update:
7573 // Do not capture if-clause expressions.
7574 break;
7575 case OMPD_threadprivate:
7576 case OMPD_taskyield:
7577 case OMPD_barrier:
7578 case OMPD_taskwait:
7579 case OMPD_cancellation_point:
7580 case OMPD_flush:
7581 case OMPD_declare_reduction:
7582 case OMPD_declare_simd:
7583 case OMPD_declare_target:
7584 case OMPD_end_declare_target:
7585 case OMPD_teams:
7586 case OMPD_simd:
7587 case OMPD_for:
7588 case OMPD_for_simd:
7589 case OMPD_sections:
7590 case OMPD_section:
7591 case OMPD_single:
7592 case OMPD_master:
7593 case OMPD_critical:
7594 case OMPD_taskgroup:
7595 case OMPD_distribute:
7596 case OMPD_ordered:
7597 case OMPD_atomic:
7598 case OMPD_distribute_simd:
7599 case OMPD_teams_distribute:
7600 case OMPD_teams_distribute_simd:
7601 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7602 case OMPD_unknown:
7603 llvm_unreachable("Unknown OpenMP directive");
7604 }
7605 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007606 case OMPC_num_threads:
7607 switch (DKind) {
7608 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007609 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007610 case OMPD_target_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007611 case OMPD_target_teams_distribute_parallel_for:
7612 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007613 CaptureRegion = OMPD_target;
7614 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007615 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007616 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007617 CaptureRegion = OMPD_teams;
7618 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007619 case OMPD_parallel:
7620 case OMPD_parallel_sections:
7621 case OMPD_parallel_for:
7622 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007623 case OMPD_distribute_parallel_for:
7624 case OMPD_distribute_parallel_for_simd:
7625 // Do not capture num_threads-clause expressions.
7626 break;
7627 case OMPD_target_data:
7628 case OMPD_target_enter_data:
7629 case OMPD_target_exit_data:
7630 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007631 case OMPD_target:
7632 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007633 case OMPD_target_teams:
7634 case OMPD_target_teams_distribute:
7635 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007636 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007637 case OMPD_task:
7638 case OMPD_taskloop:
7639 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007640 case OMPD_threadprivate:
7641 case OMPD_taskyield:
7642 case OMPD_barrier:
7643 case OMPD_taskwait:
7644 case OMPD_cancellation_point:
7645 case OMPD_flush:
7646 case OMPD_declare_reduction:
7647 case OMPD_declare_simd:
7648 case OMPD_declare_target:
7649 case OMPD_end_declare_target:
7650 case OMPD_teams:
7651 case OMPD_simd:
7652 case OMPD_for:
7653 case OMPD_for_simd:
7654 case OMPD_sections:
7655 case OMPD_section:
7656 case OMPD_single:
7657 case OMPD_master:
7658 case OMPD_critical:
7659 case OMPD_taskgroup:
7660 case OMPD_distribute:
7661 case OMPD_ordered:
7662 case OMPD_atomic:
7663 case OMPD_distribute_simd:
7664 case OMPD_teams_distribute:
7665 case OMPD_teams_distribute_simd:
7666 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7667 case OMPD_unknown:
7668 llvm_unreachable("Unknown OpenMP directive");
7669 }
7670 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007671 case OMPC_num_teams:
7672 switch (DKind) {
7673 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007674 case OMPD_target_teams_distribute:
7675 case OMPD_target_teams_distribute_simd:
7676 case OMPD_target_teams_distribute_parallel_for:
7677 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007678 CaptureRegion = OMPD_target;
7679 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007680 case OMPD_teams_distribute_parallel_for:
7681 case OMPD_teams_distribute_parallel_for_simd:
7682 case OMPD_teams:
7683 case OMPD_teams_distribute:
7684 case OMPD_teams_distribute_simd:
7685 // Do not capture num_teams-clause expressions.
7686 break;
7687 case OMPD_distribute_parallel_for:
7688 case OMPD_distribute_parallel_for_simd:
7689 case OMPD_task:
7690 case OMPD_taskloop:
7691 case OMPD_taskloop_simd:
7692 case OMPD_target_data:
7693 case OMPD_target_enter_data:
7694 case OMPD_target_exit_data:
7695 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007696 case OMPD_cancel:
7697 case OMPD_parallel:
7698 case OMPD_parallel_sections:
7699 case OMPD_parallel_for:
7700 case OMPD_parallel_for_simd:
7701 case OMPD_target:
7702 case OMPD_target_simd:
7703 case OMPD_target_parallel:
7704 case OMPD_target_parallel_for:
7705 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007706 case OMPD_threadprivate:
7707 case OMPD_taskyield:
7708 case OMPD_barrier:
7709 case OMPD_taskwait:
7710 case OMPD_cancellation_point:
7711 case OMPD_flush:
7712 case OMPD_declare_reduction:
7713 case OMPD_declare_simd:
7714 case OMPD_declare_target:
7715 case OMPD_end_declare_target:
7716 case OMPD_simd:
7717 case OMPD_for:
7718 case OMPD_for_simd:
7719 case OMPD_sections:
7720 case OMPD_section:
7721 case OMPD_single:
7722 case OMPD_master:
7723 case OMPD_critical:
7724 case OMPD_taskgroup:
7725 case OMPD_distribute:
7726 case OMPD_ordered:
7727 case OMPD_atomic:
7728 case OMPD_distribute_simd:
7729 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7730 case OMPD_unknown:
7731 llvm_unreachable("Unknown OpenMP directive");
7732 }
7733 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007734 case OMPC_thread_limit:
7735 switch (DKind) {
7736 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007737 case OMPD_target_teams_distribute:
7738 case OMPD_target_teams_distribute_simd:
7739 case OMPD_target_teams_distribute_parallel_for:
7740 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007741 CaptureRegion = OMPD_target;
7742 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007743 case OMPD_teams_distribute_parallel_for:
7744 case OMPD_teams_distribute_parallel_for_simd:
7745 case OMPD_teams:
7746 case OMPD_teams_distribute:
7747 case OMPD_teams_distribute_simd:
7748 // Do not capture thread_limit-clause expressions.
7749 break;
7750 case OMPD_distribute_parallel_for:
7751 case OMPD_distribute_parallel_for_simd:
7752 case OMPD_task:
7753 case OMPD_taskloop:
7754 case OMPD_taskloop_simd:
7755 case OMPD_target_data:
7756 case OMPD_target_enter_data:
7757 case OMPD_target_exit_data:
7758 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007759 case OMPD_cancel:
7760 case OMPD_parallel:
7761 case OMPD_parallel_sections:
7762 case OMPD_parallel_for:
7763 case OMPD_parallel_for_simd:
7764 case OMPD_target:
7765 case OMPD_target_simd:
7766 case OMPD_target_parallel:
7767 case OMPD_target_parallel_for:
7768 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007769 case OMPD_threadprivate:
7770 case OMPD_taskyield:
7771 case OMPD_barrier:
7772 case OMPD_taskwait:
7773 case OMPD_cancellation_point:
7774 case OMPD_flush:
7775 case OMPD_declare_reduction:
7776 case OMPD_declare_simd:
7777 case OMPD_declare_target:
7778 case OMPD_end_declare_target:
7779 case OMPD_simd:
7780 case OMPD_for:
7781 case OMPD_for_simd:
7782 case OMPD_sections:
7783 case OMPD_section:
7784 case OMPD_single:
7785 case OMPD_master:
7786 case OMPD_critical:
7787 case OMPD_taskgroup:
7788 case OMPD_distribute:
7789 case OMPD_ordered:
7790 case OMPD_atomic:
7791 case OMPD_distribute_simd:
7792 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7793 case OMPD_unknown:
7794 llvm_unreachable("Unknown OpenMP directive");
7795 }
7796 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007797 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007798 switch (DKind) {
7799 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007800 case OMPD_target_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007801 case OMPD_target_teams_distribute_parallel_for:
7802 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007803 CaptureRegion = OMPD_target;
7804 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007805 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007806 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007807 CaptureRegion = OMPD_teams;
7808 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007809 case OMPD_parallel_for:
7810 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00007811 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00007812 case OMPD_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00007813 CaptureRegion = OMPD_parallel;
7814 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007815 case OMPD_for:
7816 case OMPD_for_simd:
7817 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007818 break;
7819 case OMPD_task:
7820 case OMPD_taskloop:
7821 case OMPD_taskloop_simd:
7822 case OMPD_target_data:
7823 case OMPD_target_enter_data:
7824 case OMPD_target_exit_data:
7825 case OMPD_target_update:
7826 case OMPD_teams:
7827 case OMPD_teams_distribute:
7828 case OMPD_teams_distribute_simd:
7829 case OMPD_target_teams_distribute:
7830 case OMPD_target_teams_distribute_simd:
7831 case OMPD_target:
7832 case OMPD_target_simd:
7833 case OMPD_target_parallel:
7834 case OMPD_cancel:
7835 case OMPD_parallel:
7836 case OMPD_parallel_sections:
7837 case OMPD_threadprivate:
7838 case OMPD_taskyield:
7839 case OMPD_barrier:
7840 case OMPD_taskwait:
7841 case OMPD_cancellation_point:
7842 case OMPD_flush:
7843 case OMPD_declare_reduction:
7844 case OMPD_declare_simd:
7845 case OMPD_declare_target:
7846 case OMPD_end_declare_target:
7847 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007848 case OMPD_sections:
7849 case OMPD_section:
7850 case OMPD_single:
7851 case OMPD_master:
7852 case OMPD_critical:
7853 case OMPD_taskgroup:
7854 case OMPD_distribute:
7855 case OMPD_ordered:
7856 case OMPD_atomic:
7857 case OMPD_distribute_simd:
7858 case OMPD_target_teams:
7859 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
7860 case OMPD_unknown:
7861 llvm_unreachable("Unknown OpenMP directive");
7862 }
7863 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007864 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007865 switch (DKind) {
7866 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007867 case OMPD_teams_distribute_parallel_for_simd:
7868 case OMPD_teams_distribute:
7869 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007870 CaptureRegion = OMPD_teams;
7871 break;
7872 case OMPD_target_teams_distribute_parallel_for:
7873 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007874 case OMPD_target_teams_distribute:
7875 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007876 CaptureRegion = OMPD_target;
7877 break;
7878 case OMPD_distribute_parallel_for:
7879 case OMPD_distribute_parallel_for_simd:
7880 CaptureRegion = OMPD_parallel;
7881 break;
7882 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007883 case OMPD_distribute_simd:
7884 // Do not capture thread_limit-clause expressions.
7885 break;
7886 case OMPD_parallel_for:
7887 case OMPD_parallel_for_simd:
7888 case OMPD_target_parallel_for_simd:
7889 case OMPD_target_parallel_for:
7890 case OMPD_task:
7891 case OMPD_taskloop:
7892 case OMPD_taskloop_simd:
7893 case OMPD_target_data:
7894 case OMPD_target_enter_data:
7895 case OMPD_target_exit_data:
7896 case OMPD_target_update:
7897 case OMPD_teams:
7898 case OMPD_target:
7899 case OMPD_target_simd:
7900 case OMPD_target_parallel:
7901 case OMPD_cancel:
7902 case OMPD_parallel:
7903 case OMPD_parallel_sections:
7904 case OMPD_threadprivate:
7905 case OMPD_taskyield:
7906 case OMPD_barrier:
7907 case OMPD_taskwait:
7908 case OMPD_cancellation_point:
7909 case OMPD_flush:
7910 case OMPD_declare_reduction:
7911 case OMPD_declare_simd:
7912 case OMPD_declare_target:
7913 case OMPD_end_declare_target:
7914 case OMPD_simd:
7915 case OMPD_for:
7916 case OMPD_for_simd:
7917 case OMPD_sections:
7918 case OMPD_section:
7919 case OMPD_single:
7920 case OMPD_master:
7921 case OMPD_critical:
7922 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007923 case OMPD_ordered:
7924 case OMPD_atomic:
7925 case OMPD_target_teams:
7926 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
7927 case OMPD_unknown:
7928 llvm_unreachable("Unknown OpenMP directive");
7929 }
7930 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007931 case OMPC_device:
7932 switch (DKind) {
7933 case OMPD_target_teams:
7934 case OMPD_target_teams_distribute:
7935 case OMPD_target_teams_distribute_simd:
7936 case OMPD_target_teams_distribute_parallel_for:
7937 case OMPD_target_teams_distribute_parallel_for_simd:
7938 case OMPD_target_data:
7939 case OMPD_target_enter_data:
7940 case OMPD_target_exit_data:
7941 case OMPD_target_update:
7942 case OMPD_target:
7943 case OMPD_target_simd:
7944 case OMPD_target_parallel:
7945 case OMPD_target_parallel_for:
7946 case OMPD_target_parallel_for_simd:
7947 // Do not capture device-clause expressions.
7948 break;
7949 case OMPD_teams_distribute_parallel_for:
7950 case OMPD_teams_distribute_parallel_for_simd:
7951 case OMPD_teams:
7952 case OMPD_teams_distribute:
7953 case OMPD_teams_distribute_simd:
7954 case OMPD_distribute_parallel_for:
7955 case OMPD_distribute_parallel_for_simd:
7956 case OMPD_task:
7957 case OMPD_taskloop:
7958 case OMPD_taskloop_simd:
7959 case OMPD_cancel:
7960 case OMPD_parallel:
7961 case OMPD_parallel_sections:
7962 case OMPD_parallel_for:
7963 case OMPD_parallel_for_simd:
7964 case OMPD_threadprivate:
7965 case OMPD_taskyield:
7966 case OMPD_barrier:
7967 case OMPD_taskwait:
7968 case OMPD_cancellation_point:
7969 case OMPD_flush:
7970 case OMPD_declare_reduction:
7971 case OMPD_declare_simd:
7972 case OMPD_declare_target:
7973 case OMPD_end_declare_target:
7974 case OMPD_simd:
7975 case OMPD_for:
7976 case OMPD_for_simd:
7977 case OMPD_sections:
7978 case OMPD_section:
7979 case OMPD_single:
7980 case OMPD_master:
7981 case OMPD_critical:
7982 case OMPD_taskgroup:
7983 case OMPD_distribute:
7984 case OMPD_ordered:
7985 case OMPD_atomic:
7986 case OMPD_distribute_simd:
7987 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7988 case OMPD_unknown:
7989 llvm_unreachable("Unknown OpenMP directive");
7990 }
7991 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007992 case OMPC_firstprivate:
7993 case OMPC_lastprivate:
7994 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007995 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007996 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007997 case OMPC_linear:
7998 case OMPC_default:
7999 case OMPC_proc_bind:
8000 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008001 case OMPC_safelen:
8002 case OMPC_simdlen:
8003 case OMPC_collapse:
8004 case OMPC_private:
8005 case OMPC_shared:
8006 case OMPC_aligned:
8007 case OMPC_copyin:
8008 case OMPC_copyprivate:
8009 case OMPC_ordered:
8010 case OMPC_nowait:
8011 case OMPC_untied:
8012 case OMPC_mergeable:
8013 case OMPC_threadprivate:
8014 case OMPC_flush:
8015 case OMPC_read:
8016 case OMPC_write:
8017 case OMPC_update:
8018 case OMPC_capture:
8019 case OMPC_seq_cst:
8020 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008021 case OMPC_threads:
8022 case OMPC_simd:
8023 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008024 case OMPC_priority:
8025 case OMPC_grainsize:
8026 case OMPC_nogroup:
8027 case OMPC_num_tasks:
8028 case OMPC_hint:
8029 case OMPC_defaultmap:
8030 case OMPC_unknown:
8031 case OMPC_uniform:
8032 case OMPC_to:
8033 case OMPC_from:
8034 case OMPC_use_device_ptr:
8035 case OMPC_is_device_ptr:
8036 llvm_unreachable("Unexpected OpenMP clause.");
8037 }
8038 return CaptureRegion;
8039}
8040
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008041OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8042 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008043 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008044 SourceLocation NameModifierLoc,
8045 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008046 SourceLocation EndLoc) {
8047 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008048 Stmt *HelperValStmt = nullptr;
8049 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008050 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8051 !Condition->isInstantiationDependent() &&
8052 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008053 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008054 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008055 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008056
Richard Smith03a4aa32016-06-23 19:02:52 +00008057 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008058
8059 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8060 CaptureRegion =
8061 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00008062 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008063 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8064 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8065 HelperValStmt = buildPreInits(Context, Captures);
8066 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008067 }
8068
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008069 return new (Context)
8070 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8071 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008072}
8073
Alexey Bataev3778b602014-07-17 07:32:53 +00008074OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8075 SourceLocation StartLoc,
8076 SourceLocation LParenLoc,
8077 SourceLocation EndLoc) {
8078 Expr *ValExpr = Condition;
8079 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8080 !Condition->isInstantiationDependent() &&
8081 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008082 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00008083 if (Val.isInvalid())
8084 return nullptr;
8085
Richard Smith03a4aa32016-06-23 19:02:52 +00008086 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00008087 }
8088
8089 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8090}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008091ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8092 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00008093 if (!Op)
8094 return ExprError();
8095
8096 class IntConvertDiagnoser : public ICEConvertDiagnoser {
8097 public:
8098 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00008099 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00008100 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8101 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008102 return S.Diag(Loc, diag::err_omp_not_integral) << T;
8103 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008104 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8105 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008106 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8107 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008108 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8109 QualType T,
8110 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008111 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8112 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008113 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8114 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008115 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008116 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008117 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008118 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8119 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008120 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8121 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008122 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8123 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008124 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008125 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008126 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008127 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8128 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008129 llvm_unreachable("conversion functions are permitted");
8130 }
8131 } ConvertDiagnoser;
8132 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8133}
8134
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008135static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00008136 OpenMPClauseKind CKind,
8137 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008138 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8139 !ValExpr->isInstantiationDependent()) {
8140 SourceLocation Loc = ValExpr->getExprLoc();
8141 ExprResult Value =
8142 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8143 if (Value.isInvalid())
8144 return false;
8145
8146 ValExpr = Value.get();
8147 // The expression must evaluate to a non-negative integer value.
8148 llvm::APSInt Result;
8149 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00008150 Result.isSigned() &&
8151 !((!StrictlyPositive && Result.isNonNegative()) ||
8152 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008153 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008154 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8155 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008156 return false;
8157 }
8158 }
8159 return true;
8160}
8161
Alexey Bataev568a8332014-03-06 06:15:19 +00008162OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8163 SourceLocation StartLoc,
8164 SourceLocation LParenLoc,
8165 SourceLocation EndLoc) {
8166 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008167 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008168
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008169 // OpenMP [2.5, Restrictions]
8170 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00008171 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
8172 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008173 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008174
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008175 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00008176 OpenMPDirectiveKind CaptureRegion =
8177 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8178 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008179 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8180 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8181 HelperValStmt = buildPreInits(Context, Captures);
8182 }
8183
8184 return new (Context) OMPNumThreadsClause(
8185 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00008186}
8187
Alexey Bataev62c87d22014-03-21 04:51:18 +00008188ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008189 OpenMPClauseKind CKind,
8190 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008191 if (!E)
8192 return ExprError();
8193 if (E->isValueDependent() || E->isTypeDependent() ||
8194 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008195 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008196 llvm::APSInt Result;
8197 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8198 if (ICE.isInvalid())
8199 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008200 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8201 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008202 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008203 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8204 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00008205 return ExprError();
8206 }
Alexander Musman09184fe2014-09-30 05:29:28 +00008207 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8208 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8209 << E->getSourceRange();
8210 return ExprError();
8211 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008212 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8213 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00008214 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008215 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00008216 return ICE;
8217}
8218
8219OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8220 SourceLocation LParenLoc,
8221 SourceLocation EndLoc) {
8222 // OpenMP [2.8.1, simd construct, Description]
8223 // The parameter of the safelen clause must be a constant
8224 // positive integer expression.
8225 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8226 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008227 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008228 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008229 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00008230}
8231
Alexey Bataev66b15b52015-08-21 11:14:16 +00008232OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8233 SourceLocation LParenLoc,
8234 SourceLocation EndLoc) {
8235 // OpenMP [2.8.1, simd construct, Description]
8236 // The parameter of the simdlen clause must be a constant
8237 // positive integer expression.
8238 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8239 if (Simdlen.isInvalid())
8240 return nullptr;
8241 return new (Context)
8242 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8243}
8244
Alexander Musman64d33f12014-06-04 07:53:32 +00008245OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8246 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00008247 SourceLocation LParenLoc,
8248 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00008249 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008250 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00008251 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008252 // The parameter of the collapse clause must be a constant
8253 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00008254 ExprResult NumForLoopsResult =
8255 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8256 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00008257 return nullptr;
8258 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00008259 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00008260}
8261
Alexey Bataev10e775f2015-07-30 11:36:16 +00008262OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8263 SourceLocation EndLoc,
8264 SourceLocation LParenLoc,
8265 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00008266 // OpenMP [2.7.1, loop construct, Description]
8267 // OpenMP [2.8.1, simd construct, Description]
8268 // OpenMP [2.9.6, distribute construct, Description]
8269 // The parameter of the ordered clause must be a constant
8270 // positive integer expression if any.
8271 if (NumForLoops && LParenLoc.isValid()) {
8272 ExprResult NumForLoopsResult =
8273 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8274 if (NumForLoopsResult.isInvalid())
8275 return nullptr;
8276 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00008277 } else
8278 NumForLoops = nullptr;
8279 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00008280 return new (Context)
8281 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
8282}
8283
Alexey Bataeved09d242014-05-28 05:53:51 +00008284OMPClause *Sema::ActOnOpenMPSimpleClause(
8285 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8286 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008287 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008288 switch (Kind) {
8289 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008290 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00008291 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
8292 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008293 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008294 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00008295 Res = ActOnOpenMPProcBindClause(
8296 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
8297 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008298 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008299 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008300 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008301 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008302 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008303 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008304 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008305 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008306 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008307 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008308 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008309 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008310 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008311 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008312 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008313 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008314 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008315 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008316 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008317 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008318 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008319 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008320 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008321 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008322 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008323 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008324 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008325 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008326 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008327 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008328 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008329 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008330 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008331 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008332 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008333 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008334 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008335 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008336 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008337 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008338 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008339 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008340 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008341 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008342 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008343 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008344 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008345 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008346 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008347 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008348 llvm_unreachable("Clause is not allowed.");
8349 }
8350 return Res;
8351}
8352
Alexey Bataev6402bca2015-12-28 07:25:51 +00008353static std::string
8354getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
8355 ArrayRef<unsigned> Exclude = llvm::None) {
8356 std::string Values;
8357 unsigned Bound = Last >= 2 ? Last - 2 : 0;
8358 unsigned Skipped = Exclude.size();
8359 auto S = Exclude.begin(), E = Exclude.end();
8360 for (unsigned i = First; i < Last; ++i) {
8361 if (std::find(S, E, i) != E) {
8362 --Skipped;
8363 continue;
8364 }
8365 Values += "'";
8366 Values += getOpenMPSimpleClauseTypeName(K, i);
8367 Values += "'";
8368 if (i == Bound - Skipped)
8369 Values += " or ";
8370 else if (i != Bound + 1 - Skipped)
8371 Values += ", ";
8372 }
8373 return Values;
8374}
8375
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008376OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8377 SourceLocation KindKwLoc,
8378 SourceLocation StartLoc,
8379 SourceLocation LParenLoc,
8380 SourceLocation EndLoc) {
8381 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00008382 static_assert(OMPC_DEFAULT_unknown > 0,
8383 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008384 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008385 << getListOfPossibleValues(OMPC_default, /*First=*/0,
8386 /*Last=*/OMPC_DEFAULT_unknown)
8387 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008388 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008389 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00008390 switch (Kind) {
8391 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008392 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008393 break;
8394 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008395 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008396 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008397 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008398 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00008399 break;
8400 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008401 return new (Context)
8402 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008403}
8404
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008405OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8406 SourceLocation KindKwLoc,
8407 SourceLocation StartLoc,
8408 SourceLocation LParenLoc,
8409 SourceLocation EndLoc) {
8410 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008411 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008412 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
8413 /*Last=*/OMPC_PROC_BIND_unknown)
8414 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008415 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008416 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008417 return new (Context)
8418 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008419}
8420
Alexey Bataev56dafe82014-06-20 07:16:17 +00008421OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008422 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008423 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008424 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008425 SourceLocation EndLoc) {
8426 OMPClause *Res = nullptr;
8427 switch (Kind) {
8428 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008429 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
8430 assert(Argument.size() == NumberOfElements &&
8431 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008432 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008433 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
8434 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
8435 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
8436 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
8437 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008438 break;
8439 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008440 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
8441 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
8442 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
8443 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008444 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00008445 case OMPC_dist_schedule:
8446 Res = ActOnOpenMPDistScheduleClause(
8447 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
8448 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
8449 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008450 case OMPC_defaultmap:
8451 enum { Modifier, DefaultmapKind };
8452 Res = ActOnOpenMPDefaultmapClause(
8453 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8454 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00008455 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8456 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008457 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00008458 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008459 case OMPC_num_threads:
8460 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008461 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008462 case OMPC_collapse:
8463 case OMPC_default:
8464 case OMPC_proc_bind:
8465 case OMPC_private:
8466 case OMPC_firstprivate:
8467 case OMPC_lastprivate:
8468 case OMPC_shared:
8469 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008470 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008471 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008472 case OMPC_linear:
8473 case OMPC_aligned:
8474 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008475 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008476 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008477 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008478 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008479 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008480 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008481 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008482 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008483 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008484 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008485 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008486 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008487 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008488 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008489 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008490 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008491 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008492 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008493 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008494 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008495 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008496 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008497 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008498 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008499 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008500 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008501 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008502 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008503 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008504 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008505 llvm_unreachable("Clause is not allowed.");
8506 }
8507 return Res;
8508}
8509
Alexey Bataev6402bca2015-12-28 07:25:51 +00008510static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8511 OpenMPScheduleClauseModifier M2,
8512 SourceLocation M1Loc, SourceLocation M2Loc) {
8513 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8514 SmallVector<unsigned, 2> Excluded;
8515 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8516 Excluded.push_back(M2);
8517 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8518 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8519 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8520 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8521 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8522 << getListOfPossibleValues(OMPC_schedule,
8523 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8524 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8525 Excluded)
8526 << getOpenMPClauseName(OMPC_schedule);
8527 return true;
8528 }
8529 return false;
8530}
8531
Alexey Bataev56dafe82014-06-20 07:16:17 +00008532OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008533 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008534 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008535 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8536 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8537 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8538 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8539 return nullptr;
8540 // OpenMP, 2.7.1, Loop Construct, Restrictions
8541 // Either the monotonic modifier or the nonmonotonic modifier can be specified
8542 // but not both.
8543 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8544 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8545 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8546 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8547 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8548 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8549 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8550 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8551 return nullptr;
8552 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008553 if (Kind == OMPC_SCHEDULE_unknown) {
8554 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00008555 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8556 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8557 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8558 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8559 Exclude);
8560 } else {
8561 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8562 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008563 }
8564 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8565 << Values << getOpenMPClauseName(OMPC_schedule);
8566 return nullptr;
8567 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00008568 // OpenMP, 2.7.1, Loop Construct, Restrictions
8569 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8570 // schedule(guided).
8571 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8572 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8573 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8574 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8575 diag::err_omp_schedule_nonmonotonic_static);
8576 return nullptr;
8577 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008578 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00008579 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00008580 if (ChunkSize) {
8581 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8582 !ChunkSize->isInstantiationDependent() &&
8583 !ChunkSize->containsUnexpandedParameterPack()) {
8584 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8585 ExprResult Val =
8586 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8587 if (Val.isInvalid())
8588 return nullptr;
8589
8590 ValExpr = Val.get();
8591
8592 // OpenMP [2.7.1, Restrictions]
8593 // chunk_size must be a loop invariant integer expression with a positive
8594 // value.
8595 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00008596 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8597 if (Result.isSigned() && !Result.isStrictlyPositive()) {
8598 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008599 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00008600 return nullptr;
8601 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00008602 } else if (getOpenMPCaptureRegionForClause(
8603 DSAStack->getCurrentDirective(), OMPC_schedule) !=
8604 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00008605 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00008606 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8607 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8608 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008609 }
8610 }
8611 }
8612
Alexey Bataev6402bca2015-12-28 07:25:51 +00008613 return new (Context)
8614 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00008615 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008616}
8617
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008618OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8619 SourceLocation StartLoc,
8620 SourceLocation EndLoc) {
8621 OMPClause *Res = nullptr;
8622 switch (Kind) {
8623 case OMPC_ordered:
8624 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8625 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00008626 case OMPC_nowait:
8627 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8628 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008629 case OMPC_untied:
8630 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8631 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008632 case OMPC_mergeable:
8633 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8634 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008635 case OMPC_read:
8636 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8637 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00008638 case OMPC_write:
8639 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8640 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008641 case OMPC_update:
8642 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8643 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00008644 case OMPC_capture:
8645 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8646 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008647 case OMPC_seq_cst:
8648 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8649 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00008650 case OMPC_threads:
8651 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8652 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008653 case OMPC_simd:
8654 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8655 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00008656 case OMPC_nogroup:
8657 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8658 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008659 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008660 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008661 case OMPC_num_threads:
8662 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008663 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008664 case OMPC_collapse:
8665 case OMPC_schedule:
8666 case OMPC_private:
8667 case OMPC_firstprivate:
8668 case OMPC_lastprivate:
8669 case OMPC_shared:
8670 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008671 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008672 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008673 case OMPC_linear:
8674 case OMPC_aligned:
8675 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008676 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008677 case OMPC_default:
8678 case OMPC_proc_bind:
8679 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008680 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008681 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008682 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008683 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008684 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008685 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008686 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008687 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00008688 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008689 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008690 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008691 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008692 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008693 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008694 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008695 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008696 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008697 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008698 llvm_unreachable("Clause is not allowed.");
8699 }
8700 return Res;
8701}
8702
Alexey Bataev236070f2014-06-20 11:19:47 +00008703OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8704 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008705 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00008706 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8707}
8708
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008709OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8710 SourceLocation EndLoc) {
8711 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8712}
8713
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008714OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8715 SourceLocation EndLoc) {
8716 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
8717}
8718
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008719OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
8720 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008721 return new (Context) OMPReadClause(StartLoc, EndLoc);
8722}
8723
Alexey Bataevdea47612014-07-23 07:46:59 +00008724OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
8725 SourceLocation EndLoc) {
8726 return new (Context) OMPWriteClause(StartLoc, EndLoc);
8727}
8728
Alexey Bataev67a4f222014-07-23 10:25:33 +00008729OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8730 SourceLocation EndLoc) {
8731 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
8732}
8733
Alexey Bataev459dec02014-07-24 06:46:57 +00008734OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8735 SourceLocation EndLoc) {
8736 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
8737}
8738
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008739OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8740 SourceLocation EndLoc) {
8741 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
8742}
8743
Alexey Bataev346265e2015-09-25 10:37:12 +00008744OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8745 SourceLocation EndLoc) {
8746 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
8747}
8748
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008749OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8750 SourceLocation EndLoc) {
8751 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
8752}
8753
Alexey Bataevb825de12015-12-07 10:51:44 +00008754OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8755 SourceLocation EndLoc) {
8756 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
8757}
8758
Alexey Bataevc5e02582014-06-16 07:08:35 +00008759OMPClause *Sema::ActOnOpenMPVarListClause(
8760 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
8761 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
8762 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008763 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00008764 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8765 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8766 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008767 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008768 switch (Kind) {
8769 case OMPC_private:
8770 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8771 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008772 case OMPC_firstprivate:
8773 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8774 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008775 case OMPC_lastprivate:
8776 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8777 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008778 case OMPC_shared:
8779 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
8780 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008781 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00008782 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8783 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008784 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00008785 case OMPC_task_reduction:
8786 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8787 EndLoc, ReductionIdScopeSpec,
8788 ReductionId);
8789 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00008790 case OMPC_in_reduction:
8791 Res =
8792 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8793 EndLoc, ReductionIdScopeSpec, ReductionId);
8794 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00008795 case OMPC_linear:
8796 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008797 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00008798 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008799 case OMPC_aligned:
8800 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
8801 ColonLoc, EndLoc);
8802 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008803 case OMPC_copyin:
8804 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
8805 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008806 case OMPC_copyprivate:
8807 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8808 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00008809 case OMPC_flush:
8810 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
8811 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008812 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00008813 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008814 StartLoc, LParenLoc, EndLoc);
8815 break;
8816 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00008817 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
8818 DepLinMapLoc, ColonLoc, VarList, StartLoc,
8819 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008820 break;
Samuel Antao661c0902016-05-26 17:39:58 +00008821 case OMPC_to:
8822 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
8823 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00008824 case OMPC_from:
8825 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
8826 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00008827 case OMPC_use_device_ptr:
8828 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8829 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00008830 case OMPC_is_device_ptr:
8831 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8832 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008833 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008834 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008835 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008836 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008837 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008838 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008839 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008840 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008841 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008842 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008843 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008844 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008845 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008846 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008847 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008848 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008849 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008850 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008851 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00008852 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008853 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008854 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008855 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008856 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008857 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008858 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008859 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008860 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008861 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008862 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008863 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008864 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008865 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008866 llvm_unreachable("Clause is not allowed.");
8867 }
8868 return Res;
8869}
8870
Alexey Bataev90c228f2016-02-08 09:29:13 +00008871ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00008872 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00008873 ExprResult Res = BuildDeclRefExpr(
8874 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
8875 if (!Res.isUsable())
8876 return ExprError();
8877 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
8878 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
8879 if (!Res.isUsable())
8880 return ExprError();
8881 }
8882 if (VK != VK_LValue && Res.get()->isGLValue()) {
8883 Res = DefaultLvalueConversion(Res.get());
8884 if (!Res.isUsable())
8885 return ExprError();
8886 }
8887 return Res;
8888}
8889
Alexey Bataev60da77e2016-02-29 05:54:20 +00008890static std::pair<ValueDecl *, bool>
8891getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
8892 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008893 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
8894 RefExpr->containsUnexpandedParameterPack())
8895 return std::make_pair(nullptr, true);
8896
Alexey Bataevd985eda2016-02-10 11:29:16 +00008897 // OpenMP [3.1, C/C++]
8898 // A list item is a variable name.
8899 // OpenMP [2.9.3.3, Restrictions, p.1]
8900 // A variable that is part of another variable (as an array or
8901 // structure element) cannot appear in a private clause.
8902 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008903 enum {
8904 NoArrayExpr = -1,
8905 ArraySubscript = 0,
8906 OMPArraySection = 1
8907 } IsArrayExpr = NoArrayExpr;
8908 if (AllowArraySection) {
8909 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
8910 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
8911 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8912 Base = TempASE->getBase()->IgnoreParenImpCasts();
8913 RefExpr = Base;
8914 IsArrayExpr = ArraySubscript;
8915 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8916 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8917 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8918 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8919 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8920 Base = TempASE->getBase()->IgnoreParenImpCasts();
8921 RefExpr = Base;
8922 IsArrayExpr = OMPArraySection;
8923 }
8924 }
8925 ELoc = RefExpr->getExprLoc();
8926 ERange = RefExpr->getSourceRange();
8927 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008928 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8929 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8930 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8931 (S.getCurrentThisType().isNull() || !ME ||
8932 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8933 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008934 if (IsArrayExpr != NoArrayExpr)
8935 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8936 << ERange;
8937 else {
8938 S.Diag(ELoc,
8939 AllowArraySection
8940 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8941 : diag::err_omp_expected_var_name_member_expr)
8942 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8943 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008944 return std::make_pair(nullptr, false);
8945 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00008946 return std::make_pair(
8947 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008948}
8949
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008950OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8951 SourceLocation StartLoc,
8952 SourceLocation LParenLoc,
8953 SourceLocation EndLoc) {
8954 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00008955 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00008956 for (auto &RefExpr : VarList) {
8957 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008958 SourceLocation ELoc;
8959 SourceRange ERange;
8960 Expr *SimpleRefExpr = RefExpr;
8961 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008962 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008963 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008964 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008965 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008966 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008967 ValueDecl *D = Res.first;
8968 if (!D)
8969 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008970
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008971 QualType Type = D->getType();
8972 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008973
8974 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8975 // A variable that appears in a private clause must not have an incomplete
8976 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008977 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008978 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008979 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008980
Alexey Bataev758e55e2013-09-06 18:03:48 +00008981 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8982 // in a Construct]
8983 // Variables with the predetermined data-sharing attributes may not be
8984 // listed in data-sharing attributes clauses, except for the cases
8985 // listed below. For these exceptions only, listing a predetermined
8986 // variable in a data-sharing attribute clause is allowed and overrides
8987 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008988 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008989 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00008990 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8991 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008992 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008993 continue;
8994 }
8995
Kelvin Libf594a52016-12-17 05:48:59 +00008996 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008997 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008998 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00008999 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009000 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9001 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00009002 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009003 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009004 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009005 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009006 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009007 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009008 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009009 continue;
9010 }
9011
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009012 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9013 // A list item cannot appear in both a map clause and a data-sharing
9014 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00009015 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00009016 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00009017 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00009018 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00009019 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00009020 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00009021 CurrDir == OMPD_target_parallel_for_simd ||
9022 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00009023 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009024 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009025 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009026 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9027 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9028 ConflictKind = WhereFoundClauseKind;
9029 return true;
9030 })) {
9031 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009032 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00009033 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00009034 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009035 ReportOriginalDSA(*this, DSAStack, D, DVar);
9036 continue;
9037 }
9038 }
9039
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009040 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9041 // A variable of class type (or array thereof) that appears in a private
9042 // clause requires an accessible, unambiguous default constructor for the
9043 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00009044 // Generate helper private variable and initialize it with the default
9045 // value. The address of the original variable is replaced by the address of
9046 // the new private variable in CodeGen. This new variable is not added to
9047 // IdResolver, so the code in the OpenMP region uses original variable for
9048 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009049 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009050 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9051 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00009052 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009053 if (VDPrivate->isInvalidDecl())
9054 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009055 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009056 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009057
Alexey Bataev90c228f2016-02-08 09:29:13 +00009058 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009059 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009060 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00009061 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009062 Vars.push_back((VD || CurContext->isDependentContext())
9063 ? RefExpr->IgnoreParens()
9064 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009065 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009066 }
9067
Alexey Bataeved09d242014-05-28 05:53:51 +00009068 if (Vars.empty())
9069 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009070
Alexey Bataev03b340a2014-10-21 03:16:40 +00009071 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9072 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009073}
9074
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009075namespace {
9076class DiagsUninitializedSeveretyRAII {
9077private:
9078 DiagnosticsEngine &Diags;
9079 SourceLocation SavedLoc;
9080 bool IsIgnored;
9081
9082public:
9083 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9084 bool IsIgnored)
9085 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9086 if (!IsIgnored) {
9087 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9088 /*Map*/ diag::Severity::Ignored, Loc);
9089 }
9090 }
9091 ~DiagsUninitializedSeveretyRAII() {
9092 if (!IsIgnored)
9093 Diags.popMappings(SavedLoc);
9094 }
9095};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009096}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009097
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009098OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9099 SourceLocation StartLoc,
9100 SourceLocation LParenLoc,
9101 SourceLocation EndLoc) {
9102 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009103 SmallVector<Expr *, 8> PrivateCopies;
9104 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00009105 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009106 bool IsImplicitClause =
9107 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
9108 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
9109
Alexey Bataeved09d242014-05-28 05:53:51 +00009110 for (auto &RefExpr : VarList) {
9111 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009112 SourceLocation ELoc;
9113 SourceRange ERange;
9114 Expr *SimpleRefExpr = RefExpr;
9115 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009116 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009117 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009118 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009119 PrivateCopies.push_back(nullptr);
9120 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009121 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009122 ValueDecl *D = Res.first;
9123 if (!D)
9124 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009125
Alexey Bataev60da77e2016-02-29 05:54:20 +00009126 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009127 QualType Type = D->getType();
9128 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009129
9130 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9131 // A variable that appears in a private clause must not have an incomplete
9132 // type or a reference type.
9133 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00009134 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009135 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009136 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009137
9138 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
9139 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00009140 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009141 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009142 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009143
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009144 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00009145 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009146 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009147 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009148 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009149 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009150 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009151 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9152 // A list item that specifies a given variable may not appear in more
9153 // than one clause on the same directive, except that a variable may be
9154 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009155 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9156 // A list item may appear in a firstprivate or lastprivate clause but not
9157 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009158 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009159 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) &&
9160 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009161 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009162 << getOpenMPClauseName(DVar.CKind)
9163 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009164 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009165 continue;
9166 }
9167
9168 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9169 // in a Construct]
9170 // Variables with the predetermined data-sharing attributes may not be
9171 // listed in data-sharing attributes clauses, except for the cases
9172 // listed below. For these exceptions only, listing a predetermined
9173 // variable in a data-sharing attribute clause is allowed and overrides
9174 // the variable's predetermined data-sharing attributes.
9175 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9176 // in a Construct, C/C++, p.2]
9177 // Variables with const-qualified type having no mutable member may be
9178 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00009179 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009180 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9181 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009182 << getOpenMPClauseName(DVar.CKind)
9183 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009184 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009185 continue;
9186 }
9187
9188 // OpenMP [2.9.3.4, Restrictions, p.2]
9189 // A list item that is private within a parallel region must not appear
9190 // in a firstprivate clause on a worksharing construct if any of the
9191 // worksharing regions arising from the worksharing construct ever bind
9192 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009193 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9194 // A list item that is private within a teams region must not appear in a
9195 // firstprivate clause on a distribute construct if any of the distribute
9196 // regions arising from the distribute construct ever bind to any of the
9197 // teams regions arising from the teams construct.
9198 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9199 // A list item that appears in a reduction clause of a teams construct
9200 // must not appear in a firstprivate clause on a distribute construct if
9201 // any of the distribute regions arising from the distribute construct
9202 // ever bind to any of the teams regions arising from the teams construct.
9203 if ((isOpenMPWorksharingDirective(CurrDir) ||
9204 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009205 !isOpenMPParallelDirective(CurrDir) &&
9206 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009207 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009208 if (DVar.CKind != OMPC_shared &&
9209 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009210 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009211 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00009212 Diag(ELoc, diag::err_omp_required_access)
9213 << getOpenMPClauseName(OMPC_firstprivate)
9214 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009215 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009216 continue;
9217 }
9218 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009219 // OpenMP [2.9.3.4, Restrictions, p.3]
9220 // A list item that appears in a reduction clause of a parallel construct
9221 // must not appear in a firstprivate clause on a worksharing or task
9222 // construct if any of the worksharing or task regions arising from the
9223 // worksharing or task construct ever bind to any of the parallel regions
9224 // arising from the parallel construct.
9225 // OpenMP [2.9.3.4, Restrictions, p.4]
9226 // A list item that appears in a reduction clause in worksharing
9227 // construct must not appear in a firstprivate clause in a task construct
9228 // encountered during execution of any of the worksharing regions arising
9229 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00009230 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009231 DVar = DSAStack->hasInnermostDSA(
9232 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
9233 [](OpenMPDirectiveKind K) -> bool {
9234 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009235 isOpenMPWorksharingDirective(K) ||
9236 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009237 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009238 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009239 if (DVar.CKind == OMPC_reduction &&
9240 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009241 isOpenMPWorksharingDirective(DVar.DKind) ||
9242 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009243 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
9244 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009245 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009246 continue;
9247 }
9248 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009249
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009250 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9251 // A list item cannot appear in both a map clause and a data-sharing
9252 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00009253 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00009254 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00009255 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00009256 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00009257 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00009258 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00009259 CurrDir == OMPD_target_parallel_for_simd ||
9260 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00009261 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009262 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009263 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009264 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9265 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9266 ConflictKind = WhereFoundClauseKind;
9267 return true;
9268 })) {
9269 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009270 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00009271 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009272 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9273 ReportOriginalDSA(*this, DSAStack, D, DVar);
9274 continue;
9275 }
9276 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009277 }
9278
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009279 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009280 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00009281 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009282 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9283 << getOpenMPClauseName(OMPC_firstprivate) << Type
9284 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9285 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009286 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009287 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009288 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009289 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00009290 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009291 continue;
9292 }
9293
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009294 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009295 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9296 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009297 // Generate helper private variable and initialize it with the value of the
9298 // original variable. The address of the original variable is replaced by
9299 // the address of the new private variable in the CodeGen. This new variable
9300 // is not added to IdResolver, so the code in the OpenMP region uses
9301 // original variable for proper diagnostics and variable capturing.
9302 Expr *VDInitRefExpr = nullptr;
9303 // For arrays generate initializer for single element and replace it by the
9304 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009305 if (Type->isArrayType()) {
9306 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009307 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009308 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009309 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009310 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009311 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009312 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00009313 InitializedEntity Entity =
9314 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009315 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
9316
9317 InitializationSequence InitSeq(*this, Entity, Kind, Init);
9318 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
9319 if (Result.isInvalid())
9320 VDPrivate->setInvalidDecl();
9321 else
9322 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009323 // Remove temp variable declaration.
9324 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009325 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009326 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
9327 ".firstprivate.temp");
9328 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
9329 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00009330 AddInitializerToDecl(VDPrivate,
9331 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009332 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009333 }
9334 if (VDPrivate->isInvalidDecl()) {
9335 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009336 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009337 diag::note_omp_task_predetermined_firstprivate_here);
9338 }
9339 continue;
9340 }
9341 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009342 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00009343 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
9344 RefExpr->getExprLoc());
9345 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009346 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009347 if (TopDVar.CKind == OMPC_lastprivate)
9348 Ref = TopDVar.PrivateCopy;
9349 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009350 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00009351 if (!IsOpenMPCapturedDecl(D))
9352 ExprCaptures.push_back(Ref->getDecl());
9353 }
Alexey Bataev417089f2016-02-17 13:19:37 +00009354 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009355 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009356 Vars.push_back((VD || CurContext->isDependentContext())
9357 ? RefExpr->IgnoreParens()
9358 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009359 PrivateCopies.push_back(VDPrivateRefExpr);
9360 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009361 }
9362
Alexey Bataeved09d242014-05-28 05:53:51 +00009363 if (Vars.empty())
9364 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009365
9366 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009367 Vars, PrivateCopies, Inits,
9368 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009369}
9370
Alexander Musman1bb328c2014-06-04 13:06:39 +00009371OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9372 SourceLocation StartLoc,
9373 SourceLocation LParenLoc,
9374 SourceLocation EndLoc) {
9375 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00009376 SmallVector<Expr *, 8> SrcExprs;
9377 SmallVector<Expr *, 8> DstExprs;
9378 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00009379 SmallVector<Decl *, 4> ExprCaptures;
9380 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009381 for (auto &RefExpr : VarList) {
9382 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009383 SourceLocation ELoc;
9384 SourceRange ERange;
9385 Expr *SimpleRefExpr = RefExpr;
9386 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009387 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00009388 // It will be analyzed later.
9389 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00009390 SrcExprs.push_back(nullptr);
9391 DstExprs.push_back(nullptr);
9392 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009393 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009394 ValueDecl *D = Res.first;
9395 if (!D)
9396 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009397
Alexey Bataev74caaf22016-02-20 04:09:36 +00009398 QualType Type = D->getType();
9399 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009400
9401 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
9402 // A variable that appears in a lastprivate clause must not have an
9403 // incomplete type or a reference type.
9404 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00009405 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00009406 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009407 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009408
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009409 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009410 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9411 // in a Construct]
9412 // Variables with the predetermined data-sharing attributes may not be
9413 // listed in data-sharing attributes clauses, except for the cases
9414 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009415 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9416 // A list item may appear in a firstprivate or lastprivate clause but not
9417 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009418 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009419 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009420 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00009421 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
9422 Diag(ELoc, diag::err_omp_wrong_dsa)
9423 << getOpenMPClauseName(DVar.CKind)
9424 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009425 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009426 continue;
9427 }
9428
Alexey Bataevf29276e2014-06-18 04:14:57 +00009429 // OpenMP [2.14.3.5, Restrictions, p.2]
9430 // A list item that is private within a parallel region, or that appears in
9431 // the reduction clause of a parallel construct, must not appear in a
9432 // lastprivate clause on a worksharing construct if any of the corresponding
9433 // worksharing regions ever binds to any of the corresponding parallel
9434 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00009435 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00009436 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009437 !isOpenMPParallelDirective(CurrDir) &&
9438 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00009439 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009440 if (DVar.CKind != OMPC_shared) {
9441 Diag(ELoc, diag::err_omp_required_access)
9442 << getOpenMPClauseName(OMPC_lastprivate)
9443 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009444 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009445 continue;
9446 }
9447 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009448
Alexander Musman1bb328c2014-06-04 13:06:39 +00009449 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00009450 // A variable of class type (or array thereof) that appears in a
9451 // lastprivate clause requires an accessible, unambiguous default
9452 // constructor for the class type, unless the list item is also specified
9453 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00009454 // A variable of class type (or array thereof) that appears in a
9455 // lastprivate clause requires an accessible, unambiguous copy assignment
9456 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00009457 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009458 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009459 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009460 D->hasAttrs() ? &D->getAttrs() : nullptr);
9461 auto *PseudoSrcExpr =
9462 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009463 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009464 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009465 D->hasAttrs() ? &D->getAttrs() : nullptr);
9466 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009467 // For arrays generate assignment operation for single element and replace
9468 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009469 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00009470 PseudoDstExpr, PseudoSrcExpr);
9471 if (AssignmentOp.isInvalid())
9472 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00009473 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00009474 /*DiscardedValue=*/true);
9475 if (AssignmentOp.isInvalid())
9476 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009477
Alexey Bataev74caaf22016-02-20 04:09:36 +00009478 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009479 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009480 if (TopDVar.CKind == OMPC_firstprivate)
9481 Ref = TopDVar.PrivateCopy;
9482 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009483 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009484 if (!IsOpenMPCapturedDecl(D))
9485 ExprCaptures.push_back(Ref->getDecl());
9486 }
9487 if (TopDVar.CKind == OMPC_firstprivate ||
9488 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009489 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009490 ExprResult RefRes = DefaultLvalueConversion(Ref);
9491 if (!RefRes.isUsable())
9492 continue;
9493 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009494 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9495 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009496 if (!PostUpdateRes.isUsable())
9497 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009498 ExprPostUpdates.push_back(
9499 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009500 }
9501 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009502 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009503 Vars.push_back((VD || CurContext->isDependentContext())
9504 ? RefExpr->IgnoreParens()
9505 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00009506 SrcExprs.push_back(PseudoSrcExpr);
9507 DstExprs.push_back(PseudoDstExpr);
9508 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00009509 }
9510
9511 if (Vars.empty())
9512 return nullptr;
9513
9514 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00009515 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009516 buildPreInits(Context, ExprCaptures),
9517 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00009518}
9519
Alexey Bataev758e55e2013-09-06 18:03:48 +00009520OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9521 SourceLocation StartLoc,
9522 SourceLocation LParenLoc,
9523 SourceLocation EndLoc) {
9524 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00009525 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009526 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009527 SourceLocation ELoc;
9528 SourceRange ERange;
9529 Expr *SimpleRefExpr = RefExpr;
9530 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009531 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00009532 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009533 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009534 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009535 ValueDecl *D = Res.first;
9536 if (!D)
9537 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009538
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009539 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009540 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9541 // in a Construct]
9542 // Variables with the predetermined data-sharing attributes may not be
9543 // listed in data-sharing attributes clauses, except for the cases
9544 // listed below. For these exceptions only, listing a predetermined
9545 // variable in a data-sharing attribute clause is allowed and overrides
9546 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009547 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00009548 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9549 DVar.RefExpr) {
9550 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9551 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009552 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009553 continue;
9554 }
9555
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009556 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009557 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009558 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009559 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009560 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9561 ? RefExpr->IgnoreParens()
9562 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009563 }
9564
Alexey Bataeved09d242014-05-28 05:53:51 +00009565 if (Vars.empty())
9566 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009567
9568 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9569}
9570
Alexey Bataevc5e02582014-06-16 07:08:35 +00009571namespace {
9572class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9573 DSAStackTy *Stack;
9574
9575public:
9576 bool VisitDeclRefExpr(DeclRefExpr *E) {
9577 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009578 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009579 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9580 return false;
9581 if (DVar.CKind != OMPC_unknown)
9582 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009583 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9584 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009585 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009586 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009587 return true;
9588 return false;
9589 }
9590 return false;
9591 }
9592 bool VisitStmt(Stmt *S) {
9593 for (auto Child : S->children()) {
9594 if (Child && Visit(Child))
9595 return true;
9596 }
9597 return false;
9598 }
Alexey Bataev23b69422014-06-18 07:08:49 +00009599 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009600};
Alexey Bataev23b69422014-06-18 07:08:49 +00009601} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00009602
Alexey Bataev60da77e2016-02-29 05:54:20 +00009603namespace {
9604// Transform MemberExpression for specified FieldDecl of current class to
9605// DeclRefExpr to specified OMPCapturedExprDecl.
9606class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9607 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9608 ValueDecl *Field;
9609 DeclRefExpr *CapturedExpr;
9610
9611public:
9612 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9613 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9614
9615 ExprResult TransformMemberExpr(MemberExpr *E) {
9616 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9617 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00009618 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009619 return CapturedExpr;
9620 }
9621 return BaseTransform::TransformMemberExpr(E);
9622 }
9623 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9624};
9625} // namespace
9626
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009627template <typename T>
9628static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9629 const llvm::function_ref<T(ValueDecl *)> &Gen) {
9630 for (auto &Set : Lookups) {
9631 for (auto *D : Set) {
9632 if (auto Res = Gen(cast<ValueDecl>(D)))
9633 return Res;
9634 }
9635 }
9636 return T();
9637}
9638
9639static ExprResult
9640buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9641 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9642 const DeclarationNameInfo &ReductionId, QualType Ty,
9643 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9644 if (ReductionIdScopeSpec.isInvalid())
9645 return ExprError();
9646 SmallVector<UnresolvedSet<8>, 4> Lookups;
9647 if (S) {
9648 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9649 Lookup.suppressDiagnostics();
9650 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9651 auto *D = Lookup.getRepresentativeDecl();
9652 do {
9653 S = S->getParent();
9654 } while (S && !S->isDeclScope(D));
9655 if (S)
9656 S = S->getParent();
9657 Lookups.push_back(UnresolvedSet<8>());
9658 Lookups.back().append(Lookup.begin(), Lookup.end());
9659 Lookup.clear();
9660 }
9661 } else if (auto *ULE =
9662 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9663 Lookups.push_back(UnresolvedSet<8>());
9664 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00009665 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009666 if (D == PrevD)
9667 Lookups.push_back(UnresolvedSet<8>());
9668 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9669 Lookups.back().addDecl(DRD);
9670 PrevD = D;
9671 }
9672 }
Alexey Bataevfdc20352017-08-25 15:43:55 +00009673 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9674 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009675 Ty->containsUnexpandedParameterPack() ||
9676 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9677 return !D->isInvalidDecl() &&
9678 (D->getType()->isDependentType() ||
9679 D->getType()->isInstantiationDependentType() ||
9680 D->getType()->containsUnexpandedParameterPack());
9681 })) {
9682 UnresolvedSet<8> ResSet;
9683 for (auto &Set : Lookups) {
9684 ResSet.append(Set.begin(), Set.end());
9685 // The last item marks the end of all declarations at the specified scope.
9686 ResSet.addDecl(Set[Set.size() - 1]);
9687 }
9688 return UnresolvedLookupExpr::Create(
9689 SemaRef.Context, /*NamingClass=*/nullptr,
9690 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9691 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9692 }
9693 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9694 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9695 if (!D->isInvalidDecl() &&
9696 SemaRef.Context.hasSameType(D->getType(), Ty))
9697 return D;
9698 return nullptr;
9699 }))
9700 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9701 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9702 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9703 if (!D->isInvalidDecl() &&
9704 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9705 !Ty.isMoreQualifiedThan(D->getType()))
9706 return D;
9707 return nullptr;
9708 })) {
9709 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9710 /*DetectVirtual=*/false);
9711 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9712 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9713 VD->getType().getUnqualifiedType()))) {
9714 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
9715 /*DiagID=*/0) !=
9716 Sema::AR_inaccessible) {
9717 SemaRef.BuildBasePathArray(Paths, BasePath);
9718 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9719 }
9720 }
9721 }
9722 }
9723 if (ReductionIdScopeSpec.isSet()) {
9724 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
9725 return ExprError();
9726 }
9727 return ExprEmpty();
9728}
9729
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009730namespace {
9731/// Data for the reduction-based clauses.
9732struct ReductionData {
9733 /// List of original reduction items.
9734 SmallVector<Expr *, 8> Vars;
9735 /// List of private copies of the reduction items.
9736 SmallVector<Expr *, 8> Privates;
9737 /// LHS expressions for the reduction_op expressions.
9738 SmallVector<Expr *, 8> LHSs;
9739 /// RHS expressions for the reduction_op expressions.
9740 SmallVector<Expr *, 8> RHSs;
9741 /// Reduction operation expression.
9742 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +00009743 /// Taskgroup descriptors for the corresponding reduction items in
9744 /// in_reduction clauses.
9745 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009746 /// List of captures for clause.
9747 SmallVector<Decl *, 4> ExprCaptures;
9748 /// List of postupdate expressions.
9749 SmallVector<Expr *, 4> ExprPostUpdates;
9750 ReductionData() = delete;
9751 /// Reserves required memory for the reduction data.
9752 ReductionData(unsigned Size) {
9753 Vars.reserve(Size);
9754 Privates.reserve(Size);
9755 LHSs.reserve(Size);
9756 RHSs.reserve(Size);
9757 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +00009758 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009759 ExprCaptures.reserve(Size);
9760 ExprPostUpdates.reserve(Size);
9761 }
9762 /// Stores reduction item and reduction operation only (required for dependent
9763 /// reduction item).
9764 void push(Expr *Item, Expr *ReductionOp) {
9765 Vars.emplace_back(Item);
9766 Privates.emplace_back(nullptr);
9767 LHSs.emplace_back(nullptr);
9768 RHSs.emplace_back(nullptr);
9769 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009770 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009771 }
9772 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +00009773 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
9774 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009775 Vars.emplace_back(Item);
9776 Privates.emplace_back(Private);
9777 LHSs.emplace_back(LHS);
9778 RHSs.emplace_back(RHS);
9779 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009780 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009781 }
9782};
9783} // namespace
9784
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00009785static bool CheckOMPArraySectionConstantForReduction(
9786 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
9787 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
9788 const Expr *Length = OASE->getLength();
9789 if (Length == nullptr) {
9790 // For array sections of the form [1:] or [:], we would need to analyze
9791 // the lower bound...
9792 if (OASE->getColonLoc().isValid())
9793 return false;
9794
9795 // This is an array subscript which has implicit length 1!
9796 SingleElement = true;
9797 ArraySizes.push_back(llvm::APSInt::get(1));
9798 } else {
9799 llvm::APSInt ConstantLengthValue;
9800 if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
9801 return false;
9802
9803 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
9804 ArraySizes.push_back(ConstantLengthValue);
9805 }
9806
9807 // Get the base of this array section and walk up from there.
9808 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
9809
9810 // We require length = 1 for all array sections except the right-most to
9811 // guarantee that the memory region is contiguous and has no holes in it.
9812 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
9813 Length = TempOASE->getLength();
9814 if (Length == nullptr) {
9815 // For array sections of the form [1:] or [:], we would need to analyze
9816 // the lower bound...
9817 if (OASE->getColonLoc().isValid())
9818 return false;
9819
9820 // This is an array subscript which has implicit length 1!
9821 ArraySizes.push_back(llvm::APSInt::get(1));
9822 } else {
9823 llvm::APSInt ConstantLengthValue;
9824 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
9825 ConstantLengthValue.getSExtValue() != 1)
9826 return false;
9827
9828 ArraySizes.push_back(ConstantLengthValue);
9829 }
9830 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9831 }
9832
9833 // If we have a single element, we don't need to add the implicit lengths.
9834 if (!SingleElement) {
9835 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
9836 // Has implicit length 1!
9837 ArraySizes.push_back(llvm::APSInt::get(1));
9838 Base = TempASE->getBase()->IgnoreParenImpCasts();
9839 }
9840 }
9841
9842 // This array section can be privatized as a single value or as a constant
9843 // sized array.
9844 return true;
9845}
9846
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009847static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +00009848 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
9849 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9850 SourceLocation ColonLoc, SourceLocation EndLoc,
9851 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009852 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009853 auto DN = ReductionId.getName();
9854 auto OOK = DN.getCXXOverloadedOperator();
9855 BinaryOperatorKind BOK = BO_Comma;
9856
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009857 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009858 // OpenMP [2.14.3.6, reduction clause]
9859 // C
9860 // reduction-identifier is either an identifier or one of the following
9861 // operators: +, -, *, &, |, ^, && and ||
9862 // C++
9863 // reduction-identifier is either an id-expression or one of the following
9864 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +00009865 switch (OOK) {
9866 case OO_Plus:
9867 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009868 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009869 break;
9870 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009871 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009872 break;
9873 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009874 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009875 break;
9876 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009877 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009878 break;
9879 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009880 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009881 break;
9882 case OO_AmpAmp:
9883 BOK = BO_LAnd;
9884 break;
9885 case OO_PipePipe:
9886 BOK = BO_LOr;
9887 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009888 case OO_New:
9889 case OO_Delete:
9890 case OO_Array_New:
9891 case OO_Array_Delete:
9892 case OO_Slash:
9893 case OO_Percent:
9894 case OO_Tilde:
9895 case OO_Exclaim:
9896 case OO_Equal:
9897 case OO_Less:
9898 case OO_Greater:
9899 case OO_LessEqual:
9900 case OO_GreaterEqual:
9901 case OO_PlusEqual:
9902 case OO_MinusEqual:
9903 case OO_StarEqual:
9904 case OO_SlashEqual:
9905 case OO_PercentEqual:
9906 case OO_CaretEqual:
9907 case OO_AmpEqual:
9908 case OO_PipeEqual:
9909 case OO_LessLess:
9910 case OO_GreaterGreater:
9911 case OO_LessLessEqual:
9912 case OO_GreaterGreaterEqual:
9913 case OO_EqualEqual:
9914 case OO_ExclaimEqual:
9915 case OO_PlusPlus:
9916 case OO_MinusMinus:
9917 case OO_Comma:
9918 case OO_ArrowStar:
9919 case OO_Arrow:
9920 case OO_Call:
9921 case OO_Subscript:
9922 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00009923 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009924 case NUM_OVERLOADED_OPERATORS:
9925 llvm_unreachable("Unexpected reduction identifier");
9926 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009927 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009928 if (II->isStr("max"))
9929 BOK = BO_GT;
9930 else if (II->isStr("min"))
9931 BOK = BO_LT;
9932 }
9933 break;
9934 }
9935 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009936 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00009937 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009938 else
9939 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009940 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009941
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009942 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
9943 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009944 for (auto RefExpr : VarList) {
9945 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00009946 // OpenMP [2.1, C/C++]
9947 // A list item is a variable or array section, subject to the restrictions
9948 // specified in Section 2.4 on page 42 and in each of the sections
9949 // describing clauses and directives for which a list appears.
9950 // OpenMP [2.14.3.3, Restrictions, p.1]
9951 // A variable that is part of another variable (as an array or
9952 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009953 if (!FirstIter && IR != ER)
9954 ++IR;
9955 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009956 SourceLocation ELoc;
9957 SourceRange ERange;
9958 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009959 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +00009960 /*AllowArraySection=*/true);
9961 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009962 // Try to find 'declare reduction' corresponding construct before using
9963 // builtin/overloaded operators.
9964 QualType Type = Context.DependentTy;
9965 CXXCastPath BasePath;
9966 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009967 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009968 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009969 Expr *ReductionOp = nullptr;
9970 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009971 (DeclareReductionRef.isUnset() ||
9972 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009973 ReductionOp = DeclareReductionRef.get();
9974 // It will be analyzed later.
9975 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009976 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009977 ValueDecl *D = Res.first;
9978 if (!D)
9979 continue;
9980
Alexey Bataev88202be2017-07-27 13:20:36 +00009981 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +00009982 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009983 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
9984 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
9985 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00009986 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009987 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009988 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
9989 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
9990 Type = ATy->getElementType();
9991 else
9992 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00009993 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009994 } else
9995 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9996 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00009997
Alexey Bataevc5e02582014-06-16 07:08:35 +00009998 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9999 // A variable that appears in a private clause must not have an incomplete
10000 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010001 if (S.RequireCompleteType(ELoc, Type,
10002 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010003 continue;
10004 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000010005 // A list item that appears in a reduction clause must not be
10006 // const-qualified.
10007 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010008 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010009 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010010 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10011 VarDecl::DeclarationOnly;
10012 S.Diag(D->getLocation(),
10013 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010014 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +000010015 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010016 continue;
10017 }
10018 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
10019 // If a list-item is a reference type then it must bind to the same object
10020 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +000010021 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +000010022 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +000010023 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010024 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +000010025 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010026 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
10027 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010028 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +000010029 continue;
10030 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010031 }
10032 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010033
Alexey Bataevc5e02582014-06-16 07:08:35 +000010034 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10035 // in a Construct]
10036 // Variables with the predetermined data-sharing attributes may not be
10037 // listed in data-sharing attributes clauses, except for the cases
10038 // listed below. For these exceptions only, listing a predetermined
10039 // variable in a data-sharing attribute clause is allowed and overrides
10040 // the variable's predetermined data-sharing attributes.
10041 // OpenMP [2.14.3.6, Restrictions, p.3]
10042 // Any number of reduction clauses can be specified on the directive,
10043 // but a list item can appear only once in the reduction clauses for that
10044 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +000010045 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010046 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010047 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010048 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010049 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010050 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010051 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010052 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010053 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010054 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010055 << getOpenMPClauseName(DVar.CKind)
10056 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010057 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010058 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010059 }
10060
10061 // OpenMP [2.14.3.6, Restrictions, p.1]
10062 // A list item that appears in a reduction clause of a worksharing
10063 // construct must be shared in the parallel regions to which any of the
10064 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010065 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010066 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010067 !isOpenMPParallelDirective(CurrDir) &&
10068 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010069 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010070 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010071 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010072 << getOpenMPClauseName(OMPC_reduction)
10073 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010074 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010075 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000010076 }
10077 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010078
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010079 // Try to find 'declare reduction' corresponding construct before using
10080 // builtin/overloaded operators.
10081 CXXCastPath BasePath;
10082 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010083 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010084 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10085 if (DeclareReductionRef.isInvalid())
10086 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010087 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010088 (DeclareReductionRef.isUnset() ||
10089 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010090 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010091 continue;
10092 }
10093 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
10094 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010095 S.Diag(ReductionId.getLocStart(),
10096 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010097 << Type << ReductionIdRange;
10098 continue;
10099 }
10100
10101 // OpenMP [2.14.3.6, reduction clause, Restrictions]
10102 // The type of a list item that appears in a reduction clause must be valid
10103 // for the reduction-identifier. For a max or min reduction in C, the type
10104 // of the list item must be an allowed arithmetic data type: char, int,
10105 // float, double, or _Bool, possibly modified with long, short, signed, or
10106 // unsigned. For a max or min reduction in C++, the type of the list item
10107 // must be an allowed arithmetic data type: char, wchar_t, int, float,
10108 // double, or bool, possibly modified with long, short, signed, or unsigned.
10109 if (DeclareReductionRef.isUnset()) {
10110 if ((BOK == BO_GT || BOK == BO_LT) &&
10111 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010112 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
10113 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010114 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010115 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010116 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10117 VarDecl::DeclarationOnly;
10118 S.Diag(D->getLocation(),
10119 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010120 << D;
10121 }
10122 continue;
10123 }
10124 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010125 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010126 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
10127 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010128 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010129 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10130 VarDecl::DeclarationOnly;
10131 S.Diag(D->getLocation(),
10132 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010133 << D;
10134 }
10135 continue;
10136 }
10137 }
10138
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010139 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010140 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +000010141 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010142 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010143 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010144 auto PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010145
10146 // Try if we can determine constant lengths for all array sections and avoid
10147 // the VLA.
10148 bool ConstantLengthOASE = false;
10149 if (OASE) {
10150 bool SingleElement;
10151 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
10152 ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
10153 Context, OASE, SingleElement, ArraySizes);
10154
10155 // If we don't have a single element, we must emit a constant array type.
10156 if (ConstantLengthOASE && !SingleElement) {
10157 for (auto &Size : ArraySizes) {
10158 PrivateTy = Context.getConstantArrayType(
10159 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
10160 }
10161 }
10162 }
10163
10164 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000010165 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000010166 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000010167 if (!Context.getTargetInfo().isVLASupported() &&
10168 S.shouldDiagnoseTargetSupportFromOpenMP()) {
10169 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
10170 S.Diag(ELoc, diag::note_vla_unsupported);
10171 continue;
10172 }
David Majnemer9d168222016-08-05 17:44:54 +000010173 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010174 // Create pseudo array type for private copy. The size for this array will
10175 // be generated during codegen.
10176 // For array subscripts or single variables Private Ty is the same as Type
10177 // (type of the variable or single array element).
10178 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010179 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000010180 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010181 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000010182 } else if (!ASE && !OASE &&
10183 Context.getAsArrayType(D->getType().getNonReferenceType()))
10184 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010185 // Private copy.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010186 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010187 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010188 // Add initializer for private variable.
10189 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010190 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
10191 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010192 if (DeclareReductionRef.isUsable()) {
10193 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
10194 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
10195 if (DRD->getInitializer()) {
10196 Init = DRDRef;
10197 RHSVD->setInit(DRDRef);
10198 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010199 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010200 } else {
10201 switch (BOK) {
10202 case BO_Add:
10203 case BO_Xor:
10204 case BO_Or:
10205 case BO_LOr:
10206 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
10207 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010208 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010209 break;
10210 case BO_Mul:
10211 case BO_LAnd:
10212 if (Type->isScalarType() || Type->isAnyComplexType()) {
10213 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010214 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000010215 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010216 break;
10217 case BO_And: {
10218 // '&' reduction op - initializer is '~0'.
10219 QualType OrigType = Type;
10220 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
10221 Type = ComplexTy->getElementType();
10222 if (Type->isRealFloatingType()) {
10223 llvm::APFloat InitValue =
10224 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
10225 /*isIEEE=*/true);
10226 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10227 Type, ELoc);
10228 } else if (Type->isScalarType()) {
10229 auto Size = Context.getTypeSize(Type);
10230 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
10231 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
10232 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10233 }
10234 if (Init && OrigType->isAnyComplexType()) {
10235 // Init = 0xFFFF + 0xFFFFi;
10236 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010237 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010238 }
10239 Type = OrigType;
10240 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010241 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010242 case BO_LT:
10243 case BO_GT: {
10244 // 'min' reduction op - initializer is 'Largest representable number in
10245 // the reduction list item type'.
10246 // 'max' reduction op - initializer is 'Least representable number in
10247 // the reduction list item type'.
10248 if (Type->isIntegerType() || Type->isPointerType()) {
10249 bool IsSigned = Type->hasSignedIntegerRepresentation();
10250 auto Size = Context.getTypeSize(Type);
10251 QualType IntTy =
10252 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
10253 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010254 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
10255 : llvm::APInt::getMinValue(Size)
10256 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
10257 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010258 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10259 if (Type->isPointerType()) {
10260 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010261 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000010262 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010263 if (CastExpr.isInvalid())
10264 continue;
10265 Init = CastExpr.get();
10266 }
10267 } else if (Type->isRealFloatingType()) {
10268 llvm::APFloat InitValue = llvm::APFloat::getLargest(
10269 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
10270 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10271 Type, ELoc);
10272 }
10273 break;
10274 }
10275 case BO_PtrMemD:
10276 case BO_PtrMemI:
10277 case BO_MulAssign:
10278 case BO_Div:
10279 case BO_Rem:
10280 case BO_Sub:
10281 case BO_Shl:
10282 case BO_Shr:
10283 case BO_LE:
10284 case BO_GE:
10285 case BO_EQ:
10286 case BO_NE:
10287 case BO_AndAssign:
10288 case BO_XorAssign:
10289 case BO_OrAssign:
10290 case BO_Assign:
10291 case BO_AddAssign:
10292 case BO_SubAssign:
10293 case BO_DivAssign:
10294 case BO_RemAssign:
10295 case BO_ShlAssign:
10296 case BO_ShrAssign:
10297 case BO_Comma:
10298 llvm_unreachable("Unexpected reduction operation");
10299 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010300 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010301 if (Init && DeclareReductionRef.isUnset())
10302 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
10303 else if (!Init)
10304 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010305 if (RHSVD->isInvalidDecl())
10306 continue;
10307 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010308 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
10309 << Type << ReductionIdRange;
10310 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10311 VarDecl::DeclarationOnly;
10312 S.Diag(D->getLocation(),
10313 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010314 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010315 continue;
10316 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010317 // Store initializer for single element in private copy. Will be used during
10318 // codegen.
10319 PrivateVD->setInit(RHSVD->getInit());
10320 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010321 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010322 ExprResult ReductionOp;
10323 if (DeclareReductionRef.isUsable()) {
10324 QualType RedTy = DeclareReductionRef.get()->getType();
10325 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010326 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
10327 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010328 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010329 LHS = S.DefaultLvalueConversion(LHS.get());
10330 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010331 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10332 CK_UncheckedDerivedToBase, LHS.get(),
10333 &BasePath, LHS.get()->getValueKind());
10334 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10335 CK_UncheckedDerivedToBase, RHS.get(),
10336 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010337 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010338 FunctionProtoType::ExtProtoInfo EPI;
10339 QualType Params[] = {PtrRedTy, PtrRedTy};
10340 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
10341 auto *OVE = new (Context) OpaqueValueExpr(
10342 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010343 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010344 Expr *Args[] = {LHS.get(), RHS.get()};
10345 ReductionOp = new (Context)
10346 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
10347 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010348 ReductionOp = S.BuildBinOp(
10349 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010350 if (ReductionOp.isUsable()) {
10351 if (BOK != BO_LT && BOK != BO_GT) {
10352 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010353 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10354 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010355 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000010356 auto *ConditionalOp = new (Context)
10357 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
10358 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010359 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010360 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10361 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010362 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010363 if (ReductionOp.isUsable())
10364 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010365 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010366 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010367 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010368 }
10369
Alexey Bataevfa312f32017-07-21 18:48:21 +000010370 // OpenMP [2.15.4.6, Restrictions, p.2]
10371 // A list item that appears in an in_reduction clause of a task construct
10372 // must appear in a task_reduction clause of a construct associated with a
10373 // taskgroup region that includes the participating task in its taskgroup
10374 // set. The construct associated with the innermost region that meets this
10375 // condition must specify the same reduction-identifier as the in_reduction
10376 // clause.
10377 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000010378 SourceRange ParentSR;
10379 BinaryOperatorKind ParentBOK;
10380 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000010381 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000010382 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010383 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
10384 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010385 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010386 Stack->getTopMostTaskgroupReductionData(
10387 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010388 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
10389 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
10390 if (!IsParentBOK && !IsParentReductionOp) {
10391 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
10392 continue;
10393 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000010394 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
10395 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
10396 IsParentReductionOp) {
10397 bool EmitError = true;
10398 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
10399 llvm::FoldingSetNodeID RedId, ParentRedId;
10400 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
10401 DeclareReductionRef.get()->Profile(RedId, Context,
10402 /*Canonical=*/true);
10403 EmitError = RedId != ParentRedId;
10404 }
10405 if (EmitError) {
10406 S.Diag(ReductionId.getLocStart(),
10407 diag::err_omp_reduction_identifier_mismatch)
10408 << ReductionIdRange << RefExpr->getSourceRange();
10409 S.Diag(ParentSR.getBegin(),
10410 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000010411 << ParentSR
10412 << (IsParentBOK ? ParentBOKDSA.RefExpr
10413 : ParentReductionOpDSA.RefExpr)
10414 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000010415 continue;
10416 }
10417 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010418 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
10419 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000010420 }
10421
Alexey Bataev60da77e2016-02-29 05:54:20 +000010422 DeclRefExpr *Ref = nullptr;
10423 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010424 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010425 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010426 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010427 VarsExpr =
10428 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
10429 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000010430 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010431 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010432 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010433 if (!S.IsOpenMPCapturedDecl(D)) {
10434 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010435 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010436 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010437 if (!RefRes.isUsable())
10438 continue;
10439 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010440 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10441 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010442 if (!PostUpdateRes.isUsable())
10443 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010444 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
10445 Stack->getCurrentDirective() == OMPD_taskgroup) {
10446 S.Diag(RefExpr->getExprLoc(),
10447 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000010448 << RefExpr->getSourceRange();
10449 continue;
10450 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010451 RD.ExprPostUpdates.emplace_back(
10452 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000010453 }
10454 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010455 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000010456 // All reduction items are still marked as reduction (to do not increase
10457 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010458 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010459 if (CurrDir == OMPD_taskgroup) {
10460 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010461 Stack->addTaskgroupReductionData(D, ReductionIdRange,
10462 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000010463 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010464 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010465 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010466 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10467 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010468 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010469 return RD.Vars.empty();
10470}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010471
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010472OMPClause *Sema::ActOnOpenMPReductionClause(
10473 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10474 SourceLocation ColonLoc, SourceLocation EndLoc,
10475 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10476 ArrayRef<Expr *> UnresolvedReductions) {
10477 ReductionData RD(VarList.size());
10478
Alexey Bataev169d96a2017-07-18 20:17:46 +000010479 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
10480 StartLoc, LParenLoc, ColonLoc, EndLoc,
10481 ReductionIdScopeSpec, ReductionId,
10482 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010483 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000010484
Alexey Bataevc5e02582014-06-16 07:08:35 +000010485 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010486 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10487 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10488 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10489 buildPreInits(Context, RD.ExprCaptures),
10490 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000010491}
10492
Alexey Bataev169d96a2017-07-18 20:17:46 +000010493OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10494 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10495 SourceLocation ColonLoc, SourceLocation EndLoc,
10496 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10497 ArrayRef<Expr *> UnresolvedReductions) {
10498 ReductionData RD(VarList.size());
10499
10500 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
10501 VarList, StartLoc, LParenLoc, ColonLoc,
10502 EndLoc, ReductionIdScopeSpec, ReductionId,
10503 UnresolvedReductions, RD))
10504 return nullptr;
10505
10506 return OMPTaskReductionClause::Create(
10507 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10508 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10509 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10510 buildPreInits(Context, RD.ExprCaptures),
10511 buildPostUpdate(*this, RD.ExprPostUpdates));
10512}
10513
Alexey Bataevfa312f32017-07-21 18:48:21 +000010514OMPClause *Sema::ActOnOpenMPInReductionClause(
10515 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10516 SourceLocation ColonLoc, SourceLocation EndLoc,
10517 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10518 ArrayRef<Expr *> UnresolvedReductions) {
10519 ReductionData RD(VarList.size());
10520
10521 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
10522 StartLoc, LParenLoc, ColonLoc, EndLoc,
10523 ReductionIdScopeSpec, ReductionId,
10524 UnresolvedReductions, RD))
10525 return nullptr;
10526
10527 return OMPInReductionClause::Create(
10528 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10529 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000010530 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000010531 buildPreInits(Context, RD.ExprCaptures),
10532 buildPostUpdate(*this, RD.ExprPostUpdates));
10533}
10534
Alexey Bataevecba70f2016-04-12 11:02:11 +000010535bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10536 SourceLocation LinLoc) {
10537 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10538 LinKind == OMPC_LINEAR_unknown) {
10539 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10540 return true;
10541 }
10542 return false;
10543}
10544
10545bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
10546 OpenMPLinearClauseKind LinKind,
10547 QualType Type) {
10548 auto *VD = dyn_cast_or_null<VarDecl>(D);
10549 // A variable must not have an incomplete type or a reference type.
10550 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10551 return true;
10552 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10553 !Type->isReferenceType()) {
10554 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10555 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10556 return true;
10557 }
10558 Type = Type.getNonReferenceType();
10559
10560 // A list item must not be const-qualified.
10561 if (Type.isConstant(Context)) {
10562 Diag(ELoc, diag::err_omp_const_variable)
10563 << getOpenMPClauseName(OMPC_linear);
10564 if (D) {
10565 bool IsDecl =
10566 !VD ||
10567 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10568 Diag(D->getLocation(),
10569 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10570 << D;
10571 }
10572 return true;
10573 }
10574
10575 // A list item must be of integral or pointer type.
10576 Type = Type.getUnqualifiedType().getCanonicalType();
10577 const auto *Ty = Type.getTypePtrOrNull();
10578 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10579 !Ty->isPointerType())) {
10580 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10581 if (D) {
10582 bool IsDecl =
10583 !VD ||
10584 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10585 Diag(D->getLocation(),
10586 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10587 << D;
10588 }
10589 return true;
10590 }
10591 return false;
10592}
10593
Alexey Bataev182227b2015-08-20 10:54:39 +000010594OMPClause *Sema::ActOnOpenMPLinearClause(
10595 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10596 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10597 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010598 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010599 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000010600 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010601 SmallVector<Decl *, 4> ExprCaptures;
10602 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010603 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000010604 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +000010605 for (auto &RefExpr : VarList) {
10606 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010607 SourceLocation ELoc;
10608 SourceRange ERange;
10609 Expr *SimpleRefExpr = RefExpr;
10610 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10611 /*AllowArraySection=*/false);
10612 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010613 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010614 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010615 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000010616 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000010617 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010618 ValueDecl *D = Res.first;
10619 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000010620 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000010621
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010622 QualType Type = D->getType();
10623 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000010624
10625 // OpenMP [2.14.3.7, linear clause]
10626 // A list-item cannot appear in more than one linear clause.
10627 // A list-item that appears in a linear clause cannot appear in any
10628 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010629 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +000010630 if (DVar.RefExpr) {
10631 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10632 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010633 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000010634 continue;
10635 }
10636
Alexey Bataevecba70f2016-04-12 11:02:11 +000010637 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000010638 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010639 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000010640
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010641 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010642 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
10643 D->hasAttrs() ? &D->getAttrs() : nullptr);
10644 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010645 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010646 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010647 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010648 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010649 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000010650 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10651 if (!IsOpenMPCapturedDecl(D)) {
10652 ExprCaptures.push_back(Ref->getDecl());
10653 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10654 ExprResult RefRes = DefaultLvalueConversion(Ref);
10655 if (!RefRes.isUsable())
10656 continue;
10657 ExprResult PostUpdateRes =
10658 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10659 SimpleRefExpr, RefRes.get());
10660 if (!PostUpdateRes.isUsable())
10661 continue;
10662 ExprPostUpdates.push_back(
10663 IgnoredValueConversions(PostUpdateRes.get()).get());
10664 }
10665 }
10666 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010667 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010668 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010669 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010670 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010671 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010672 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010673 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
10674
10675 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010676 Vars.push_back((VD || CurContext->isDependentContext())
10677 ? RefExpr->IgnoreParens()
10678 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010679 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000010680 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000010681 }
10682
10683 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010684 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010685
10686 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000010687 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010688 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
10689 !Step->isInstantiationDependent() &&
10690 !Step->containsUnexpandedParameterPack()) {
10691 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000010692 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000010693 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010694 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010695 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000010696
Alexander Musman3276a272015-03-21 10:12:56 +000010697 // Build var to save the step value.
10698 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010699 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000010700 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010701 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010702 ExprResult CalcStep =
10703 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010704 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +000010705
Alexander Musman8dba6642014-04-22 13:09:42 +000010706 // Warn about zero linear step (it would be probably better specified as
10707 // making corresponding variables 'const').
10708 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000010709 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
10710 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000010711 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
10712 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000010713 if (!IsConstant && CalcStep.isUsable()) {
10714 // Calculate the step beforehand instead of doing this on each iteration.
10715 // (This is not used if the number of iterations may be kfold-ed).
10716 CalcStepExpr = CalcStep.get();
10717 }
Alexander Musman8dba6642014-04-22 13:09:42 +000010718 }
10719
Alexey Bataev182227b2015-08-20 10:54:39 +000010720 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
10721 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010722 StepExpr, CalcStepExpr,
10723 buildPreInits(Context, ExprCaptures),
10724 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000010725}
10726
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010727static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
10728 Expr *NumIterations, Sema &SemaRef,
10729 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000010730 // Walk the vars and build update/final expressions for the CodeGen.
10731 SmallVector<Expr *, 8> Updates;
10732 SmallVector<Expr *, 8> Finals;
10733 Expr *Step = Clause.getStep();
10734 Expr *CalcStep = Clause.getCalcStep();
10735 // OpenMP [2.14.3.7, linear clause]
10736 // If linear-step is not specified it is assumed to be 1.
10737 if (Step == nullptr)
10738 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010739 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +000010740 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010741 }
Alexander Musman3276a272015-03-21 10:12:56 +000010742 bool HasErrors = false;
10743 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010744 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010745 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +000010746 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010747 SourceLocation ELoc;
10748 SourceRange ERange;
10749 Expr *SimpleRefExpr = RefExpr;
10750 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
10751 /*AllowArraySection=*/false);
10752 ValueDecl *D = Res.first;
10753 if (Res.second || !D) {
10754 Updates.push_back(nullptr);
10755 Finals.push_back(nullptr);
10756 HasErrors = true;
10757 continue;
10758 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010759 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +000010760 Expr *InitExpr = *CurInit;
10761
10762 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000010763 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010764 Expr *CapturedRef;
10765 if (LinKind == OMPC_LINEAR_uval)
10766 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
10767 else
10768 CapturedRef =
10769 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
10770 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
10771 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010772
10773 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010774 ExprResult Update;
10775 if (!Info.first) {
10776 Update =
10777 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
10778 InitExpr, IV, Step, /* Subtract */ false);
10779 } else
10780 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010781 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
10782 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010783
10784 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010785 ExprResult Final;
10786 if (!Info.first) {
10787 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
10788 InitExpr, NumIterations, Step,
10789 /* Subtract */ false);
10790 } else
10791 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010792 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
10793 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010794
Alexander Musman3276a272015-03-21 10:12:56 +000010795 if (!Update.isUsable() || !Final.isUsable()) {
10796 Updates.push_back(nullptr);
10797 Finals.push_back(nullptr);
10798 HasErrors = true;
10799 } else {
10800 Updates.push_back(Update.get());
10801 Finals.push_back(Final.get());
10802 }
Richard Trieucc3949d2016-02-18 22:34:54 +000010803 ++CurInit;
10804 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000010805 }
10806 Clause.setUpdates(Updates);
10807 Clause.setFinals(Finals);
10808 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000010809}
10810
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010811OMPClause *Sema::ActOnOpenMPAlignedClause(
10812 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
10813 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
10814
10815 SmallVector<Expr *, 8> Vars;
10816 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000010817 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10818 SourceLocation ELoc;
10819 SourceRange ERange;
10820 Expr *SimpleRefExpr = RefExpr;
10821 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10822 /*AllowArraySection=*/false);
10823 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010824 // It will be analyzed later.
10825 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010826 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000010827 ValueDecl *D = Res.first;
10828 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010829 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010830
Alexey Bataev1efd1662016-03-29 10:59:56 +000010831 QualType QType = D->getType();
10832 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010833
10834 // OpenMP [2.8.1, simd construct, Restrictions]
10835 // The type of list items appearing in the aligned clause must be
10836 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010837 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010838 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000010839 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010840 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010841 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010842 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000010843 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010844 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000010845 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010846 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010847 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010848 continue;
10849 }
10850
10851 // OpenMP [2.8.1, simd construct, Restrictions]
10852 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000010853 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000010854 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010855 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
10856 << getOpenMPClauseName(OMPC_aligned);
10857 continue;
10858 }
10859
Alexey Bataev1efd1662016-03-29 10:59:56 +000010860 DeclRefExpr *Ref = nullptr;
10861 if (!VD && IsOpenMPCapturedDecl(D))
10862 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10863 Vars.push_back(DefaultFunctionArrayConversion(
10864 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
10865 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010866 }
10867
10868 // OpenMP [2.8.1, simd construct, Description]
10869 // The parameter of the aligned clause, alignment, must be a constant
10870 // positive integer expression.
10871 // If no optional parameter is specified, implementation-defined default
10872 // alignments for SIMD instructions on the target platforms are assumed.
10873 if (Alignment != nullptr) {
10874 ExprResult AlignResult =
10875 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
10876 if (AlignResult.isInvalid())
10877 return nullptr;
10878 Alignment = AlignResult.get();
10879 }
10880 if (Vars.empty())
10881 return nullptr;
10882
10883 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
10884 EndLoc, Vars, Alignment);
10885}
10886
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010887OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10888 SourceLocation StartLoc,
10889 SourceLocation LParenLoc,
10890 SourceLocation EndLoc) {
10891 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010892 SmallVector<Expr *, 8> SrcExprs;
10893 SmallVector<Expr *, 8> DstExprs;
10894 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000010895 for (auto &RefExpr : VarList) {
10896 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
10897 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010898 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010899 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010900 SrcExprs.push_back(nullptr);
10901 DstExprs.push_back(nullptr);
10902 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010903 continue;
10904 }
10905
Alexey Bataeved09d242014-05-28 05:53:51 +000010906 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010907 // OpenMP [2.1, C/C++]
10908 // A list item is a variable name.
10909 // OpenMP [2.14.4.1, Restrictions, p.1]
10910 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000010911 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010912 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010913 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
10914 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010915 continue;
10916 }
10917
10918 Decl *D = DE->getDecl();
10919 VarDecl *VD = cast<VarDecl>(D);
10920
10921 QualType Type = VD->getType();
10922 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
10923 // It will be analyzed later.
10924 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010925 SrcExprs.push_back(nullptr);
10926 DstExprs.push_back(nullptr);
10927 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010928 continue;
10929 }
10930
10931 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
10932 // A list item that appears in a copyin clause must be threadprivate.
10933 if (!DSAStack->isThreadPrivate(VD)) {
10934 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000010935 << getOpenMPClauseName(OMPC_copyin)
10936 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010937 continue;
10938 }
10939
10940 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10941 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000010942 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010943 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010944 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010945 auto *SrcVD =
10946 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
10947 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000010948 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010949 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
10950 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010951 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
10952 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010953 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010954 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010955 // For arrays generate assignment operation for single element and replace
10956 // it by the original array element in CodeGen.
10957 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
10958 PseudoDstExpr, PseudoSrcExpr);
10959 if (AssignmentOp.isInvalid())
10960 continue;
10961 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
10962 /*DiscardedValue=*/true);
10963 if (AssignmentOp.isInvalid())
10964 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010965
10966 DSAStack->addDSA(VD, DE, OMPC_copyin);
10967 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010968 SrcExprs.push_back(PseudoSrcExpr);
10969 DstExprs.push_back(PseudoDstExpr);
10970 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010971 }
10972
Alexey Bataeved09d242014-05-28 05:53:51 +000010973 if (Vars.empty())
10974 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010975
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010976 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10977 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010978}
10979
Alexey Bataevbae9a792014-06-27 10:37:06 +000010980OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10981 SourceLocation StartLoc,
10982 SourceLocation LParenLoc,
10983 SourceLocation EndLoc) {
10984 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000010985 SmallVector<Expr *, 8> SrcExprs;
10986 SmallVector<Expr *, 8> DstExprs;
10987 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010988 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010989 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10990 SourceLocation ELoc;
10991 SourceRange ERange;
10992 Expr *SimpleRefExpr = RefExpr;
10993 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10994 /*AllowArraySection=*/false);
10995 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010996 // It will be analyzed later.
10997 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010998 SrcExprs.push_back(nullptr);
10999 DstExprs.push_back(nullptr);
11000 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011001 }
Alexey Bataeve122da12016-03-17 10:50:17 +000011002 ValueDecl *D = Res.first;
11003 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000011004 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011005
Alexey Bataeve122da12016-03-17 10:50:17 +000011006 QualType Type = D->getType();
11007 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011008
11009 // OpenMP [2.14.4.2, Restrictions, p.2]
11010 // A list item that appears in a copyprivate clause may not appear in a
11011 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000011012 if (!VD || !DSAStack->isThreadPrivate(VD)) {
11013 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011014 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
11015 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011016 Diag(ELoc, diag::err_omp_wrong_dsa)
11017 << getOpenMPClauseName(DVar.CKind)
11018 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000011019 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011020 continue;
11021 }
11022
11023 // OpenMP [2.11.4.2, Restrictions, p.1]
11024 // All list items that appear in a copyprivate clause must be either
11025 // threadprivate or private in the enclosing context.
11026 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011027 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011028 if (DVar.CKind == OMPC_shared) {
11029 Diag(ELoc, diag::err_omp_required_access)
11030 << getOpenMPClauseName(OMPC_copyprivate)
11031 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000011032 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011033 continue;
11034 }
11035 }
11036 }
11037
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011038 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000011039 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011040 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011041 << getOpenMPClauseName(OMPC_copyprivate) << Type
11042 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011043 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000011044 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011045 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000011046 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011047 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000011048 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011049 continue;
11050 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011051
Alexey Bataevbae9a792014-06-27 10:37:06 +000011052 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11053 // A variable of class type (or array thereof) that appears in a
11054 // copyin clause requires an accessible, unambiguous copy assignment
11055 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011056 Type = Context.getBaseElementType(Type.getNonReferenceType())
11057 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000011058 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011059 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
11060 D->hasAttrs() ? &D->getAttrs() : nullptr);
11061 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000011062 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011063 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
11064 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000011065 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000011066 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011067 PseudoDstExpr, PseudoSrcExpr);
11068 if (AssignmentOp.isInvalid())
11069 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000011070 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011071 /*DiscardedValue=*/true);
11072 if (AssignmentOp.isInvalid())
11073 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011074
11075 // No need to mark vars as copyprivate, they are already threadprivate or
11076 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000011077 assert(VD || IsOpenMPCapturedDecl(D));
11078 Vars.push_back(
11079 VD ? RefExpr->IgnoreParens()
11080 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000011081 SrcExprs.push_back(PseudoSrcExpr);
11082 DstExprs.push_back(PseudoDstExpr);
11083 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000011084 }
11085
11086 if (Vars.empty())
11087 return nullptr;
11088
Alexey Bataeva63048e2015-03-23 06:18:07 +000011089 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11090 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011091}
11092
Alexey Bataev6125da92014-07-21 11:26:11 +000011093OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11094 SourceLocation StartLoc,
11095 SourceLocation LParenLoc,
11096 SourceLocation EndLoc) {
11097 if (VarList.empty())
11098 return nullptr;
11099
11100 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
11101}
Alexey Bataevdea47612014-07-23 07:46:59 +000011102
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011103OMPClause *
11104Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
11105 SourceLocation DepLoc, SourceLocation ColonLoc,
11106 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11107 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011108 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011109 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011110 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011111 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000011112 return nullptr;
11113 }
11114 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011115 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
11116 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011117 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011118 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011119 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
11120 /*Last=*/OMPC_DEPEND_unknown, Except)
11121 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011122 return nullptr;
11123 }
11124 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000011125 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011126 llvm::APSInt DepCounter(/*BitWidth=*/32);
11127 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
11128 if (DepKind == OMPC_DEPEND_sink) {
11129 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
11130 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
11131 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011132 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011133 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011134 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
11135 DSAStack->getParentOrderedRegionParam()) {
11136 for (auto &RefExpr : VarList) {
11137 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000011138 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011139 // It will be analyzed later.
11140 Vars.push_back(RefExpr);
11141 continue;
11142 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011143
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011144 SourceLocation ELoc = RefExpr->getExprLoc();
11145 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
11146 if (DepKind == OMPC_DEPEND_sink) {
11147 if (DepCounter >= TotalDepCount) {
11148 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
11149 continue;
11150 }
11151 ++DepCounter;
11152 // OpenMP [2.13.9, Summary]
11153 // depend(dependence-type : vec), where dependence-type is:
11154 // 'sink' and where vec is the iteration vector, which has the form:
11155 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
11156 // where n is the value specified by the ordered clause in the loop
11157 // directive, xi denotes the loop iteration variable of the i-th nested
11158 // loop associated with the loop directive, and di is a constant
11159 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000011160 if (CurContext->isDependentContext()) {
11161 // It will be analyzed later.
11162 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011163 continue;
11164 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011165 SimpleExpr = SimpleExpr->IgnoreImplicit();
11166 OverloadedOperatorKind OOK = OO_None;
11167 SourceLocation OOLoc;
11168 Expr *LHS = SimpleExpr;
11169 Expr *RHS = nullptr;
11170 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
11171 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
11172 OOLoc = BO->getOperatorLoc();
11173 LHS = BO->getLHS()->IgnoreParenImpCasts();
11174 RHS = BO->getRHS()->IgnoreParenImpCasts();
11175 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
11176 OOK = OCE->getOperator();
11177 OOLoc = OCE->getOperatorLoc();
11178 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11179 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
11180 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
11181 OOK = MCE->getMethodDecl()
11182 ->getNameInfo()
11183 .getName()
11184 .getCXXOverloadedOperator();
11185 OOLoc = MCE->getCallee()->getExprLoc();
11186 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
11187 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11188 }
11189 SourceLocation ELoc;
11190 SourceRange ERange;
11191 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
11192 /*AllowArraySection=*/false);
11193 if (Res.second) {
11194 // It will be analyzed later.
11195 Vars.push_back(RefExpr);
11196 }
11197 ValueDecl *D = Res.first;
11198 if (!D)
11199 continue;
11200
11201 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
11202 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
11203 continue;
11204 }
11205 if (RHS) {
11206 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
11207 RHS, OMPC_depend, /*StrictlyPositive=*/false);
11208 if (RHSRes.isInvalid())
11209 continue;
11210 }
11211 if (!CurContext->isDependentContext() &&
11212 DSAStack->getParentOrderedRegionParam() &&
11213 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Rachel Craik1cf49e42017-09-19 21:04:23 +000011214 ValueDecl* VD = DSAStack->getParentLoopControlVariable(
11215 DepCounter.getZExtValue());
11216 if (VD) {
11217 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
11218 << 1 << VD;
11219 } else {
11220 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
11221 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011222 continue;
11223 }
11224 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011225 } else {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011226 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011227 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000011228 (ASE &&
11229 !ASE->getBase()
11230 ->getType()
11231 .getNonReferenceType()
11232 ->isPointerType() &&
11233 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev463a9fe2017-07-27 19:15:30 +000011234 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11235 << RefExpr->getSourceRange();
11236 continue;
11237 }
11238 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
11239 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevd070a582017-10-25 15:54:04 +000011240 ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
Alexey Bataev463a9fe2017-07-27 19:15:30 +000011241 RefExpr->IgnoreParenImpCasts());
11242 getDiagnostics().setSuppressAllDiagnostics(Suppress);
11243 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
11244 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11245 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011246 continue;
11247 }
11248 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011249 Vars.push_back(RefExpr->IgnoreParenImpCasts());
11250 }
11251
11252 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
11253 TotalDepCount > VarList.size() &&
Rachel Craik1cf49e42017-09-19 21:04:23 +000011254 DSAStack->getParentOrderedRegionParam() &&
11255 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
11256 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011257 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
11258 }
11259 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
11260 Vars.empty())
11261 return nullptr;
11262 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011263 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11264 DepKind, DepLoc, ColonLoc, Vars);
11265 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
11266 DSAStack->addDoacrossDependClause(C, OpsOffs);
11267 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011268}
Michael Wonge710d542015-08-07 16:16:36 +000011269
11270OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
11271 SourceLocation LParenLoc,
11272 SourceLocation EndLoc) {
11273 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000011274 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000011275
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011276 // OpenMP [2.9.1, Restrictions]
11277 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011278 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
11279 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011280 return nullptr;
11281
Alexey Bataev931e19b2017-10-02 16:32:39 +000011282 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011283 OpenMPDirectiveKind CaptureRegion =
11284 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
11285 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev931e19b2017-10-02 16:32:39 +000011286 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11287 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11288 HelperValStmt = buildPreInits(Context, Captures);
11289 }
11290
11291 return new (Context)
11292 OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000011293}
Kelvin Li0bff7af2015-11-23 05:32:03 +000011294
Kelvin Li0bff7af2015-11-23 05:32:03 +000011295static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
11296 DSAStackTy *Stack, QualType QTy) {
11297 NamedDecl *ND;
11298 if (QTy->isIncompleteType(&ND)) {
11299 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
11300 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011301 }
11302 return true;
11303}
11304
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011305/// \brief Return true if it can be proven that the provided array expression
11306/// (array section or array subscript) does NOT specify the whole size of the
11307/// array whose base type is \a BaseQTy.
11308static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
11309 const Expr *E,
11310 QualType BaseQTy) {
11311 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11312
11313 // If this is an array subscript, it refers to the whole size if the size of
11314 // the dimension is constant and equals 1. Also, an array section assumes the
11315 // format of an array subscript if no colon is used.
11316 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
11317 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11318 return ATy->getSize().getSExtValue() != 1;
11319 // Size can't be evaluated statically.
11320 return false;
11321 }
11322
11323 assert(OASE && "Expecting array section if not an array subscript.");
11324 auto *LowerBound = OASE->getLowerBound();
11325 auto *Length = OASE->getLength();
11326
11327 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000011328 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011329 if (LowerBound) {
11330 llvm::APSInt ConstLowerBound;
11331 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
11332 return false; // Can't get the integer value as a constant.
11333 if (ConstLowerBound.getSExtValue())
11334 return true;
11335 }
11336
11337 // If we don't have a length we covering the whole dimension.
11338 if (!Length)
11339 return false;
11340
11341 // If the base is a pointer, we don't have a way to get the size of the
11342 // pointee.
11343 if (BaseQTy->isPointerType())
11344 return false;
11345
11346 // We can only check if the length is the same as the size of the dimension
11347 // if we have a constant array.
11348 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
11349 if (!CATy)
11350 return false;
11351
11352 llvm::APSInt ConstLength;
11353 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11354 return false; // Can't get the integer value as a constant.
11355
11356 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
11357}
11358
11359// Return true if it can be proven that the provided array expression (array
11360// section or array subscript) does NOT specify a single element of the array
11361// whose base type is \a BaseQTy.
11362static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000011363 const Expr *E,
11364 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011365 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11366
11367 // An array subscript always refer to a single element. Also, an array section
11368 // assumes the format of an array subscript if no colon is used.
11369 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
11370 return false;
11371
11372 assert(OASE && "Expecting array section if not an array subscript.");
11373 auto *Length = OASE->getLength();
11374
11375 // If we don't have a length we have to check if the array has unitary size
11376 // for this dimension. Also, we should always expect a length if the base type
11377 // is pointer.
11378 if (!Length) {
11379 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11380 return ATy->getSize().getSExtValue() != 1;
11381 // We cannot assume anything.
11382 return false;
11383 }
11384
11385 // Check if the length evaluates to 1.
11386 llvm::APSInt ConstLength;
11387 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11388 return false; // Can't get the integer value as a constant.
11389
11390 return ConstLength.getSExtValue() != 1;
11391}
11392
Samuel Antao661c0902016-05-26 17:39:58 +000011393// Return the expression of the base of the mappable expression or null if it
11394// cannot be determined and do all the necessary checks to see if the expression
11395// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000011396// components of the expression.
11397static Expr *CheckMapClauseExpressionBase(
11398 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000011399 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
11400 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011401 SourceLocation ELoc = E->getExprLoc();
11402 SourceRange ERange = E->getSourceRange();
11403
11404 // The base of elements of list in a map clause have to be either:
11405 // - a reference to variable or field.
11406 // - a member expression.
11407 // - an array expression.
11408 //
11409 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
11410 // reference to 'r'.
11411 //
11412 // If we have:
11413 //
11414 // struct SS {
11415 // Bla S;
11416 // foo() {
11417 // #pragma omp target map (S.Arr[:12]);
11418 // }
11419 // }
11420 //
11421 // We want to retrieve the member expression 'this->S';
11422
11423 Expr *RelevantExpr = nullptr;
11424
Samuel Antao5de996e2016-01-22 20:21:36 +000011425 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
11426 // If a list item is an array section, it must specify contiguous storage.
11427 //
11428 // For this restriction it is sufficient that we make sure only references
11429 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011430 // exist except in the rightmost expression (unless they cover the whole
11431 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000011432 //
11433 // r.ArrS[3:5].Arr[6:7]
11434 //
11435 // r.ArrS[3:5].x
11436 //
11437 // but these would be valid:
11438 // r.ArrS[3].Arr[6:7]
11439 //
11440 // r.ArrS[3].x
11441
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011442 bool AllowUnitySizeArraySection = true;
11443 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000011444
Dmitry Polukhin644a9252016-03-11 07:58:34 +000011445 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011446 E = E->IgnoreParenImpCasts();
11447
11448 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
11449 if (!isa<VarDecl>(CurE->getDecl()))
11450 break;
11451
11452 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011453
11454 // If we got a reference to a declaration, we should not expect any array
11455 // section before that.
11456 AllowUnitySizeArraySection = false;
11457 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011458
11459 // Record the component.
11460 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
11461 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000011462 continue;
11463 }
11464
11465 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
11466 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
11467
11468 if (isa<CXXThisExpr>(BaseE))
11469 // We found a base expression: this->Val.
11470 RelevantExpr = CurE;
11471 else
11472 E = BaseE;
11473
11474 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
11475 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11476 << CurE->getSourceRange();
11477 break;
11478 }
11479
11480 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11481
11482 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11483 // A bit-field cannot appear in a map clause.
11484 //
11485 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011486 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11487 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011488 break;
11489 }
11490
11491 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11492 // If the type of a list item is a reference to a type T then the type
11493 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011494 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011495
11496 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11497 // A list item cannot be a variable that is a member of a structure with
11498 // a union type.
11499 //
11500 if (auto *RT = CurType->getAs<RecordType>())
11501 if (RT->isUnionType()) {
11502 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11503 << CurE->getSourceRange();
11504 break;
11505 }
11506
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011507 // If we got a member expression, we should not expect any array section
11508 // before that:
11509 //
11510 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11511 // If a list item is an element of a structure, only the rightmost symbol
11512 // of the variable reference can be an array section.
11513 //
11514 AllowUnitySizeArraySection = false;
11515 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011516
11517 // Record the component.
11518 CurComponents.push_back(
11519 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000011520 continue;
11521 }
11522
11523 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
11524 E = CurE->getBase()->IgnoreParenImpCasts();
11525
11526 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
11527 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11528 << 0 << CurE->getSourceRange();
11529 break;
11530 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011531
11532 // If we got an array subscript that express the whole dimension we
11533 // can have any array expressions before. If it only expressing part of
11534 // the dimension, we can only have unitary-size array expressions.
11535 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
11536 E->getType()))
11537 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011538
11539 // Record the component - we don't have any declaration associated.
11540 CurComponents.push_back(
11541 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000011542 continue;
11543 }
11544
11545 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011546 E = CurE->getBase()->IgnoreParenImpCasts();
11547
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011548 auto CurType =
11549 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11550
Samuel Antao5de996e2016-01-22 20:21:36 +000011551 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11552 // If the type of a list item is a reference to a type T then the type
11553 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000011554 if (CurType->isReferenceType())
11555 CurType = CurType->getPointeeType();
11556
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011557 bool IsPointer = CurType->isAnyPointerType();
11558
11559 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011560 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11561 << 0 << CurE->getSourceRange();
11562 break;
11563 }
11564
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011565 bool NotWhole =
11566 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11567 bool NotUnity =
11568 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11569
Samuel Antaodab51bb2016-07-18 23:22:11 +000011570 if (AllowWholeSizeArraySection) {
11571 // Any array section is currently allowed. Allowing a whole size array
11572 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011573 //
11574 // If this array section refers to the whole dimension we can still
11575 // accept other array sections before this one, except if the base is a
11576 // pointer. Otherwise, only unitary sections are accepted.
11577 if (NotWhole || IsPointer)
11578 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000011579 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011580 // A unity or whole array section is not allowed and that is not
11581 // compatible with the properties of the current array section.
11582 SemaRef.Diag(
11583 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11584 << CurE->getSourceRange();
11585 break;
11586 }
Samuel Antao90927002016-04-26 14:54:23 +000011587
11588 // Record the component - we don't have any declaration associated.
11589 CurComponents.push_back(
11590 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000011591 continue;
11592 }
11593
11594 // If nothing else worked, this is not a valid map clause expression.
11595 SemaRef.Diag(ELoc,
11596 diag::err_omp_expected_named_var_member_or_array_expression)
11597 << ERange;
11598 break;
11599 }
11600
11601 return RelevantExpr;
11602}
11603
11604// Return true if expression E associated with value VD has conflicts with other
11605// map information.
Samuel Antao90927002016-04-26 14:54:23 +000011606static bool CheckMapConflicts(
11607 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
11608 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000011609 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11610 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011611 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000011612 SourceLocation ELoc = E->getExprLoc();
11613 SourceRange ERange = E->getSourceRange();
11614
11615 // In order to easily check the conflicts we need to match each component of
11616 // the expression under test with the components of the expressions that are
11617 // already in the stack.
11618
Samuel Antao5de996e2016-01-22 20:21:36 +000011619 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011620 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011621 "Map clause expression with unexpected base!");
11622
11623 // Variables to help detecting enclosing problems in data environment nests.
11624 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000011625 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011626
Samuel Antao90927002016-04-26 14:54:23 +000011627 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11628 VD, CurrentRegionOnly,
11629 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000011630 StackComponents,
11631 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000011632
Samuel Antao5de996e2016-01-22 20:21:36 +000011633 assert(!StackComponents.empty() &&
11634 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011635 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011636 "Map clause expression with unexpected base!");
11637
Samuel Antao90927002016-04-26 14:54:23 +000011638 // The whole expression in the stack.
11639 auto *RE = StackComponents.front().getAssociatedExpression();
11640
Samuel Antao5de996e2016-01-22 20:21:36 +000011641 // Expressions must start from the same base. Here we detect at which
11642 // point both expressions diverge from each other and see if we can
11643 // detect if the memory referred to both expressions is contiguous and
11644 // do not overlap.
11645 auto CI = CurComponents.rbegin();
11646 auto CE = CurComponents.rend();
11647 auto SI = StackComponents.rbegin();
11648 auto SE = StackComponents.rend();
11649 for (; CI != CE && SI != SE; ++CI, ++SI) {
11650
11651 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
11652 // At most one list item can be an array item derived from a given
11653 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000011654 if (CurrentRegionOnly &&
11655 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
11656 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
11657 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
11658 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
11659 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000011660 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000011661 << CI->getAssociatedExpression()->getSourceRange();
11662 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
11663 diag::note_used_here)
11664 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000011665 return true;
11666 }
11667
11668 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000011669 if (CI->getAssociatedExpression()->getStmtClass() !=
11670 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000011671 break;
11672
11673 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000011674 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000011675 break;
11676 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000011677 // Check if the extra components of the expressions in the enclosing
11678 // data environment are redundant for the current base declaration.
11679 // If they are, the maps completely overlap, which is legal.
11680 for (; SI != SE; ++SI) {
11681 QualType Type;
11682 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000011683 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011684 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000011685 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
11686 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011687 auto *E = OASE->getBase()->IgnoreParenImpCasts();
11688 Type =
11689 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11690 }
11691 if (Type.isNull() || Type->isAnyPointerType() ||
11692 CheckArrayExpressionDoesNotReferToWholeSize(
11693 SemaRef, SI->getAssociatedExpression(), Type))
11694 break;
11695 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011696
11697 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11698 // List items of map clauses in the same construct must not share
11699 // original storage.
11700 //
11701 // If the expressions are exactly the same or one is a subset of the
11702 // other, it means they are sharing storage.
11703 if (CI == CE && SI == SE) {
11704 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000011705 if (CKind == OMPC_map)
11706 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11707 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011708 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011709 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11710 << ERange;
11711 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011712 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11713 << RE->getSourceRange();
11714 return true;
11715 } else {
11716 // If we find the same expression in the enclosing data environment,
11717 // that is legal.
11718 IsEnclosedByDataEnvironmentExpr = true;
11719 return false;
11720 }
11721 }
11722
Samuel Antao90927002016-04-26 14:54:23 +000011723 QualType DerivedType =
11724 std::prev(CI)->getAssociatedDeclaration()->getType();
11725 SourceLocation DerivedLoc =
11726 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000011727
11728 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11729 // If the type of a list item is a reference to a type T then the type
11730 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011731 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011732
11733 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
11734 // A variable for which the type is pointer and an array section
11735 // derived from that variable must not appear as list items of map
11736 // clauses of the same construct.
11737 //
11738 // Also, cover one of the cases in:
11739 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11740 // If any part of the original storage of a list item has corresponding
11741 // storage in the device data environment, all of the original storage
11742 // must have corresponding storage in the device data environment.
11743 //
11744 if (DerivedType->isAnyPointerType()) {
11745 if (CI == CE || SI == SE) {
11746 SemaRef.Diag(
11747 DerivedLoc,
11748 diag::err_omp_pointer_mapped_along_with_derived_section)
11749 << DerivedLoc;
11750 } else {
11751 assert(CI != CE && SI != SE);
11752 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
11753 << DerivedLoc;
11754 }
11755 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11756 << RE->getSourceRange();
11757 return true;
11758 }
11759
11760 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11761 // List items of map clauses in the same construct must not share
11762 // original storage.
11763 //
11764 // An expression is a subset of the other.
11765 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000011766 if (CKind == OMPC_map)
11767 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11768 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011769 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011770 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11771 << ERange;
11772 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011773 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11774 << RE->getSourceRange();
11775 return true;
11776 }
11777
11778 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000011779 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000011780 if (!CurrentRegionOnly && SI != SE)
11781 EnclosingExpr = RE;
11782
11783 // The current expression is a subset of the expression in the data
11784 // environment.
11785 IsEnclosedByDataEnvironmentExpr |=
11786 (!CurrentRegionOnly && CI != CE && SI == SE);
11787
11788 return false;
11789 });
11790
11791 if (CurrentRegionOnly)
11792 return FoundError;
11793
11794 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11795 // If any part of the original storage of a list item has corresponding
11796 // storage in the device data environment, all of the original storage must
11797 // have corresponding storage in the device data environment.
11798 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
11799 // If a list item is an element of a structure, and a different element of
11800 // the structure has a corresponding list item in the device data environment
11801 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000011802 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000011803 // data environment prior to the task encountering the construct.
11804 //
11805 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
11806 SemaRef.Diag(ELoc,
11807 diag::err_omp_original_storage_is_shared_and_does_not_contain)
11808 << ERange;
11809 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
11810 << EnclosingExpr->getSourceRange();
11811 return true;
11812 }
11813
11814 return FoundError;
11815}
11816
Samuel Antao661c0902016-05-26 17:39:58 +000011817namespace {
11818// Utility struct that gathers all the related lists associated with a mappable
11819// expression.
11820struct MappableVarListInfo final {
11821 // The list of expressions.
11822 ArrayRef<Expr *> VarList;
11823 // The list of processed expressions.
11824 SmallVector<Expr *, 16> ProcessedVarList;
11825 // The mappble components for each expression.
11826 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
11827 // The base declaration of the variable.
11828 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
11829
11830 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
11831 // We have a list of components and base declarations for each entry in the
11832 // variable list.
11833 VarComponents.reserve(VarList.size());
11834 VarBaseDeclarations.reserve(VarList.size());
11835 }
11836};
11837}
11838
11839// Check the validity of the provided variable list for the provided clause kind
11840// \a CKind. In the check process the valid expressions, and mappable expression
11841// components and variables are extracted and used to fill \a Vars,
11842// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
11843// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
11844static void
11845checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
11846 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
11847 SourceLocation StartLoc,
11848 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
11849 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011850 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
11851 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000011852 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011853
Samuel Antao90927002016-04-26 14:54:23 +000011854 // Keep track of the mappable components and base declarations in this clause.
11855 // Each entry in the list is going to have a list of components associated. We
11856 // record each set of the components so that we can build the clause later on.
11857 // In the end we should have the same amount of declarations and component
11858 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000011859
Samuel Antao661c0902016-05-26 17:39:58 +000011860 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011861 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011862 SourceLocation ELoc = RE->getExprLoc();
11863
Kelvin Li0bff7af2015-11-23 05:32:03 +000011864 auto *VE = RE->IgnoreParenLValueCasts();
11865
11866 if (VE->isValueDependent() || VE->isTypeDependent() ||
11867 VE->isInstantiationDependent() ||
11868 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011869 // We can only analyze this information once the missing information is
11870 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000011871 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011872 continue;
11873 }
11874
11875 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011876
Samuel Antao5de996e2016-01-22 20:21:36 +000011877 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011878 SemaRef.Diag(ELoc,
11879 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000011880 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011881 continue;
11882 }
11883
Samuel Antao90927002016-04-26 14:54:23 +000011884 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
11885 ValueDecl *CurDeclaration = nullptr;
11886
11887 // Obtain the array or member expression bases if required. Also, fill the
11888 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000011889 auto *BE =
11890 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011891 if (!BE)
11892 continue;
11893
Samuel Antao90927002016-04-26 14:54:23 +000011894 assert(!CurComponents.empty() &&
11895 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011896
Samuel Antao90927002016-04-26 14:54:23 +000011897 // For the following checks, we rely on the base declaration which is
11898 // expected to be associated with the last component. The declaration is
11899 // expected to be a variable or a field (if 'this' is being mapped).
11900 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
11901 assert(CurDeclaration && "Null decl on map clause.");
11902 assert(
11903 CurDeclaration->isCanonicalDecl() &&
11904 "Expecting components to have associated only canonical declarations.");
11905
11906 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
11907 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000011908
11909 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000011910 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000011911
11912 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000011913 // threadprivate variables cannot appear in a map clause.
11914 // OpenMP 4.5 [2.10.5, target update Construct]
11915 // threadprivate variables cannot appear in a from clause.
11916 if (VD && DSAS->isThreadPrivate(VD)) {
11917 auto DVar = DSAS->getTopDSA(VD, false);
11918 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
11919 << getOpenMPClauseName(CKind);
11920 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011921 continue;
11922 }
11923
Samuel Antao5de996e2016-01-22 20:21:36 +000011924 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
11925 // A list item cannot appear in both a map clause and a data-sharing
11926 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000011927
Samuel Antao5de996e2016-01-22 20:21:36 +000011928 // Check conflicts with other map clause expressions. We check the conflicts
11929 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000011930 // environment, because the restrictions are different. We only have to
11931 // check conflicts across regions for the map clauses.
11932 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11933 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011934 break;
Samuel Antao661c0902016-05-26 17:39:58 +000011935 if (CKind == OMPC_map &&
11936 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11937 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011938 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011939
Samuel Antao661c0902016-05-26 17:39:58 +000011940 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000011941 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11942 // If the type of a list item is a reference to a type T then the type will
11943 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011944 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011945
Samuel Antao661c0902016-05-26 17:39:58 +000011946 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
11947 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000011948 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000011949 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000011950 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
11951 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000011952 continue;
11953
Samuel Antao661c0902016-05-26 17:39:58 +000011954 if (CKind == OMPC_map) {
11955 // target enter data
11956 // OpenMP [2.10.2, Restrictions, p. 99]
11957 // A map-type must be specified in all map clauses and must be either
11958 // to or alloc.
11959 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
11960 if (DKind == OMPD_target_enter_data &&
11961 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
11962 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11963 << (IsMapTypeImplicit ? 1 : 0)
11964 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11965 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011966 continue;
11967 }
Samuel Antao661c0902016-05-26 17:39:58 +000011968
11969 // target exit_data
11970 // OpenMP [2.10.3, Restrictions, p. 102]
11971 // A map-type must be specified in all map clauses and must be either
11972 // from, release, or delete.
11973 if (DKind == OMPD_target_exit_data &&
11974 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
11975 MapType == OMPC_MAP_delete)) {
11976 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11977 << (IsMapTypeImplicit ? 1 : 0)
11978 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11979 << getOpenMPDirectiveName(DKind);
11980 continue;
11981 }
11982
11983 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11984 // A list item cannot appear in both a map clause and a data-sharing
11985 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000011986 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000011987 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000011988 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000011989 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
11990 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000011991 auto DVar = DSAS->getTopDSA(VD, false);
11992 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000011993 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000011994 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000011995 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000011996 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
11997 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
11998 continue;
11999 }
12000 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012001 }
12002
Samuel Antao90927002016-04-26 14:54:23 +000012003 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000012004 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000012005
12006 // Store the components in the stack so that they can be used to check
12007 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000012008 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
12009 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000012010
12011 // Save the components and declaration to create the clause. For purposes of
12012 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000012013 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000012014 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12015 MVLI.VarComponents.back().append(CurComponents.begin(),
12016 CurComponents.end());
12017 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
12018 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012019 }
Samuel Antao661c0902016-05-26 17:39:58 +000012020}
12021
12022OMPClause *
12023Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
12024 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
12025 SourceLocation MapLoc, SourceLocation ColonLoc,
12026 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12027 SourceLocation LParenLoc, SourceLocation EndLoc) {
12028 MappableVarListInfo MVLI(VarList);
12029 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
12030 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012031
Samuel Antao5de996e2016-01-22 20:21:36 +000012032 // We need to produce a map clause even if we don't have variables so that
12033 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000012034 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12035 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12036 MVLI.VarComponents, MapTypeModifier, MapType,
12037 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012038}
Kelvin Li099bb8c2015-11-24 20:50:12 +000012039
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012040QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
12041 TypeResult ParsedType) {
12042 assert(ParsedType.isUsable());
12043
12044 QualType ReductionType = GetTypeFromParser(ParsedType.get());
12045 if (ReductionType.isNull())
12046 return QualType();
12047
12048 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
12049 // A type name in a declare reduction directive cannot be a function type, an
12050 // array type, a reference type, or a type qualified with const, volatile or
12051 // restrict.
12052 if (ReductionType.hasQualifiers()) {
12053 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
12054 return QualType();
12055 }
12056
12057 if (ReductionType->isFunctionType()) {
12058 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
12059 return QualType();
12060 }
12061 if (ReductionType->isReferenceType()) {
12062 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
12063 return QualType();
12064 }
12065 if (ReductionType->isArrayType()) {
12066 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
12067 return QualType();
12068 }
12069 return ReductionType;
12070}
12071
12072Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
12073 Scope *S, DeclContext *DC, DeclarationName Name,
12074 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
12075 AccessSpecifier AS, Decl *PrevDeclInScope) {
12076 SmallVector<Decl *, 8> Decls;
12077 Decls.reserve(ReductionTypes.size());
12078
12079 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000012080 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012081 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
12082 // A reduction-identifier may not be re-declared in the current scope for the
12083 // same type or for a type that is compatible according to the base language
12084 // rules.
12085 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
12086 OMPDeclareReductionDecl *PrevDRD = nullptr;
12087 bool InCompoundScope = true;
12088 if (S != nullptr) {
12089 // Find previous declaration with the same name not referenced in other
12090 // declarations.
12091 FunctionScopeInfo *ParentFn = getEnclosingFunction();
12092 InCompoundScope =
12093 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
12094 LookupName(Lookup, S);
12095 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
12096 /*AllowInlineNamespace=*/false);
12097 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
12098 auto Filter = Lookup.makeFilter();
12099 while (Filter.hasNext()) {
12100 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
12101 if (InCompoundScope) {
12102 auto I = UsedAsPrevious.find(PrevDecl);
12103 if (I == UsedAsPrevious.end())
12104 UsedAsPrevious[PrevDecl] = false;
12105 if (auto *D = PrevDecl->getPrevDeclInScope())
12106 UsedAsPrevious[D] = true;
12107 }
12108 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
12109 PrevDecl->getLocation();
12110 }
12111 Filter.done();
12112 if (InCompoundScope) {
12113 for (auto &PrevData : UsedAsPrevious) {
12114 if (!PrevData.second) {
12115 PrevDRD = PrevData.first;
12116 break;
12117 }
12118 }
12119 }
12120 } else if (PrevDeclInScope != nullptr) {
12121 auto *PrevDRDInScope = PrevDRD =
12122 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
12123 do {
12124 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
12125 PrevDRDInScope->getLocation();
12126 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
12127 } while (PrevDRDInScope != nullptr);
12128 }
12129 for (auto &TyData : ReductionTypes) {
12130 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
12131 bool Invalid = false;
12132 if (I != PreviousRedeclTypes.end()) {
12133 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
12134 << TyData.first;
12135 Diag(I->second, diag::note_previous_definition);
12136 Invalid = true;
12137 }
12138 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
12139 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
12140 Name, TyData.first, PrevDRD);
12141 DC->addDecl(DRD);
12142 DRD->setAccess(AS);
12143 Decls.push_back(DRD);
12144 if (Invalid)
12145 DRD->setInvalidDecl();
12146 else
12147 PrevDRD = DRD;
12148 }
12149
12150 return DeclGroupPtrTy::make(
12151 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
12152}
12153
12154void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
12155 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12156
12157 // Enter new function scope.
12158 PushFunctionScope();
12159 getCurFunction()->setHasBranchProtectedScope();
12160 getCurFunction()->setHasOMPDeclareReductionCombiner();
12161
12162 if (S != nullptr)
12163 PushDeclContext(S, DRD);
12164 else
12165 CurContext = DRD;
12166
Faisal Valid143a0c2017-04-01 21:30:49 +000012167 PushExpressionEvaluationContext(
12168 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012169
12170 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012171 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
12172 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
12173 // uses semantics of argument handles by value, but it should be passed by
12174 // reference. C lang does not support references, so pass all parameters as
12175 // pointers.
12176 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012177 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012178 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012179 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
12180 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
12181 // uses semantics of argument handles by value, but it should be passed by
12182 // reference. C lang does not support references, so pass all parameters as
12183 // pointers.
12184 // Create 'T omp_out;' variable.
12185 auto *OmpOutParm =
12186 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
12187 if (S != nullptr) {
12188 PushOnScopeChains(OmpInParm, S);
12189 PushOnScopeChains(OmpOutParm, S);
12190 } else {
12191 DRD->addDecl(OmpInParm);
12192 DRD->addDecl(OmpOutParm);
12193 }
12194}
12195
12196void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
12197 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12198 DiscardCleanupsInEvaluationContext();
12199 PopExpressionEvaluationContext();
12200
12201 PopDeclContext();
12202 PopFunctionScopeInfo();
12203
12204 if (Combiner != nullptr)
12205 DRD->setCombiner(Combiner);
12206 else
12207 DRD->setInvalidDecl();
12208}
12209
Alexey Bataev070f43a2017-09-06 14:49:58 +000012210VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012211 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12212
12213 // Enter new function scope.
12214 PushFunctionScope();
12215 getCurFunction()->setHasBranchProtectedScope();
12216
12217 if (S != nullptr)
12218 PushDeclContext(S, DRD);
12219 else
12220 CurContext = DRD;
12221
Faisal Valid143a0c2017-04-01 21:30:49 +000012222 PushExpressionEvaluationContext(
12223 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012224
12225 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012226 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
12227 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
12228 // uses semantics of argument handles by value, but it should be passed by
12229 // reference. C lang does not support references, so pass all parameters as
12230 // pointers.
12231 // Create 'T omp_priv;' variable.
12232 auto *OmpPrivParm =
12233 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012234 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
12235 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
12236 // uses semantics of argument handles by value, but it should be passed by
12237 // reference. C lang does not support references, so pass all parameters as
12238 // pointers.
12239 // Create 'T omp_orig;' variable.
12240 auto *OmpOrigParm =
12241 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012242 if (S != nullptr) {
12243 PushOnScopeChains(OmpPrivParm, S);
12244 PushOnScopeChains(OmpOrigParm, S);
12245 } else {
12246 DRD->addDecl(OmpPrivParm);
12247 DRD->addDecl(OmpOrigParm);
12248 }
Alexey Bataev070f43a2017-09-06 14:49:58 +000012249 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012250}
12251
Alexey Bataev070f43a2017-09-06 14:49:58 +000012252void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
12253 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012254 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12255 DiscardCleanupsInEvaluationContext();
12256 PopExpressionEvaluationContext();
12257
12258 PopDeclContext();
12259 PopFunctionScopeInfo();
12260
Alexey Bataev070f43a2017-09-06 14:49:58 +000012261 if (Initializer != nullptr) {
12262 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
12263 } else if (OmpPrivParm->hasInit()) {
12264 DRD->setInitializer(OmpPrivParm->getInit(),
12265 OmpPrivParm->isDirectInit()
12266 ? OMPDeclareReductionDecl::DirectInit
12267 : OMPDeclareReductionDecl::CopyInit);
12268 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012269 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000012270 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012271}
12272
12273Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
12274 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
12275 for (auto *D : DeclReductions.get()) {
12276 if (IsValid) {
12277 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12278 if (S != nullptr)
12279 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
12280 } else
12281 D->setInvalidDecl();
12282 }
12283 return DeclReductions;
12284}
12285
David Majnemer9d168222016-08-05 17:44:54 +000012286OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000012287 SourceLocation StartLoc,
12288 SourceLocation LParenLoc,
12289 SourceLocation EndLoc) {
12290 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012291 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012292
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012293 // OpenMP [teams Constrcut, Restrictions]
12294 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012295 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
12296 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012297 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012298
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012299 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012300 OpenMPDirectiveKind CaptureRegion =
12301 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
12302 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012303 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12304 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12305 HelperValStmt = buildPreInits(Context, Captures);
12306 }
12307
12308 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
12309 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000012310}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012311
12312OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12313 SourceLocation StartLoc,
12314 SourceLocation LParenLoc,
12315 SourceLocation EndLoc) {
12316 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012317 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012318
12319 // OpenMP [teams Constrcut, Restrictions]
12320 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012321 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
12322 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012323 return nullptr;
12324
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012325 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012326 OpenMPDirectiveKind CaptureRegion =
12327 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
12328 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012329 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12330 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12331 HelperValStmt = buildPreInits(Context, Captures);
12332 }
12333
12334 return new (Context) OMPThreadLimitClause(
12335 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012336}
Alexey Bataeva0569352015-12-01 10:17:31 +000012337
12338OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
12339 SourceLocation StartLoc,
12340 SourceLocation LParenLoc,
12341 SourceLocation EndLoc) {
12342 Expr *ValExpr = Priority;
12343
12344 // OpenMP [2.9.1, task Constrcut]
12345 // The priority-value is a non-negative numerical scalar expression.
12346 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
12347 /*StrictlyPositive=*/false))
12348 return nullptr;
12349
12350 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12351}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012352
12353OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
12354 SourceLocation StartLoc,
12355 SourceLocation LParenLoc,
12356 SourceLocation EndLoc) {
12357 Expr *ValExpr = Grainsize;
12358
12359 // OpenMP [2.9.2, taskloop Constrcut]
12360 // The parameter of the grainsize clause must be a positive integer
12361 // expression.
12362 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
12363 /*StrictlyPositive=*/true))
12364 return nullptr;
12365
12366 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12367}
Alexey Bataev382967a2015-12-08 12:06:20 +000012368
12369OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
12370 SourceLocation StartLoc,
12371 SourceLocation LParenLoc,
12372 SourceLocation EndLoc) {
12373 Expr *ValExpr = NumTasks;
12374
12375 // OpenMP [2.9.2, taskloop Constrcut]
12376 // The parameter of the num_tasks clause must be a positive integer
12377 // expression.
12378 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
12379 /*StrictlyPositive=*/true))
12380 return nullptr;
12381
12382 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12383}
12384
Alexey Bataev28c75412015-12-15 08:19:24 +000012385OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
12386 SourceLocation LParenLoc,
12387 SourceLocation EndLoc) {
12388 // OpenMP [2.13.2, critical construct, Description]
12389 // ... where hint-expression is an integer constant expression that evaluates
12390 // to a valid lock hint.
12391 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
12392 if (HintExpr.isInvalid())
12393 return nullptr;
12394 return new (Context)
12395 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
12396}
12397
Carlo Bertollib4adf552016-01-15 18:50:31 +000012398OMPClause *Sema::ActOnOpenMPDistScheduleClause(
12399 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
12400 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
12401 SourceLocation EndLoc) {
12402 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
12403 std::string Values;
12404 Values += "'";
12405 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
12406 Values += "'";
12407 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12408 << Values << getOpenMPClauseName(OMPC_dist_schedule);
12409 return nullptr;
12410 }
12411 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012412 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012413 if (ChunkSize) {
12414 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12415 !ChunkSize->isInstantiationDependent() &&
12416 !ChunkSize->containsUnexpandedParameterPack()) {
12417 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
12418 ExprResult Val =
12419 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12420 if (Val.isInvalid())
12421 return nullptr;
12422
12423 ValExpr = Val.get();
12424
12425 // OpenMP [2.7.1, Restrictions]
12426 // chunk_size must be a loop invariant integer expression with a positive
12427 // value.
12428 llvm::APSInt Result;
12429 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12430 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12431 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
12432 << "dist_schedule" << ChunkSize->getSourceRange();
12433 return nullptr;
12434 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012435 } else if (getOpenMPCaptureRegionForClause(
12436 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
12437 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012438 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000012439 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12440 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12441 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012442 }
12443 }
12444 }
12445
12446 return new (Context)
12447 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000012448 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012449}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012450
12451OMPClause *Sema::ActOnOpenMPDefaultmapClause(
12452 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12453 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12454 SourceLocation KindLoc, SourceLocation EndLoc) {
12455 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000012456 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012457 std::string Value;
12458 SourceLocation Loc;
12459 Value += "'";
12460 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12461 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012462 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012463 Loc = MLoc;
12464 } else {
12465 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012466 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012467 Loc = KindLoc;
12468 }
12469 Value += "'";
12470 Diag(Loc, diag::err_omp_unexpected_clause_value)
12471 << Value << getOpenMPClauseName(OMPC_defaultmap);
12472 return nullptr;
12473 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000012474 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012475
12476 return new (Context)
12477 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12478}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012479
12480bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12481 DeclContext *CurLexicalContext = getCurLexicalContext();
12482 if (!CurLexicalContext->isFileContext() &&
12483 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000012484 !CurLexicalContext->isExternCXXContext() &&
12485 !isa<CXXRecordDecl>(CurLexicalContext) &&
12486 !isa<ClassTemplateDecl>(CurLexicalContext) &&
12487 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12488 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012489 Diag(Loc, diag::err_omp_region_not_file_context);
12490 return false;
12491 }
12492 if (IsInOpenMPDeclareTargetContext) {
12493 Diag(Loc, diag::err_omp_enclosed_declare_target);
12494 return false;
12495 }
12496
12497 IsInOpenMPDeclareTargetContext = true;
12498 return true;
12499}
12500
12501void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12502 assert(IsInOpenMPDeclareTargetContext &&
12503 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
12504
12505 IsInOpenMPDeclareTargetContext = false;
12506}
12507
David Majnemer9d168222016-08-05 17:44:54 +000012508void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12509 CXXScopeSpec &ScopeSpec,
12510 const DeclarationNameInfo &Id,
12511 OMPDeclareTargetDeclAttr::MapTypeTy MT,
12512 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012513 LookupResult Lookup(*this, Id, LookupOrdinaryName);
12514 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12515
12516 if (Lookup.isAmbiguous())
12517 return;
12518 Lookup.suppressDiagnostics();
12519
12520 if (!Lookup.isSingleResult()) {
12521 if (TypoCorrection Corrected =
12522 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12523 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12524 CTK_ErrorRecovery)) {
12525 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12526 << Id.getName());
12527 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12528 return;
12529 }
12530
12531 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12532 return;
12533 }
12534
12535 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12536 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12537 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12538 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
12539
12540 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
12541 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
12542 ND->addAttr(A);
12543 if (ASTMutationListener *ML = Context.getASTMutationListener())
12544 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
12545 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
12546 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12547 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12548 << Id.getName();
12549 }
12550 } else
12551 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12552}
12553
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012554static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12555 Sema &SemaRef, Decl *D) {
12556 if (!D)
12557 return;
12558 Decl *LD = nullptr;
12559 if (isa<TagDecl>(D)) {
12560 LD = cast<TagDecl>(D)->getDefinition();
12561 } else if (isa<VarDecl>(D)) {
12562 LD = cast<VarDecl>(D)->getDefinition();
12563
12564 // If this is an implicit variable that is legal and we do not need to do
12565 // anything.
12566 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012567 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12568 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12569 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012570 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012571 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012572 return;
12573 }
12574
12575 } else if (isa<FunctionDecl>(D)) {
12576 const FunctionDecl *FD = nullptr;
12577 if (cast<FunctionDecl>(D)->hasBody(FD))
12578 LD = const_cast<FunctionDecl *>(FD);
12579
12580 // If the definition is associated with the current declaration in the
12581 // target region (it can be e.g. a lambda) that is legal and we do not need
12582 // to do anything else.
12583 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012584 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12585 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12586 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012587 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012588 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012589 return;
12590 }
12591 }
12592 if (!LD)
12593 LD = D;
12594 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12595 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
12596 // Outlined declaration is not declared target.
12597 if (LD->isOutOfLine()) {
12598 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12599 SemaRef.Diag(SL, diag::note_used_here) << SR;
12600 } else {
12601 DeclContext *DC = LD->getDeclContext();
12602 while (DC) {
12603 if (isa<FunctionDecl>(DC) &&
12604 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
12605 break;
12606 DC = DC->getParent();
12607 }
12608 if (DC)
12609 return;
12610
12611 // Is not declared in target context.
12612 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12613 SemaRef.Diag(SL, diag::note_used_here) << SR;
12614 }
12615 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012616 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12617 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12618 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012619 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012620 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012621 }
12622}
12623
12624static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12625 Sema &SemaRef, DSAStackTy *Stack,
12626 ValueDecl *VD) {
12627 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
12628 return true;
12629 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
12630 return false;
12631 return true;
12632}
12633
12634void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
12635 if (!D || D->isInvalidDecl())
12636 return;
12637 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
12638 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
12639 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
12640 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12641 if (DSAStack->isThreadPrivate(VD)) {
12642 Diag(SL, diag::err_omp_threadprivate_in_target);
12643 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
12644 return;
12645 }
12646 }
12647 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
12648 // Problem if any with var declared with incomplete type will be reported
12649 // as normal, so no need to check it here.
12650 if ((E || !VD->getType()->isIncompleteType()) &&
12651 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
12652 // Mark decl as declared target to prevent further diagnostic.
12653 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012654 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12655 Context, OMPDeclareTargetDeclAttr::MT_To);
12656 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012657 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012658 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012659 }
12660 return;
12661 }
12662 }
12663 if (!E) {
12664 // Checking declaration inside declare target region.
12665 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
12666 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012667 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12668 Context, OMPDeclareTargetDeclAttr::MT_To);
12669 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012670 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012671 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012672 }
12673 return;
12674 }
12675 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
12676}
Samuel Antao661c0902016-05-26 17:39:58 +000012677
12678OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
12679 SourceLocation StartLoc,
12680 SourceLocation LParenLoc,
12681 SourceLocation EndLoc) {
12682 MappableVarListInfo MVLI(VarList);
12683 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
12684 if (MVLI.ProcessedVarList.empty())
12685 return nullptr;
12686
12687 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12688 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12689 MVLI.VarComponents);
12690}
Samuel Antaoec172c62016-05-26 17:49:04 +000012691
12692OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
12693 SourceLocation StartLoc,
12694 SourceLocation LParenLoc,
12695 SourceLocation EndLoc) {
12696 MappableVarListInfo MVLI(VarList);
12697 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
12698 if (MVLI.ProcessedVarList.empty())
12699 return nullptr;
12700
12701 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12702 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12703 MVLI.VarComponents);
12704}
Carlo Bertolli2404b172016-07-13 15:37:16 +000012705
12706OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
12707 SourceLocation StartLoc,
12708 SourceLocation LParenLoc,
12709 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000012710 MappableVarListInfo MVLI(VarList);
12711 SmallVector<Expr *, 8> PrivateCopies;
12712 SmallVector<Expr *, 8> Inits;
12713
Carlo Bertolli2404b172016-07-13 15:37:16 +000012714 for (auto &RefExpr : VarList) {
12715 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
12716 SourceLocation ELoc;
12717 SourceRange ERange;
12718 Expr *SimpleRefExpr = RefExpr;
12719 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12720 if (Res.second) {
12721 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000012722 MVLI.ProcessedVarList.push_back(RefExpr);
12723 PrivateCopies.push_back(nullptr);
12724 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012725 }
12726 ValueDecl *D = Res.first;
12727 if (!D)
12728 continue;
12729
12730 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000012731 Type = Type.getNonReferenceType().getUnqualifiedType();
12732
12733 auto *VD = dyn_cast<VarDecl>(D);
12734
12735 // Item should be a pointer or reference to pointer.
12736 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000012737 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
12738 << 0 << RefExpr->getSourceRange();
12739 continue;
12740 }
Samuel Antaocc10b852016-07-28 14:23:26 +000012741
12742 // Build the private variable and the expression that refers to it.
12743 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
12744 D->hasAttrs() ? &D->getAttrs() : nullptr);
12745 if (VDPrivate->isInvalidDecl())
12746 continue;
12747
12748 CurContext->addDecl(VDPrivate);
12749 auto VDPrivateRefExpr = buildDeclRefExpr(
12750 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
12751
12752 // Add temporary variable to initialize the private copy of the pointer.
12753 auto *VDInit =
12754 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
12755 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12756 RefExpr->getExprLoc());
12757 AddInitializerToDecl(VDPrivate,
12758 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012759 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000012760
12761 // If required, build a capture to implement the privatization initialized
12762 // with the current list item value.
12763 DeclRefExpr *Ref = nullptr;
12764 if (!VD)
12765 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12766 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
12767 PrivateCopies.push_back(VDPrivateRefExpr);
12768 Inits.push_back(VDInitRefExpr);
12769
12770 // We need to add a data sharing attribute for this variable to make sure it
12771 // is correctly captured. A variable that shows up in a use_device_ptr has
12772 // similar properties of a first private variable.
12773 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
12774
12775 // Create a mappable component for the list item. List items in this clause
12776 // only need a component.
12777 MVLI.VarBaseDeclarations.push_back(D);
12778 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12779 MVLI.VarComponents.back().push_back(
12780 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000012781 }
12782
Samuel Antaocc10b852016-07-28 14:23:26 +000012783 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000012784 return nullptr;
12785
Samuel Antaocc10b852016-07-28 14:23:26 +000012786 return OMPUseDevicePtrClause::Create(
12787 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12788 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012789}
Carlo Bertolli70594e92016-07-13 17:16:49 +000012790
12791OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
12792 SourceLocation StartLoc,
12793 SourceLocation LParenLoc,
12794 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000012795 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012796 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000012797 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000012798 SourceLocation ELoc;
12799 SourceRange ERange;
12800 Expr *SimpleRefExpr = RefExpr;
12801 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12802 if (Res.second) {
12803 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000012804 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012805 }
12806 ValueDecl *D = Res.first;
12807 if (!D)
12808 continue;
12809
12810 QualType Type = D->getType();
12811 // item should be a pointer or array or reference to pointer or array
12812 if (!Type.getNonReferenceType()->isPointerType() &&
12813 !Type.getNonReferenceType()->isArrayType()) {
12814 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
12815 << 0 << RefExpr->getSourceRange();
12816 continue;
12817 }
Samuel Antao6890b092016-07-28 14:25:09 +000012818
12819 // Check if the declaration in the clause does not show up in any data
12820 // sharing attribute.
12821 auto DVar = DSAStack->getTopDSA(D, false);
12822 if (isOpenMPPrivate(DVar.CKind)) {
12823 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12824 << getOpenMPClauseName(DVar.CKind)
12825 << getOpenMPClauseName(OMPC_is_device_ptr)
12826 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12827 ReportOriginalDSA(*this, DSAStack, D, DVar);
12828 continue;
12829 }
12830
12831 Expr *ConflictExpr;
12832 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012833 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012834 [&ConflictExpr](
12835 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
12836 OpenMPClauseKind) -> bool {
12837 ConflictExpr = R.front().getAssociatedExpression();
12838 return true;
12839 })) {
12840 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
12841 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
12842 << ConflictExpr->getSourceRange();
12843 continue;
12844 }
12845
12846 // Store the components in the stack so that they can be used to check
12847 // against other clauses later on.
12848 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
12849 DSAStack->addMappableExpressionComponents(
12850 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
12851
12852 // Record the expression we've just processed.
12853 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
12854
12855 // Create a mappable component for the list item. List items in this clause
12856 // only need a component. We use a null declaration to signal fields in
12857 // 'this'.
12858 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
12859 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
12860 "Unexpected device pointer expression!");
12861 MVLI.VarBaseDeclarations.push_back(
12862 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
12863 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12864 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012865 }
12866
Samuel Antao6890b092016-07-28 14:25:09 +000012867 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000012868 return nullptr;
12869
Samuel Antao6890b092016-07-28 14:25:09 +000012870 return OMPIsDevicePtrClause::Create(
12871 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12872 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012873}